diff --git a/README.md b/README.md index b99faccb..fa4cf3b3 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ [![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) > ["For coding interview preparation, LeetCode is one of the best online resource providing a rich library of more than 300 real coding interview questions for you to practice from using one of the 7 supported languages - C, C++, Java, Python, C#, JavaScript, Ruby."](https://www.quora.com/How-effective-is-Leetcode-for-preparing-for-technical-interviews) +* [Level 2](#level-2) +* [Udemy](#udemy) * [Data Structure I](#data-structure-i) * [Data Structure II](#data-structure-ii) * [Algorithm I](#algorithm-i) @@ -14,762 +16,1121 @@ * [Graph Theory I](#graph-theory-i) * [SQL I](#sql-i) * [Level 1](#level-1) -* [Level 2](#level-2) -* [Udemy](#udemy) -### Data Structure I +### Level 2 -#### Day 1 Array +#### Day 1 Implementation/Simulation | | | | | | |-|-|-|-|-|- -| 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 -| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 +| 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 +| 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 224 | 62.50 -#### Day 2 Array +#### Day 2 String | | | | | | |-|-|-|-|-|- -| 0001 |[Two Sum](src/main/kotlin/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 234 | 92.75 -| 0088 |[Merge Sorted Array](src/main/kotlin/g0001_0100/s0088_merge_sorted_array)| Easy | Top_Interview_Questions, Array, Sorting, Two_Pointers | 311 | 33.40 +| 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String | 209 | 88.86 +| 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 390 | 56.25 -#### Day 3 Array +#### Day 3 Linked List | | | | | | |-|-|-|-|-|- -| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 321 | 73.37 -| 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 609 | 94.06 +| 0019 |[Remove Nth Node From End of List](src/main/kotlin/g0001_0100/s0019_remove_nth_node_from_end_of_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Linked_List | 180 | 91.58 +| 0234 |[Palindrome Linked List](src/main/kotlin/g0201_0300/s0234_palindrome_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Stack, Linked_List, Recursion | 641 | 79.53 -#### Day 4 Array +#### Day 4 Linked List | | | | | | |-|-|-|-|-|- -| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 239 | 99.05 -| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 +| 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List | 216 | 86.96 +| 0148 |[Sort List](src/main/kotlin/g0101_0200/s0148_sort_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Sorting, Two_Pointers, Linked_List, Divide_and_Conquer, Merge_Sort | 820 | 61.70 -#### Day 5 Array +#### Day 5 Greedy | | | | | | |-|-|-|-|-|- -| 0036 |[Valid Sudoku](src/main/kotlin/g0001_0100/s0036_valid_sudoku)| Medium | Top_Interview_Questions, Array, Hash_Table, Matrix | 346 | 65.03 -| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 +| 0621 |[Task Scheduler](src/main/kotlin/g0601_0700/s0621_task_scheduler)| Medium | Array, Hash_Table, Sorting, Greedy, Heap_Priority_Queue, Counting | 266 | 98.36 -#### Day 6 String +#### Day 6 Tree | | | | | | |-|-|-|-|-|- -| 0387 |[First Unique Character in a String](src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string)| Easy | Top_Interview_Questions, String, Hash_Table, Counting, Queue | 369 | 82.68 -| 0383 |[Ransom Note](src/main/kotlin/g0301_0400/s0383_ransom_note)| Easy | String, Hash_Table, Counting | 333 | 79.58 -| 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 +| 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 +| 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 310 | 63.63 -#### Day 7 Linked List +#### Day 7 Tree | | | | | | |-|-|-|-|-|- -| 0141 |[Linked List Cycle](src/main/kotlin/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 223 | 91.85 -| 0021 |[Merge Two Sorted Lists](src/main/kotlin/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 176 | 96.25 -| 0203 |[Remove Linked List Elements](src/main/kotlin/g0201_0300/s0203_remove_linked_list_elements)| Easy | Linked_List, Recursion | 233 | 91.22 +| 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 307 | 43.93 +| 0437 |[Path Sum III](src/main/kotlin/g0401_0500/s0437_path_sum_iii)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 403 | 54.12 -#### Day 8 Linked List +#### Day 8 Binary Search | | | | | | |-|-|-|-|-|- -| 0206 |[Reverse Linked List](src/main/kotlin/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 279 | 45.78 -| 0083 |[Remove Duplicates from Sorted List](src/main/kotlin/g0001_0100/s0083_remove_duplicates_from_sorted_list)| Easy | Linked_List | 274 | 77.82 +| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 +| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 -#### Day 9 Stack Queue +#### Day 9 Binary Search Tree | | | | | | |-|-|-|-|-|- -| 0020 |[Valid Parentheses](src/main/kotlin/g0001_0100/s0020_valid_parentheses)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, String, Stack | 226 | 72.53 -| 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 +| 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 +| 0230 |[Kth Smallest Element in a BST](src/main/kotlin/g0201_0300/s0230_kth_smallest_element_in_a_bst)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 393 | 33.33 +| 0173 |[Binary Search Tree Iterator](src/main/kotlin/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 563 | 46.91 -#### Day 10 Tree +#### Day 10 Graph/BFS/DFS | | | | | | |-|-|-|-|-|- -| 0144 |[Binary Tree Preorder Traversal](src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 277 | 37.90 -| 0094 |[Binary Tree Inorder Traversal](src/main/kotlin/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 269 | 38.80 -| 0145 |[Binary Tree Postorder Traversal](src/main/kotlin/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 211 | 80.00 +| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 164 | 82.95 +| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 -#### Day 11 Tree +#### Day 11 Graph/BFS/DFS | | | | | | |-|-|-|-|-|- -| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 -| 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 236 | 83.39 -| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 91.36 +| 0210 |[Course Schedule II](src/main/kotlin/g0201_0300/s0210_course_schedule_ii)| Medium | Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Graph, Topological_Sort | 266 | 96.32 +| 0815 |[Bus Routes](src/main/kotlin/g0801_0900/s0815_bus_routes)| Hard | Array, Hash_Table, Breadth_First_Search | 429 | 100.00 -#### Day 12 Tree +#### Day 12 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 -| 0112 |[Path Sum](src/main/kotlin/g0101_0200/s0112_path_sum)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 322 | 36.41 +| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 +| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search | 332 | 50.68 -#### Day 13 Tree +#### Day 13 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0700 |[Search in a Binary Search Tree](src/main/kotlin/g0601_0700/s0700_search_in_a_binary_search_tree)| Easy | Tree, Binary_Tree, Binary_Search_Tree | 251 | 88.31 -| 0701 |[Insert into a Binary Search Tree](src/main/kotlin/g0701_0800/s0701_insert_into_a_binary_search_tree)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 311 | 79.03 +| 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming | 204 | 98.82 +| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 -#### Day 14 Tree +#### Day 14 Sliding Window/Two Pointer | | | | | | |-|-|-|-|-|- -| 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 -| 0653 |[Two Sum IV - Input is a BST](src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree | 231 | 96.08 -| 0235 |[Lowest Common Ancestor of a Binary Search Tree](src/main/kotlin/g0201_0300/s0235_lowest_common_ancestor_of_a_binary_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 404 | 75.59 - -### Data Structure II +| 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 +| 0016 |[3Sum Closest](src/main/kotlin/g0001_0100/s0016_3sum_closest)| Medium | Array, Sorting, Two_Pointers | 413 | 95.05 +| 0076 |[Minimum Window Substring](src/main/kotlin/g0001_0100/s0076_minimum_window_substring)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 346 | 85.20 -#### Day 1 Array +#### Day 15 Tree | | | | | | |-|-|-|-|-|- -| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 -| 0169 |[Majority Element](src/main/kotlin/g0101_0200/s0169_majority_element)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Counting, Divide_and_Conquer | 460 | 51.25 -| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 761 | 90.55 +| 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 +| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 91.36 +| 0199 |[Binary Tree Right Side View](src/main/kotlin/g0101_0200/s0199_binary_tree_right_side_view)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 194 | 92.89 -#### Day 2 Array +#### Day 16 Design | | | | | | |-|-|-|-|-|- -| 0075 |[Sort Colors](src/main/kotlin/g0001_0100/s0075_sort_colors)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 198 | 85.66 -| 0056 |[Merge Intervals](src/main/kotlin/g0001_0100/s0056_merge_intervals)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting | 320 | 94.22 -| 0706 |[Design HashMap](src/main/kotlin/g0701_0800/s0706_design_hashmap)| Easy | Array, Hash_Table, Design, Linked_List, Hash_Function | 405 | 92.11 +| 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 +| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 +| 0208 |[Implement Trie (Prefix Tree)](src/main/kotlin/g0201_0300/s0208_implement_trie_prefix_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Design, Trie | 689 | 61.00 -#### Day 3 Array +#### Day 17 Interval | | | | | | |-|-|-|-|-|- -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 -| 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix | 287 | 46.50 -| 0059 |[Spiral Matrix II](src/main/kotlin/g0001_0100/s0059_spiral_matrix_ii)| Medium | Array, Matrix, Simulation | 153 | 100.00 +| 0057 |[Insert Interval](src/main/kotlin/g0001_0100/s0057_insert_interval)| Medium | Array | 257 | 99.52 +| 0056 |[Merge Intervals](src/main/kotlin/g0001_0100/s0056_merge_intervals)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting | 320 | 94.22 -#### Day 4 Array +#### Day 18 Stack | | | | | | |-|-|-|-|-|- -| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer | 460 | 66.08 -| 0435 |[Non-overlapping Intervals](src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals)| Medium | Array, Dynamic_Programming, Sorting, Greedy | 1040 | 85.07 +| 0735 |[Asteroid Collision](src/main/kotlin/g0701_0800/s0735_asteroid_collision)| Medium | Array, Stack | 243 | 100.00 +| 0227 |[Basic Calculator II](src/main/kotlin/g0201_0300/s0227_basic_calculator_ii)| Medium | Top_Interview_Questions, String, Math, Stack | 383 | 62.50 -#### Day 5 Array +#### Day 19 Union Find | | | | | | |-|-|-|-|-|- -| 0334 |[Increasing Triplet Subsequence](src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence)| Medium | Top_Interview_Questions, Array, Greedy | 672 | 60.61 -| 0238 |[Product of Array Except Self](src/main/kotlin/g0201_0300/s0238_product_of_array_except_self)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Prefix_Sum | 669 | 48.96 -| 0560 |[Subarray Sum Equals K](src/main/kotlin/g0501_0600/s0560_subarray_sum_equals_k)| Medium | Top_100_Liked_Questions, Array, Hash_Table, Prefix_Sum | 692 | 53.27 +| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 +| 0947 |[Most Stones Removed with Same Row or Column](src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column)| Medium | Depth_First_Search, Graph, Union_Find | 200 | 100.00 -#### Day 6 String +#### Day 20 Brute Force/Backtracking | | | | | | |-|-|-|-|-|- -| 0415 |[Add Strings](src/main/kotlin/g0401_0500/s0415_add_strings)| Easy | String, Math, Simulation | 296 | 76.00 -| 0409 |[Longest Palindrome](src/main/kotlin/g0401_0500/s0409_longest_palindrome)| Easy | String, Hash_Table, Greedy | 259 | 60.71 - -#### Day 7 String +| 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 +| 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 -| | | | | | -|-|-|-|-|-|- -| 0290 |[Word Pattern](src/main/kotlin/g0201_0300/s0290_word_pattern)| Easy | String, Hash_Table | 177 | 89.55 -| 0763 |[Partition Labels](src/main/kotlin/g0701_0800/s0763_partition_labels)| Medium | Top_100_Liked_Questions, String, Hash_Table, Greedy, Two_Pointers | 235 | 84.75 +### Udemy -#### Day 8 String +#### Udemy Integers | | | | | | |-|-|-|-|-|- -| 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting | 506 | 86.55 -| 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 390 | 56.25 +| 0412 |[Fizz Buzz](src/main/kotlin/g0401_0500/s0412_fizz_buzz)| Easy | Top_Interview_Questions, String, Math, Simulation | 307 | 71.81 +| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 +| 0007 |[Reverse Integer](src/main/kotlin/g0001_0100/s0007_reverse_integer)| Medium | Top_Interview_Questions, Math | 245 | 60.32 +| 0009 |[Palindrome Number](src/main/kotlin/g0001_0100/s0009_palindrome_number)| Easy | Math | 238 | 96.24 +| 0172 |[Factorial Trailing Zeroes](src/main/kotlin/g0101_0200/s0172_factorial_trailing_zeroes)| Medium | Top_Interview_Questions, Math | 220 | 67.65 +| 0050 |[Pow(x, n)](src/main/kotlin/g0001_0100/s0050_powx_n)| Medium | Top_Interview_Questions, Math, Recursion | 264 | 52.98 -#### Day 9 String +#### Udemy Strings | | | | | | |-|-|-|-|-|- +| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 +| 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String | 209 | 88.86 | 0187 |[Repeated DNA Sequences](src/main/kotlin/g0101_0200/s0187_repeated_dna_sequences)| Medium | String, Hash_Table, Bit_Manipulation, Sliding_Window, Hash_Function, Rolling_Hash | 319 | 79.03 +| 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 +| 0020 |[Valid Parentheses](src/main/kotlin/g0001_0100/s0020_valid_parentheses)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, String, Stack | 226 | 72.53 | 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 +| 0394 |[Decode String](src/main/kotlin/g0301_0400/s0394_decode_string)| Medium | Top_100_Liked_Questions, String, Stack, Recursion | 224 | 64.86 +| 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 +| 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting | 506 | 86.55 +| 0151 |[Reverse Words in a String](src/main/kotlin/g0101_0200/s0151_reverse_words_in_a_string)| Medium | String, Two_Pointers | 206 | 98.90 +| 0273 |[Integer to English Words](src/main/kotlin/g0201_0300/s0273_integer_to_english_words)| Hard | String, Math, Recursion | 273 | 82.93 -#### Day 10 Linked List +#### Udemy Binary Search | | | | | | |-|-|-|-|-|- -| 0002 |[Add Two Numbers](src/main/kotlin/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion | 417 | 50.44 -| 0142 |[Linked List Cycle II](src/main/kotlin/g0101_0200/s0142_linked_list_cycle_ii)| Medium | Top_100_Liked_Questions, Hash_Table, Two_Pointers, Linked_List | 192 | 63.39 +| 0704 |[Binary Search](src/main/kotlin/g0701_0800/s0704_binary_search)| Easy | Array, Binary_Search | 261 | 77.91 +| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 +| 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 -#### Day 11 Linked List +#### Udemy Arrays | | | | | | |-|-|-|-|-|- -| 0160 |[Intersection of Two Linked Lists](src/main/kotlin/g0101_0200/s0160_intersection_of_two_linked_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 262 | 83.50 -| 0082 |[Remove Duplicates from Sorted List II](src/main/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii)| Medium | Two_Pointers, Linked_List | 241 | 91.04 +| 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 609 | 94.06 +| 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers | 516 | 79.07 +| 0001 |[Two Sum](src/main/kotlin/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 234 | 92.75 +| 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 +| 0058 |[Length of Last Word](src/main/kotlin/g0001_0100/s0058_length_of_last_word)| Easy | String | 243 | 63.33 +| 0605 |[Can Place Flowers](src/main/kotlin/g0601_0700/s0605_can_place_flowers)| Easy | Array, Greedy | 209 | 85.71 +| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 +| 0080 |[Remove Duplicates from Sorted Array II](src/main/kotlin/g0001_0100/s0080_remove_duplicates_from_sorted_array_ii)| Medium | Array, Two_Pointers | 357 | 44.78 +| 0189 |[Rotate Array](src/main/kotlin/g0101_0200/s0189_rotate_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Two_Pointers | 483 | 86.95 +| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 +| 0075 |[Sort Colors](src/main/kotlin/g0001_0100/s0075_sort_colors)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 198 | 85.66 +| 0066 |[Plus One](src/main/kotlin/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 303 | 35.18 +| 0238 |[Product of Array Except Self](src/main/kotlin/g0201_0300/s0238_product_of_array_except_self)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Prefix_Sum | 669 | 48.96 +| 0448 |[Find All Numbers Disappeared in an Array](src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array)| Easy | Array, Hash_Table | 394 | 100.00 +| 0442 |[Find All Duplicates in an Array](src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array)| Medium | Array, Hash_Table | 480 | 73.81 +| 0041 |[First Missing Positive](src/main/kotlin/g0001_0100/s0041_first_missing_positive)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 345 | 100.00 +| 0697 |[Degree of an Array](src/main/kotlin/g0601_0700/s0697_degree_of_an_array)| Easy | Array, Hash_Table | 289 | 84.62 +| 0532 |[K-diff Pairs in an Array](src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array)| Medium | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 230 | 84.62 +| 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 +| 1007 |[Minimum Domino Rotations For Equal Row](src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row)| Medium | Array, Greedy | 421 | 50.00 +| 1306 |[Jump Game III](src/main/kotlin/g1301_1400/s1306_jump_game_iii)| Medium | Array, Depth_First_Search, Breadth_First_Search | 291 | 100.00 +| 0456 |[132 Pattern](src/main/kotlin/g0401_0500/s0456_132_pattern)| Medium | Array, Binary_Search, Stack, Ordered_Set, Monotonic_Stack | 434 | 100.00 +| 0239 |[Sliding Window Maximum](src/main/kotlin/g0201_0300/s0239_sliding_window_maximum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 1059 | 86.14 -#### Day 12 Linked List +#### Udemy Two Pointers | | | | | | |-|-|-|-|-|- -| 0024 |[Swap Nodes in Pairs](src/main/kotlin/g0001_0100/s0024_swap_nodes_in_pairs)| Medium | Top_100_Liked_Questions, Linked_List, Recursion | 149 | 99.39 -| 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 +| 0125 |[Valid Palindrome](src/main/kotlin/g0101_0200/s0125_valid_palindrome)| Easy | Top_Interview_Questions, String, Two_Pointers | 353 | 52.06 +| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 375 | 18.43 +| 0026 |[Remove Duplicates from Sorted Array](src/main/kotlin/g0001_0100/s0026_remove_duplicates_from_sorted_array)| Easy | Top_Interview_Questions, Array, Two_Pointers | 361 | 77.19 +| 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack | 196 | 100.00 +| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 761 | 90.55 -#### Day 13 Linked List +#### Udemy Famous Algorithm | | | | | | |-|-|-|-|-|- -| 0025 |[Reverse Nodes in k-Group](src/main/kotlin/g0001_0100/s0025_reverse_nodes_in_k_group)| Hard | Top_100_Liked_Questions, Linked_List, Recursion | 194 | 87.72 -| 0143 |[Reorder List](src/main/kotlin/g0101_0200/s0143_reorder_list)| Medium | Two_Pointers, Stack, Linked_List, Recursion | 395 | 82.26 +| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 +| 0169 |[Majority Element](src/main/kotlin/g0101_0200/s0169_majority_element)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Counting, Divide_and_Conquer | 460 | 51.25 -#### Day 14 Stack Queue +#### Udemy Sorting Algorithms | | | | | | |-|-|-|-|-|- -| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 +| 0912 |[Sort an Array](src/main/kotlin/g0901_1000/s0912_sort_an_array)| Medium | Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Merge_Sort, Bucket_Sort, Counting_Sort, Radix_Sort | 606 | 98.48 -#### Day 15 Tree +#### Udemy 2D Arrays/Matrix | | | | | | |-|-|-|-|-|- -| 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 -| 0105 |[Construct Binary Tree from Preorder and Inorder Traversal](src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Tree, Binary_Tree, Divide_and_Conquer | 370 | 58.31 -| 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 316 | 34.25 +| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 +| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 +| 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 224 | 62.50 +| 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix | 287 | 46.50 +| 0073 |[Set Matrix Zeroes](src/main/kotlin/g0001_0100/s0073_set_matrix_zeroes)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Matrix | 255 | 100.00 +| 0056 |[Merge Intervals](src/main/kotlin/g0001_0100/s0056_merge_intervals)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting | 320 | 94.22 -#### Day 16 Tree +#### Udemy Linked List | | | | | | |-|-|-|-|-|- -| 0199 |[Binary Tree Right Side View](src/main/kotlin/g0101_0200/s0199_binary_tree_right_side_view)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 194 | 92.89 -| 0113 |[Path Sum II](src/main/kotlin/g0101_0200/s0113_path_sum_ii)| Medium | Depth_First_Search, Tree, Binary_Tree, Backtracking | 364 | 78.67 -| 0450 |[Delete Node in a BST](src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 257 | 84.62 +| 0114 |[Flatten Binary Tree to Linked List](src/main/kotlin/g0101_0200/s0114_flatten_binary_tree_to_linked_list)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Stack, Linked_List | 191 | 93.10 +| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 240 | 82.61 +| 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List | 216 | 86.96 +| 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 193 | 92.16 +| 0024 |[Swap Nodes in Pairs](src/main/kotlin/g0001_0100/s0024_swap_nodes_in_pairs)| Medium | Top_100_Liked_Questions, Linked_List, Recursion | 149 | 99.39 +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 +| 0142 |[Linked List Cycle II](src/main/kotlin/g0101_0200/s0142_linked_list_cycle_ii)| Medium | Top_100_Liked_Questions, Hash_Table, Two_Pointers, Linked_List | 192 | 63.39 +| 0141 |[Linked List Cycle](src/main/kotlin/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 223 | 91.85 +| 0206 |[Reverse Linked List](src/main/kotlin/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 279 | 45.78 +| 0021 |[Merge Two Sorted Lists](src/main/kotlin/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 176 | 96.25 +| 0160 |[Intersection of Two Linked Lists](src/main/kotlin/g0101_0200/s0160_intersection_of_two_linked_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 262 | 83.50 +| 0234 |[Palindrome Linked List](src/main/kotlin/g0201_0300/s0234_palindrome_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Stack, Linked_List, Recursion | 641 | 79.53 +| 0138 |[Copy List with Random Pointer](src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Linked_List | 274 | 80.58 +| 0025 |[Reverse Nodes in k-Group](src/main/kotlin/g0001_0100/s0025_reverse_nodes_in_k_group)| Hard | Top_100_Liked_Questions, Linked_List, Recursion | 194 | 87.72 +| 0146 |[LRU Cache](src/main/kotlin/g0101_0200/s0146_lru_cache)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Design, Linked_List, Doubly_Linked_List | 1116 | 97.93 +| 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 -#### Day 17 Tree +#### Udemy Tree Stack Queue | | | | | | |-|-|-|-|-|- -| 0230 |[Kth Smallest Element in a BST](src/main/kotlin/g0201_0300/s0230_kth_smallest_element_in_a_bst)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 393 | 33.33 -| 0173 |[Binary Search Tree Iterator](src/main/kotlin/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 563 | 46.91 +| 0144 |[Binary Tree Preorder Traversal](src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 277 | 37.90 +| 0094 |[Binary Tree Inorder Traversal](src/main/kotlin/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 269 | 38.80 +| 0145 |[Binary Tree Postorder Traversal](src/main/kotlin/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 211 | 80.00 +| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 +| 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 316 | 34.25 +| 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 +| 1008 |[Construct Binary Search Tree from Preorder Traversal](src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal)| Medium | Array, Tree, Binary_Tree, Stack, Monotonic_Stack, Binary_Search_Tree | 145 | 100.00 +| 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 307 | 43.93 +| 0938 |[Range Sum of BST](src/main/kotlin/g0901_1000/s0938_range_sum_of_bst)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 356 | 55.36 +| 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 +| 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 +| 0111 |[Minimum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 525 | 90.51 +| 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 236 | 83.39 +| 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 310 | 63.63 +| 0701 |[Insert into a Binary Search Tree](src/main/kotlin/g0701_0800/s0701_insert_into_a_binary_search_tree)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 311 | 79.03 +| 0297 |[Serialize and Deserialize Binary Tree](src/main/kotlin/g0201_0300/s0297_serialize_and_deserialize_binary_tree)| Hard | Top_Interview_Questions, String, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Design | 475 | 78.85 +| 0124 |[Binary Tree Maximum Path Sum](src/main/kotlin/g0101_0200/s0124_binary_tree_maximum_path_sum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 331 | 74.42 +| 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 +| 0337 |[House Robber III](src/main/kotlin/g0301_0400/s0337_house_robber_iii)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 282 | 84.62 +| 0236 |[Lowest Common Ancestor of a Binary Tree](src/main/kotlin/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree | 386 | 45.21 +| 0968 |[Binary Tree Cameras](src/main/kotlin/g0901_1000/s0968_binary_tree_cameras)| Hard | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 176 | 100.00 -#### Day 18 Tree +#### Udemy Trie and Heap | | | | | | |-|-|-|-|-|- -| 0236 |[Lowest Common Ancestor of a Binary Tree](src/main/kotlin/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree | 386 | 45.21 -| 0297 |[Serialize and Deserialize Binary Tree](src/main/kotlin/g0201_0300/s0297_serialize_and_deserialize_binary_tree)| Hard | Top_Interview_Questions, String, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Design | 475 | 78.85 +| 0208 |[Implement Trie (Prefix Tree)](src/main/kotlin/g0201_0300/s0208_implement_trie_prefix_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Design, Trie | 689 | 61.00 +| 0745 |[Prefix and Suffix Search](src/main/kotlin/g0701_0800/s0745_prefix_and_suffix_search)| Hard | String, Design, Trie | 1638 | 100.00 -#### Day 19 Graph +#### Udemy Graph | | | | | | |-|-|-|-|-|- -| 0997 |[Find the Town Judge](src/main/kotlin/g0901_1000/s0997_find_the_town_judge)| Easy | Array, Hash_Table, Graph | 475 | 58.62 -| 0841 |[Keys and Rooms](src/main/kotlin/g0801_0900/s0841_keys_and_rooms)| Medium | Depth_First_Search, Breadth_First_Search, Graph | 189 | 69.23 +| 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 252 | 95.41 +| 0133 |[Clone Graph](src/main/kotlin/g0101_0200/s0133_clone_graph)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Graph | 351 | 60.91 +| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 -#### Day 20 Heap Priority Queue +#### Udemy Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0215 |[Kth Largest Element in an Array](src/main/kotlin/g0201_0300/s0215_kth_largest_element_in_an_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Quickselect | 839 | 34.43 -| 0347 |[Top K Frequent Elements](src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Divide_and_Conquer, Quickselect, Bucket_Sort | 268 | 99.74 +| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 +| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 +| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 +| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 +| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 +| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 +| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 +| 0064 |[Minimum Path Sum](src/main/kotlin/g0001_0100/s0064_minimum_path_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix | 222 | 95.70 +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 +| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 +| 0044 |[Wildcard Matching](src/main/kotlin/g0001_0100/s0044_wildcard_matching)| Hard | Top_Interview_Questions, String, Dynamic_Programming, Greedy, Recursion | 401 | 86.11 +| 0010 |[Regular Expression Matching](src/main/kotlin/g0001_0100/s0010_regular_expression_matching)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Recursion | 292 | 58.58 -#### Day 21 Heap Priority Queue +#### Udemy Backtracking/Recursion | | | | | | |-|-|-|-|-|- -| 0451 |[Sort Characters By Frequency](src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Bucket_Sort | 288 | 81.72 -| 0973 |[K Closest Points to Origin](src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect | 800 | 37.89 - -### Algorithm I +| 0022 |[Generate Parentheses](src/main/kotlin/g0001_0100/s0022_generate_parentheses)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Backtracking | 210 | 78.51 +| 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 +| 0216 |[Combination Sum III](src/main/kotlin/g0201_0300/s0216_combination_sum_iii)| Medium | Array, Backtracking | 175 | 90.91 +| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 191 | 97.44 +| 0017 |[Letter Combinations of a Phone Number](src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Backtracking | 262 | 73.59 +| 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 -#### Day 1 Binary Search +#### Udemy Bit Manipulation | | | | | | |-|-|-|-|-|- -| 0704 |[Binary Search](src/main/kotlin/g0701_0800/s0704_binary_search)| Easy | Array, Binary_Search | 261 | 77.91 -| 0278 |[First Bad Version](src/main/kotlin/g0201_0300/s0278_first_bad_version)| Easy | Binary_Search, Interactive | 349 | 76.86 -| 0035 |[Search Insert Position](src/main/kotlin/g0001_0100/s0035_search_insert_position)| Easy | Top_100_Liked_Questions, Array, Binary_Search | 267 | 50.32 +| 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 +| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 +| 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 +| 0461 |[Hamming Distance](src/main/kotlin/g0401_0500/s0461_hamming_distance)| Easy | Bit_Manipulation | 150 | 96.15 +| 1009 |[Complement of Base 10 Integer](src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer)| Easy | Bit_Manipulation | 126 | 72.73 +| 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation | 186 | 99.26 +| 0371 |[Sum of Two Integers](src/main/kotlin/g0301_0400/s0371_sum_of_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 129 | 95.45 +| 0029 |[Divide Two Integers](src/main/kotlin/g0001_0100/s0029_divide_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 281 | 31.67 -#### Day 2 Two Pointers +#### Udemy Design | | | | | | |-|-|-|-|-|- -| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 375 | 18.43 -| 0189 |[Rotate Array](src/main/kotlin/g0101_0200/s0189_rotate_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Two_Pointers | 483 | 86.95 +| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 -#### Day 3 Two Pointers +### Data Structure I + +#### Day 1 Array | | | | | | |-|-|-|-|-|- -| 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers | 516 | 79.07 -| 0167 |[Two Sum II - Input Array Is Sorted](src/main/kotlin/g0101_0200/s0167_two_sum_ii_input_array_is_sorted)| Medium | Array, Binary_Search, Two_Pointers | 403 | 68.74 +| 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 +| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 -#### Day 4 Two Pointers +#### Day 2 Array | | | | | | |-|-|-|-|-|- -| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 -| 0557 |[Reverse Words in a String III](src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii)| Easy | String, Two_Pointers | 215 | 98.10 +| 0001 |[Two Sum](src/main/kotlin/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 234 | 92.75 +| 0088 |[Merge Sorted Array](src/main/kotlin/g0001_0100/s0088_merge_sorted_array)| Easy | Top_Interview_Questions, Array, Sorting, Two_Pointers | 311 | 33.40 -#### Day 5 Two Pointers +#### Day 3 Array | | | | | | |-|-|-|-|-|- -| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 -| 0019 |[Remove Nth Node From End of List](src/main/kotlin/g0001_0100/s0019_remove_nth_node_from_end_of_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Linked_List | 180 | 91.58 +| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 321 | 73.37 +| 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 609 | 94.06 -#### Day 6 Sliding Window +#### Day 4 Array | | | | | | |-|-|-|-|-|- -| 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 -| 0567 |[Permutation in String](src/main/kotlin/g0501_0600/s0567_permutation_in_string)| Medium | String, Hash_Table, Two_Pointers, Sliding_Window | 169 | 100.00 +| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 239 | 99.05 +| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 -#### Day 7 Breadth First Search Depth First Search +#### Day 5 Array | | | | | | |-|-|-|-|-|- -| 0733 |[Flood Fill](src/main/kotlin/g0701_0800/s0733_flood_fill)| Easy | Array, Depth_First_Search, Breadth_First_Search, Matrix | 230 | 97.76 -| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 324 | 24.06 +| 0036 |[Valid Sudoku](src/main/kotlin/g0001_0100/s0036_valid_sudoku)| Medium | Top_Interview_Questions, Array, Hash_Table, Matrix | 346 | 65.03 +| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 -#### Day 8 Breadth First Search Depth First Search +#### Day 6 String | | | | | | |-|-|-|-|-|- -| 0617 |[Merge Two Binary Trees](src/main/kotlin/g0601_0700/s0617_merge_two_binary_trees)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 243 | 72.83 -| 0116 |[Populating Next Right Pointers in Each Node](src/main/kotlin/g0101_0200/s0116_populating_next_right_pointers_in_each_node)| Medium | Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 355 | 69.02 +| 0387 |[First Unique Character in a String](src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string)| Easy | Top_Interview_Questions, String, Hash_Table, Counting, Queue | 369 | 82.68 +| 0383 |[Ransom Note](src/main/kotlin/g0301_0400/s0383_ransom_note)| Easy | String, Hash_Table, Counting | 333 | 79.58 +| 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 -#### Day 9 Breadth First Search Depth First Search +#### Day 7 Linked List | | | | | | |-|-|-|-|-|- -| 0542 |[01 Matrix](src/main/kotlin/g0501_0600/s0542_01_matrix)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 441 | 94.06 -| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 164 | 82.95 +| 0141 |[Linked List Cycle](src/main/kotlin/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 223 | 91.85 +| 0021 |[Merge Two Sorted Lists](src/main/kotlin/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 176 | 96.25 +| 0203 |[Remove Linked List Elements](src/main/kotlin/g0201_0300/s0203_remove_linked_list_elements)| Easy | Linked_List, Recursion | 233 | 91.22 -#### Day 10 Recursion Backtracking +#### Day 8 Linked List | | | | | | |-|-|-|-|-|- -| 0021 |[Merge Two Sorted Lists](src/main/kotlin/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 176 | 96.25 | 0206 |[Reverse Linked List](src/main/kotlin/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 279 | 45.78 +| 0083 |[Remove Duplicates from Sorted List](src/main/kotlin/g0001_0100/s0083_remove_duplicates_from_sorted_list)| Easy | Linked_List | 274 | 77.82 -#### Day 11 Recursion Backtracking +#### Day 9 Stack Queue | | | | | | |-|-|-|-|-|- -| 0077 |[Combinations](src/main/kotlin/g0001_0100/s0077_combinations)| Medium | Backtracking | 244 | 100.00 -| 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 -| 0784 |[Letter Case Permutation](src/main/kotlin/g0701_0800/s0784_letter_case_permutation)| Medium | String, Bit_Manipulation, Backtracking | 219 | 84.62 +| 0020 |[Valid Parentheses](src/main/kotlin/g0001_0100/s0020_valid_parentheses)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, String, Stack | 226 | 72.53 +| 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 -#### Day 12 Dynamic Programming +#### Day 10 Tree | | | | | | |-|-|-|-|-|- -| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 -| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 -| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 +| 0144 |[Binary Tree Preorder Traversal](src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 277 | 37.90 +| 0094 |[Binary Tree Inorder Traversal](src/main/kotlin/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 269 | 38.80 +| 0145 |[Binary Tree Postorder Traversal](src/main/kotlin/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 211 | 80.00 -#### Day 13 Bit Manipulation +#### Day 11 Tree | | | | | | |-|-|-|-|-|- -| 0231 |[Power of Two](src/main/kotlin/g0201_0300/s0231_power_of_two)| Easy | Math, Bit_Manipulation, Recursion | 161 | 86.81 -| 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 +| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 +| 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 236 | 83.39 +| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 91.36 -#### Day 14 Bit Manipulation +#### Day 12 Tree | | | | | | |-|-|-|-|-|- -| 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 -| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 - -### Algorithm II +| 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 +| 0112 |[Path Sum](src/main/kotlin/g0101_0200/s0112_path_sum)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 322 | 36.41 -#### Day 1 Binary Search +#### Day 13 Tree | | | | | | |-|-|-|-|-|- -| 0034 |[Find First and Last Position of Element in Sorted Array](src/main/kotlin/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 228 | 83.38 -| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 -| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 +| 0700 |[Search in a Binary Search Tree](src/main/kotlin/g0601_0700/s0700_search_in_a_binary_search_tree)| Easy | Tree, Binary_Tree, Binary_Search_Tree | 251 | 88.31 +| 0701 |[Insert into a Binary Search Tree](src/main/kotlin/g0701_0800/s0701_insert_into_a_binary_search_tree)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 311 | 79.03 -#### Day 2 Binary Search +#### Day 14 Tree | | | | | | |-|-|-|-|-|- -| 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 -| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 +| 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 +| 0653 |[Two Sum IV - Input is a BST](src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree | 231 | 96.08 +| 0235 |[Lowest Common Ancestor of a Binary Search Tree](src/main/kotlin/g0201_0300/s0235_lowest_common_ancestor_of_a_binary_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 404 | 75.59 -#### Day 3 Two Pointers +### Data Structure II + +#### Day 1 Array | | | | | | |-|-|-|-|-|- -| 0082 |[Remove Duplicates from Sorted List II](src/main/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii)| Medium | Two_Pointers, Linked_List | 241 | 91.04 +| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 +| 0169 |[Majority Element](src/main/kotlin/g0101_0200/s0169_majority_element)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Counting, Divide_and_Conquer | 460 | 51.25 | 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 761 | 90.55 -#### Day 4 Two Pointers +#### Day 2 Array | | | | | | |-|-|-|-|-|- -| 0844 |[Backspace String Compare](src/main/kotlin/g0801_0900/s0844_backspace_string_compare)| Easy | String, Two_Pointers, Stack, Simulation | 126 | 98.31 -| 0986 |[Interval List Intersections](src/main/kotlin/g0901_1000/s0986_interval_list_intersections)| Medium | Array, Two_Pointers | 318 | 60.98 -| 0011 |[Container With Most Water](src/main/kotlin/g0001_0100/s0011_container_with_most_water)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Greedy, Two_Pointers | 474 | 89.18 +| 0075 |[Sort Colors](src/main/kotlin/g0001_0100/s0075_sort_colors)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 198 | 85.66 +| 0056 |[Merge Intervals](src/main/kotlin/g0001_0100/s0056_merge_intervals)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting | 320 | 94.22 +| 0706 |[Design HashMap](src/main/kotlin/g0701_0800/s0706_design_hashmap)| Easy | Array, Hash_Table, Design, Linked_List, Hash_Function | 405 | 92.11 -#### Day 5 Sliding Window +#### Day 3 Array | | | | | | |-|-|-|-|-|- -| 0438 |[Find All Anagrams in a String](src/main/kotlin/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window | 561 | 54.68 -| 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 -| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 +| 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix | 287 | 46.50 +| 0059 |[Spiral Matrix II](src/main/kotlin/g0001_0100/s0059_spiral_matrix_ii)| Medium | Array, Matrix, Simulation | 153 | 100.00 -#### Day 6 Breadth First Search Depth First Search +#### Day 4 Array | | | | | | |-|-|-|-|-|- -| 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 252 | 95.41 -| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 +| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer | 460 | 66.08 +| 0435 |[Non-overlapping Intervals](src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals)| Medium | Array, Dynamic_Programming, Sorting, Greedy | 1040 | 85.07 -#### Day 7 Breadth First Search Depth First Search +#### Day 5 Array | | | | | | |-|-|-|-|-|- -| 0117 |[Populating Next Right Pointers in Each Node II](src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 199 | 94.67 -| 0572 |[Subtree of Another Tree](src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Hash_Function, String_Matching | 214 | 92.39 +| 0334 |[Increasing Triplet Subsequence](src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence)| Medium | Top_Interview_Questions, Array, Greedy | 672 | 60.61 +| 0238 |[Product of Array Except Self](src/main/kotlin/g0201_0300/s0238_product_of_array_except_self)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Prefix_Sum | 669 | 48.96 +| 0560 |[Subarray Sum Equals K](src/main/kotlin/g0501_0600/s0560_subarray_sum_equals_k)| Medium | Top_100_Liked_Questions, Array, Hash_Table, Prefix_Sum | 692 | 53.27 -#### Day 8 Breadth First Search Depth First Search +#### Day 6 String | | | | | | |-|-|-|-|-|- -| 1091 |[Shortest Path in Binary Matrix](src/main/kotlin/g1001_1100/s1091_shortest_path_in_binary_matrix)| Medium | Array, Breadth_First_Search, Matrix | 305 | 98.28 -| 0130 |[Surrounded Regions](src/main/kotlin/g0101_0200/s0130_surrounded_regions)| Medium | Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 355 | 84.42 -| 0797 |[All Paths From Source to Target](src/main/kotlin/g0701_0800/s0797_all_paths_from_source_to_target)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Backtracking | 232 | 100.00 +| 0415 |[Add Strings](src/main/kotlin/g0401_0500/s0415_add_strings)| Easy | String, Math, Simulation | 296 | 76.00 +| 0409 |[Longest Palindrome](src/main/kotlin/g0401_0500/s0409_longest_palindrome)| Easy | String, Hash_Table, Greedy | 259 | 60.71 -#### Day 9 Recursion Backtracking +#### Day 7 String | | | | | | |-|-|-|-|-|- -| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 191 | 97.44 -| 0090 |[Subsets II](src/main/kotlin/g0001_0100/s0090_subsets_ii)| Medium | Array, Bit_Manipulation, Backtracking | 366 | 58.09 +| 0290 |[Word Pattern](src/main/kotlin/g0201_0300/s0290_word_pattern)| Easy | String, Hash_Table | 177 | 89.55 +| 0763 |[Partition Labels](src/main/kotlin/g0701_0800/s0763_partition_labels)| Medium | Top_100_Liked_Questions, String, Hash_Table, Greedy, Two_Pointers | 235 | 84.75 -#### Day 10 Recursion Backtracking +#### Day 8 String | | | | | | |-|-|-|-|-|- -| 0047 |[Permutations II](src/main/kotlin/g0001_0100/s0047_permutations_ii)| Medium | Array, Backtracking | 406 | 76.36 -| 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 -| 0040 |[Combination Sum II](src/main/kotlin/g0001_0100/s0040_combination_sum_ii)| Medium | Array, Backtracking | 348 | 80.92 +| 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting | 506 | 86.55 +| 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 390 | 56.25 -#### Day 11 Recursion Backtracking +#### Day 9 String | | | | | | |-|-|-|-|-|- -| 0017 |[Letter Combinations of a Phone Number](src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Backtracking | 262 | 73.59 -| 0022 |[Generate Parentheses](src/main/kotlin/g0001_0100/s0022_generate_parentheses)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Backtracking | 210 | 78.51 -| 0079 |[Word Search](src/main/kotlin/g0001_0100/s0079_word_search)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Matrix, Backtracking | 463 | 68.49 +| 0187 |[Repeated DNA Sequences](src/main/kotlin/g0101_0200/s0187_repeated_dna_sequences)| Medium | String, Hash_Table, Bit_Manipulation, Sliding_Window, Hash_Function, Rolling_Hash | 319 | 79.03 +| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 -#### Day 12 Dynamic Programming +#### Day 10 Linked List | | | | | | |-|-|-|-|-|- -| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 -| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 +| 0002 |[Add Two Numbers](src/main/kotlin/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion | 417 | 50.44 +| 0142 |[Linked List Cycle II](src/main/kotlin/g0101_0200/s0142_linked_list_cycle_ii)| Medium | Top_100_Liked_Questions, Hash_Table, Two_Pointers, Linked_List | 192 | 63.39 -#### Day 13 Dynamic Programming +#### Day 11 Linked List | | | | | | |-|-|-|-|-|- -| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy | 227 | 98.14 -| 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics | 209 | 49.18 +| 0160 |[Intersection of Two Linked Lists](src/main/kotlin/g0101_0200/s0160_intersection_of_two_linked_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 262 | 83.50 +| 0082 |[Remove Duplicates from Sorted List II](src/main/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii)| Medium | Two_Pointers, Linked_List | 241 | 91.04 -#### Day 14 Dynamic Programming +#### Day 12 Linked List | | | | | | |-|-|-|-|-|- -| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 -| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 +| 0024 |[Swap Nodes in Pairs](src/main/kotlin/g0001_0100/s0024_swap_nodes_in_pairs)| Medium | Top_100_Liked_Questions, Linked_List, Recursion | 149 | 99.39 +| 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 -#### Day 15 Dynamic Programming +#### Day 13 Linked List | | | | | | |-|-|-|-|-|- -| 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 237 | 76.88 -| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 +| 0025 |[Reverse Nodes in k-Group](src/main/kotlin/g0001_0100/s0025_reverse_nodes_in_k_group)| Hard | Top_100_Liked_Questions, Linked_List, Recursion | 194 | 87.72 +| 0143 |[Reorder List](src/main/kotlin/g0101_0200/s0143_reorder_list)| Medium | Two_Pointers, Stack, Linked_List, Recursion | 395 | 82.26 -#### Day 16 Dynamic Programming +#### Day 14 Stack Queue | | | | | | |-|-|-|-|-|- -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 -| 0673 |[Number of Longest Increasing Subsequence](src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence)| Medium | Array, Dynamic_Programming, Segment_Tree, Binary_Indexed_Tree | 226 | 91.67 +| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 -#### Day 17 Dynamic Programming +#### Day 15 Tree | | | | | | |-|-|-|-|-|- -| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 -| 0583 |[Delete Operation for Two Strings](src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings)| Medium | String, Dynamic_Programming | 197 | 100.00 +| 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 +| 0105 |[Construct Binary Tree from Preorder and Inorder Traversal](src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Tree, Binary_Tree, Divide_and_Conquer | 370 | 58.31 +| 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 316 | 34.25 -#### Day 18 Dynamic Programming +#### Day 16 Tree | | | | | | |-|-|-|-|-|- -| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 -| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search | 332 | 50.68 -| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 +| 0199 |[Binary Tree Right Side View](src/main/kotlin/g0101_0200/s0199_binary_tree_right_side_view)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 194 | 92.89 +| 0113 |[Path Sum II](src/main/kotlin/g0101_0200/s0113_path_sum_ii)| Medium | Depth_First_Search, Tree, Binary_Tree, Backtracking | 364 | 78.67 +| 0450 |[Delete Node in a BST](src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 257 | 84.62 -#### Day 19 Bit Manipulation +#### Day 17 Tree | | | | | | |-|-|-|-|-|- -| 0201 |[Bitwise AND of Numbers Range](src/main/kotlin/g0201_0300/s0201_bitwise_and_of_numbers_range)| Medium | Bit_Manipulation | 368 | 80.00 +| 0230 |[Kth Smallest Element in a BST](src/main/kotlin/g0201_0300/s0230_kth_smallest_element_in_a_bst)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 393 | 33.33 +| 0173 |[Binary Search Tree Iterator](src/main/kotlin/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 563 | 46.91 -#### Day 20 Others +#### Day 18 Tree | | | | | | |-|-|-|-|-|- -| 0384 |[Shuffle an Array](src/main/kotlin/g0301_0400/s0384_shuffle_an_array)| Medium | Top_Interview_Questions, Array, Math, Randomized | 940 | 72.09 +| 0236 |[Lowest Common Ancestor of a Binary Tree](src/main/kotlin/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree | 386 | 45.21 +| 0297 |[Serialize and Deserialize Binary Tree](src/main/kotlin/g0201_0300/s0297_serialize_and_deserialize_binary_tree)| Hard | Top_Interview_Questions, String, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Design | 475 | 78.85 -#### Day 21 Others +#### Day 19 Graph | | | | | | |-|-|-|-|-|- -| 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 -| 0149 |[Max Points on a Line](src/main/kotlin/g0101_0200/s0149_max_points_on_a_line)| Hard | Top_Interview_Questions, Array, Hash_Table, Math, Geometry | 307 | 83.33 - -### Binary Search I +| 0997 |[Find the Town Judge](src/main/kotlin/g0901_1000/s0997_find_the_town_judge)| Easy | Array, Hash_Table, Graph | 475 | 58.62 +| 0841 |[Keys and Rooms](src/main/kotlin/g0801_0900/s0841_keys_and_rooms)| Medium | Depth_First_Search, Breadth_First_Search, Graph | 189 | 69.23 -#### Day 1 +#### Day 20 Heap Priority Queue | | | | | | |-|-|-|-|-|- -| 0704 |[Binary Search](src/main/kotlin/g0701_0800/s0704_binary_search)| Easy | Array, Binary_Search | 261 | 77.91 -| 0374 |[Guess Number Higher or Lower](src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower)| Easy | Binary_Search, Interactive | 134 | 94.19 +| 0215 |[Kth Largest Element in an Array](src/main/kotlin/g0201_0300/s0215_kth_largest_element_in_an_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Quickselect | 839 | 34.43 +| 0347 |[Top K Frequent Elements](src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Divide_and_Conquer, Quickselect, Bucket_Sort | 268 | 99.74 -#### Day 2 +#### Day 21 Heap Priority Queue | | | | | | |-|-|-|-|-|- -| 0035 |[Search Insert Position](src/main/kotlin/g0001_0100/s0035_search_insert_position)| Easy | Top_100_Liked_Questions, Array, Binary_Search | 267 | 50.32 -| 0852 |[Peak Index in a Mountain Array](src/main/kotlin/g0801_0900/s0852_peak_index_in_a_mountain_array)| Easy | Array, Binary_Search | 433 | 94.29 +| 0451 |[Sort Characters By Frequency](src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Bucket_Sort | 288 | 81.72 +| 0973 |[K Closest Points to Origin](src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect | 800 | 37.89 -#### Day 3 +### Algorithm I + +#### Day 1 Binary Search | | | | | | |-|-|-|-|-|- -| 0367 |[Valid Perfect Square](src/main/kotlin/g0301_0400/s0367_valid_perfect_square)| Easy | Math, Binary_Search | 137 | 94.55 +| 0704 |[Binary Search](src/main/kotlin/g0701_0800/s0704_binary_search)| Easy | Array, Binary_Search | 261 | 77.91 +| 0278 |[First Bad Version](src/main/kotlin/g0201_0300/s0278_first_bad_version)| Easy | Binary_Search, Interactive | 349 | 76.86 +| 0035 |[Search Insert Position](src/main/kotlin/g0001_0100/s0035_search_insert_position)| Easy | Top_100_Liked_Questions, Array, Binary_Search | 267 | 50.32 -#### Day 4 +#### Day 2 Two Pointers | | | | | | |-|-|-|-|-|- -| 0069 |[Sqrt(x)](src/main/kotlin/g0001_0100/s0069_sqrtx)| Easy | Top_Interview_Questions, Math, Binary_Search | 153 | 95.75 -| 0744 |[Find Smallest Letter Greater Than Target](src/main/kotlin/g0701_0800/s0744_find_smallest_letter_greater_than_target)| Easy | Array, Binary_Search | 162 | 100.00 +| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 375 | 18.43 +| 0189 |[Rotate Array](src/main/kotlin/g0101_0200/s0189_rotate_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Two_Pointers | 483 | 86.95 -#### Day 5 +#### Day 3 Two Pointers | | | | | | |-|-|-|-|-|- -| 0278 |[First Bad Version](src/main/kotlin/g0201_0300/s0278_first_bad_version)| Easy | Binary_Search, Interactive | 349 | 76.86 -| 0034 |[Find First and Last Position of Element in Sorted Array](src/main/kotlin/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 228 | 83.38 +| 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers | 516 | 79.07 +| 0167 |[Two Sum II - Input Array Is Sorted](src/main/kotlin/g0101_0200/s0167_two_sum_ii_input_array_is_sorted)| Medium | Array, Binary_Search, Two_Pointers | 403 | 68.74 -#### Day 6 +#### Day 4 Two Pointers | | | | | | |-|-|-|-|-|- -| 0441 |[Arranging Coins](src/main/kotlin/g0401_0500/s0441_arranging_coins)| Easy | Math, Binary_Search | 150 | 84.21 +| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 +| 0557 |[Reverse Words in a String III](src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii)| Easy | String, Two_Pointers | 215 | 98.10 -#### Day 7 +#### Day 5 Two Pointers | | | | | | |-|-|-|-|-|- -| 0167 |[Two Sum II - Input Array Is Sorted](src/main/kotlin/g0101_0200/s0167_two_sum_ii_input_array_is_sorted)| Medium | Array, Binary_Search, Two_Pointers | 403 | 68.74 +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 +| 0019 |[Remove Nth Node From End of List](src/main/kotlin/g0001_0100/s0019_remove_nth_node_from_end_of_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Linked_List | 180 | 91.58 -#### Day 8 +#### Day 6 Sliding Window | | | | | | |-|-|-|-|-|- -| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 +| 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 +| 0567 |[Permutation in String](src/main/kotlin/g0501_0600/s0567_permutation_in_string)| Medium | String, Hash_Table, Two_Pointers, Sliding_Window | 169 | 100.00 -#### Day 9 +#### Day 7 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- +| 0733 |[Flood Fill](src/main/kotlin/g0701_0800/s0733_flood_fill)| Easy | Array, Depth_First_Search, Breadth_First_Search, Matrix | 230 | 97.76 +| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 324 | 24.06 -#### Day 10 +#### Day 8 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- -| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 321 | 73.37 -| 0633 |[Sum of Square Numbers](src/main/kotlin/g0601_0700/s0633_sum_of_square_numbers)| Medium | Math, Binary_Search, Two_Pointers | 126 | 100.00 +| 0617 |[Merge Two Binary Trees](src/main/kotlin/g0601_0700/s0617_merge_two_binary_trees)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 243 | 72.83 +| 0116 |[Populating Next Right Pointers in Each Node](src/main/kotlin/g0101_0200/s0116_populating_next_right_pointers_in_each_node)| Medium | Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 355 | 69.02 -#### Day 11 +#### Day 9 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- -| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 +| 0542 |[01 Matrix](src/main/kotlin/g0501_0600/s0542_01_matrix)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 441 | 94.06 +| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 164 | 82.95 -#### Day 12 +#### Day 10 Recursion Backtracking | | | | | | |-|-|-|-|-|- -| 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 - -### Binary Search II +| 0021 |[Merge Two Sorted Lists](src/main/kotlin/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 176 | 96.25 +| 0206 |[Reverse Linked List](src/main/kotlin/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 279 | 45.78 -#### Day 1 +#### Day 11 Recursion Backtracking | | | | | | |-|-|-|-|-|- -| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 -| 0611 |[Valid Triangle Number](src/main/kotlin/g0601_0700/s0611_valid_triangle_number)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 203 | 100.00 +| 0077 |[Combinations](src/main/kotlin/g0001_0100/s0077_combinations)| Medium | Backtracking | 244 | 100.00 +| 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 +| 0784 |[Letter Case Permutation](src/main/kotlin/g0701_0800/s0784_letter_case_permutation)| Medium | String, Bit_Manipulation, Backtracking | 219 | 84.62 -#### Day 2 +#### Day 12 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue | 375 | 95.16 +| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 +| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 +| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 -#### Day 3 +#### Day 13 Bit Manipulation | | | | | | |-|-|-|-|-|- -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 0231 |[Power of Two](src/main/kotlin/g0201_0300/s0231_power_of_two)| Easy | Math, Bit_Manipulation, Recursion | 161 | 86.81 +| 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 -#### Day 4 +#### Day 14 Bit Manipulation | | | | | | |-|-|-|-|-|- -| 0875 |[Koko Eating Bananas](src/main/kotlin/g0801_0900/s0875_koko_eating_bananas)| Medium | Array, Binary_Search | 267 | 93.85 +| 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 +| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 -#### Day 5 +### Algorithm II + +#### Day 1 Binary Search | | | | | | |-|-|-|-|-|- -| 0287 |[Find the Duplicate Number](src/main/kotlin/g0201_0300/s0287_find_the_duplicate_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Two_Pointers, Bit_Manipulation | 656 | 66.21 +| 0034 |[Find First and Last Position of Element in Sorted Array](src/main/kotlin/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 228 | 83.38 +| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 +| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 -#### Day 6 +#### Day 2 Binary Search | | | | | | |-|-|-|-|-|- +| 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 +| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 -#### Day 7 +#### Day 3 Two Pointers | | | | | | |-|-|-|-|-|- +| 0082 |[Remove Duplicates from Sorted List II](src/main/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii)| Medium | Two_Pointers, Linked_List | 241 | 91.04 +| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 761 | 90.55 -#### Day 8 +#### Day 4 Two Pointers | | | | | | |-|-|-|-|-|- -| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer | 460 | 66.08 -| 0275 |[H-Index II](src/main/kotlin/g0201_0300/s0275_h_index_ii)| Medium | Array, Binary_Search | 398 | 81.82 +| 0844 |[Backspace String Compare](src/main/kotlin/g0801_0900/s0844_backspace_string_compare)| Easy | String, Two_Pointers, Stack, Simulation | 126 | 98.31 +| 0986 |[Interval List Intersections](src/main/kotlin/g0901_1000/s0986_interval_list_intersections)| Medium | Array, Two_Pointers | 318 | 60.98 +| 0011 |[Container With Most Water](src/main/kotlin/g0001_0100/s0011_container_with_most_water)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Greedy, Two_Pointers | 474 | 89.18 -#### Day 9 +#### Day 5 Sliding Window | | | | | | |-|-|-|-|-|- -| 0540 |[Single Element in a Sorted Array](src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array)| Medium | Array, Binary_Search | 274 | 86.67 +| 0438 |[Find All Anagrams in a String](src/main/kotlin/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window | 561 | 54.68 +| 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 +| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 -#### Day 10 +#### Day 6 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- -| 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| +| 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 252 | 95.41 +| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 -#### Day 11 +#### Day 7 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- -| 0826 |[Most Profit Assigning Work](src/main/kotlin/g0801_0900/s0826_most_profit_assigning_work)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 366 | 100.00 -| 0436 |[Find Right Interval](src/main/kotlin/g0401_0500/s0436_find_right_interval)| Medium | Array, Sorting, Binary_Search | 333 | 100.00 +| 0117 |[Populating Next Right Pointers in Each Node II](src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 199 | 94.67 +| 0572 |[Subtree of Another Tree](src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Hash_Function, String_Matching | 214 | 92.39 -#### Day 12 +#### Day 8 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- -| 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search | 352 | 42.31 -| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 +| 1091 |[Shortest Path in Binary Matrix](src/main/kotlin/g1001_1100/s1091_shortest_path_in_binary_matrix)| Medium | Array, Breadth_First_Search, Matrix | 305 | 98.28 +| 0130 |[Surrounded Regions](src/main/kotlin/g0101_0200/s0130_surrounded_regions)| Medium | Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 355 | 84.42 +| 0797 |[All Paths From Source to Target](src/main/kotlin/g0701_0800/s0797_all_paths_from_source_to_target)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Backtracking | 232 | 100.00 -#### Day 13 +#### Day 9 Recursion Backtracking | | | | | | |-|-|-|-|-|- -| 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 -| 0528 |[Random Pick with Weight](src/main/kotlin/g0501_0600/s0528_random_pick_with_weight)| Medium | Math, Binary_Search, Prefix_Sum, Randomized | 393 | 91.38 +| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 191 | 97.44 +| 0090 |[Subsets II](src/main/kotlin/g0001_0100/s0090_subsets_ii)| Medium | Array, Bit_Manipulation, Backtracking | 366 | 58.09 -#### Day 14 +#### Day 10 Recursion Backtracking | | | | | | |-|-|-|-|-|- +| 0047 |[Permutations II](src/main/kotlin/g0001_0100/s0047_permutations_ii)| Medium | Array, Backtracking | 406 | 76.36 +| 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 +| 0040 |[Combination Sum II](src/main/kotlin/g0001_0100/s0040_combination_sum_ii)| Medium | Array, Backtracking | 348 | 80.92 -#### Day 15 +#### Day 11 Recursion Backtracking | | | | | | |-|-|-|-|-|- +| 0017 |[Letter Combinations of a Phone Number](src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Backtracking | 262 | 73.59 +| 0022 |[Generate Parentheses](src/main/kotlin/g0001_0100/s0022_generate_parentheses)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Backtracking | 210 | 78.51 +| 0079 |[Word Search](src/main/kotlin/g0001_0100/s0079_word_search)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Matrix, Backtracking | 463 | 68.49 -#### Day 16 +#### Day 12 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0981 |[Time Based Key-Value Store](src/main/kotlin/g0901_1000/s0981_time_based_key_value_store)| Medium | String, Hash_Table, Binary_Search, Design | 1555 | 10.00 +| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 +| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 -#### Day 17 +#### Day 13 Dynamic Programming | | | | | | |-|-|-|-|-|- +| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy | 227 | 98.14 +| 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics | 209 | 49.18 -#### Day 18 +#### Day 14 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 1146 |[Snapshot Array](src/main/kotlin/g1101_1200/s1146_snapshot_array)| Medium | Array, Hash_Table, Binary_Search, Design | 1064 | 57.14 +| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 +| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 -#### Day 19 +#### Day 15 Dynamic Programming | | | | | | |-|-|-|-|-|- +| 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 237 | 76.88 +| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 -#### Day 20 +#### Day 16 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design | 766 | 83.33 - -### Dynamic Programming I +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 0673 |[Number of Longest Increasing Subsequence](src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence)| Medium | Array, Dynamic_Programming, Segment_Tree, Binary_Indexed_Tree | 226 | 91.67 -#### Day 1 +#### Day 17 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 -| 1137 |[N-th Tribonacci Number](src/main/kotlin/g1101_1200/s1137_n_th_tribonacci_number)| Easy | Dynamic_Programming, Math, Memoization | 122 | 69.35 +| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 +| 0583 |[Delete Operation for Two Strings](src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings)| Medium | String, Dynamic_Programming | 197 | 100.00 -#### Day 2 +#### Day 18 Dynamic Programming | | | | | | |-|-|-|-|-|- -| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 -| 0746 |[Min Cost Climbing Stairs](src/main/kotlin/g0701_0800/s0746_min_cost_climbing_stairs)| Easy | Array, Dynamic_Programming | 171 | 96.76 +| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 +| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search | 332 | 50.68 +| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 -#### Day 3 +#### Day 19 Bit Manipulation | | | | | | |-|-|-|-|-|- -| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 -| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 -| 0740 |[Delete and Earn](src/main/kotlin/g0701_0800/s0740_delete_and_earn)| Medium | Array, Hash_Table, Dynamic_Programming | 192 | 100.00 +| 0201 |[Bitwise AND of Numbers Range](src/main/kotlin/g0201_0300/s0201_bitwise_and_of_numbers_range)| Medium | Bit_Manipulation | 368 | 80.00 -#### Day 4 +#### Day 20 Others | | | | | | |-|-|-|-|-|- -| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 -| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy | 227 | 98.14 +| 0384 |[Shuffle an Array](src/main/kotlin/g0301_0400/s0384_shuffle_an_array)| Medium | Top_Interview_Questions, Array, Math, Randomized | 940 | 72.09 -#### Day 5 +#### Day 21 Others | | | | | | |-|-|-|-|-|- -| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 -| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 339 | 86.96 - +| 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 +| 0149 |[Max Points on a Line](src/main/kotlin/g0101_0200/s0149_max_points_on_a_line)| Hard | Top_Interview_Questions, Array, Hash_Table, Math, Geometry | 307 | 83.33 + +### Binary Search I + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0704 |[Binary Search](src/main/kotlin/g0701_0800/s0704_binary_search)| Easy | Array, Binary_Search | 261 | 77.91 +| 0374 |[Guess Number Higher or Lower](src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower)| Easy | Binary_Search, Interactive | 134 | 94.19 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0035 |[Search Insert Position](src/main/kotlin/g0001_0100/s0035_search_insert_position)| Easy | Top_100_Liked_Questions, Array, Binary_Search | 267 | 50.32 +| 0852 |[Peak Index in a Mountain Array](src/main/kotlin/g0801_0900/s0852_peak_index_in_a_mountain_array)| Easy | Array, Binary_Search | 433 | 94.29 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0367 |[Valid Perfect Square](src/main/kotlin/g0301_0400/s0367_valid_perfect_square)| Easy | Math, Binary_Search | 137 | 94.55 +| 1385 |[Find the Distance Value Between Two Arrays](src/main/kotlin/g1301_1400/s1385_find_the_distance_value_between_two_arrays)| Easy | Array, Sorting, Binary_Search, Two_Pointers | 190 | 84.62 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 0069 |[Sqrt(x)](src/main/kotlin/g0001_0100/s0069_sqrtx)| Easy | Top_Interview_Questions, Math, Binary_Search | 153 | 95.75 +| 0744 |[Find Smallest Letter Greater Than Target](src/main/kotlin/g0701_0800/s0744_find_smallest_letter_greater_than_target)| Easy | Array, Binary_Search | 162 | 100.00 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0278 |[First Bad Version](src/main/kotlin/g0201_0300/s0278_first_bad_version)| Easy | Binary_Search, Interactive | 349 | 76.86 +| 0034 |[Find First and Last Position of Element in Sorted Array](src/main/kotlin/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 228 | 83.38 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- +| 0441 |[Arranging Coins](src/main/kotlin/g0401_0500/s0441_arranging_coins)| Easy | Math, Binary_Search | 150 | 84.21 + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- +| 0167 |[Two Sum II - Input Array Is Sorted](src/main/kotlin/g0101_0200/s0167_two_sum_ii_input_array_is_sorted)| Medium | Array, Binary_Search, Two_Pointers | 403 | 68.74 + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 1351 |[Count Negative Numbers in a Sorted Matrix](src/main/kotlin/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix)| Easy | Array, Binary_Search, Matrix | 206 | 71.43 +| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- +| 1337 |[The K Weakest Rows in a Matrix](src/main/kotlin/g1301_1400/s1337_the_k_weakest_rows_in_a_matrix)| Easy | Array, Sorting, Binary_Search, Matrix, Heap_Priority_Queue | 216 | 77.59 +| 1346 |[Check If N and Its Double Exist](src/main/kotlin/g1301_1400/s1346_check_if_n_and_its_double_exist)| Easy | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 175 | 70.83 + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 321 | 73.37 +| 0633 |[Sum of Square Numbers](src/main/kotlin/g0601_0700/s0633_sum_of_square_numbers)| Medium | Math, Binary_Search, Two_Pointers | 126 | 100.00 + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- +| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 + +### Binary Search II + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 +| 0611 |[Valid Triangle Number](src/main/kotlin/g0601_0700/s0611_valid_triangle_number)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 203 | 100.00 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue | 375 | 95.16 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 0875 |[Koko Eating Bananas](src/main/kotlin/g0801_0900/s0875_koko_eating_bananas)| Medium | Array, Binary_Search | 267 | 93.85 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0287 |[Find the Duplicate Number](src/main/kotlin/g0201_0300/s0287_find_the_duplicate_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Two_Pointers, Bit_Manipulation | 656 | 66.21 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer | 460 | 66.08 +| 0275 |[H-Index II](src/main/kotlin/g0201_0300/s0275_h_index_ii)| Medium | Array, Binary_Search | 398 | 81.82 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- +| 0540 |[Single Element in a Sorted Array](src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array)| Medium | Array, Binary_Search | 274 | 86.67 + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- +| 0826 |[Most Profit Assigning Work](src/main/kotlin/g0801_0900/s0826_most_profit_assigning_work)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 366 | 100.00 +| 0436 |[Find Right Interval](src/main/kotlin/g0401_0500/s0436_find_right_interval)| Medium | Array, Sorting, Binary_Search | 333 | 100.00 + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search | 352 | 42.31 +| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 + +#### Day 13 + +| | | | | | +|-|-|-|-|-|- +| 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 +| 0528 |[Random Pick with Weight](src/main/kotlin/g0501_0600/s0528_random_pick_with_weight)| Medium | Math, Binary_Search, Prefix_Sum, Randomized | 393 | 91.38 + +#### Day 14 + +| | | | | | +|-|-|-|-|-|- + +#### Day 15 + +| | | | | | +|-|-|-|-|-|- + +#### Day 16 + +| | | | | | +|-|-|-|-|-|- +| 0981 |[Time Based Key-Value Store](src/main/kotlin/g0901_1000/s0981_time_based_key_value_store)| Medium | String, Hash_Table, Binary_Search, Design | 1555 | 10.00 + +#### Day 17 + +| | | | | | +|-|-|-|-|-|- + +#### Day 18 + +| | | | | | +|-|-|-|-|-|- +| 1146 |[Snapshot Array](src/main/kotlin/g1101_1200/s1146_snapshot_array)| Medium | Array, Hash_Table, Binary_Search, Design | 1064 | 57.14 + +#### Day 19 + +| | | | | | +|-|-|-|-|-|- + +#### Day 20 + +| | | | | | +|-|-|-|-|-|- +| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design | 766 | 83.33 + +### Dynamic Programming I + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 +| 1137 |[N-th Tribonacci Number](src/main/kotlin/g1101_1200/s1137_n_th_tribonacci_number)| Easy | Dynamic_Programming, Math, Memoization | 122 | 69.35 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 +| 0746 |[Min Cost Climbing Stairs](src/main/kotlin/g0701_0800/s0746_min_cost_climbing_stairs)| Easy | Array, Dynamic_Programming | 171 | 96.76 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 +| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 +| 0740 |[Delete and Earn](src/main/kotlin/g0701_0800/s0740_delete_and_earn)| Medium | Array, Hash_Table, Dynamic_Programming | 192 | 100.00 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 +| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy | 227 | 98.14 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 +| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 339 | 86.96 + #### Day 6 | | | | | | @@ -830,6 +1191,7 @@ | | | | | | |-|-|-|-|-|- +| 1314 |[Matrix Block Sum](src/main/kotlin/g1301_1400/s1314_matrix_block_sum)| Medium | Array, Matrix, Prefix_Sum | 235 | 100.00 | 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 #### Day 15 @@ -938,6 +1300,7 @@ | | | | | | |-|-|-|-|-|- | 0709 |[To Lower Case](src/main/kotlin/g0701_0800/s0709_to_lower_case)| Easy | String | 142 | 98.68 +| 1309 |[Decrypt String from Alphabet to Integer Mapping](src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping)| Easy | String | 129 | 95.45 | 0953 |[Verifying an Alien Dictionary](src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary)| Easy | Array, String, Hash_Table | 137 | 100.00 #### Day 10 Linked List and Tree @@ -952,6 +1315,7 @@ | | | | | | |-|-|-|-|-|- +| 1356 |[Sort Integers by The Number of 1 Bits](src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits)| Easy | Array, Sorting, Bit_Manipulation, Counting | 236 | 92.31 | 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 | 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 | 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 @@ -989,6 +1353,7 @@ | | | | | | |-|-|-|-|-|- +| 1367 |[Linked List in Binary Tree](src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 237 | 92.86 | 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 390 | 56.25 #### Day 5 @@ -1035,6 +1400,7 @@ | | | | | | |-|-|-|-|-|- +| 1376 |[Time Needed to Inform All Employees](src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree | 915 | 37.62 | 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting | 506 | 86.55 #### Day 12 @@ -1152,11 +1518,13 @@ | | | | | | |-|-|-|-|-|- | 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 +| 1319 |[Number of Operations to Make Network Connected](src/main/kotlin/g1301_1400/s1319_number_of_operations_to_make_network_connected)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 379 | 83.33 #### Day 9 Standard Traversal | | | | | | |-|-|-|-|-|- +| 1376 |[Time Needed to Inform All Employees](src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree | 915 | 37.62 | 0802 |[Find Eventual Safe States](src/main/kotlin/g0801_0900/s0802_find_eventual_safe_states)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Topological_Sort | 511 | 100.00 #### Day 10 Standard Traversal @@ -1170,6 +1538,7 @@ | | | | | | |-|-|-|-|-|- +| 1306 |[Jump Game III](src/main/kotlin/g1301_1400/s1306_jump_game_iii)| Medium | Array, Depth_First_Search, Breadth_First_Search | 291 | 100.00 | 0365 |[Water and Jug Problem](src/main/kotlin/g0301_0400/s0365_water_and_jug_problem)| Medium | Math, Depth_First_Search, Breadth_First_Search | 130 | 100.00 #### Day 12 Breadth First Search @@ -1253,6 +1622,8 @@ | | | | | | |-|-|-|-|-|- +| 1393 |[Capital Gain/Loss](src/main/kotlin/g1301_1400/s1393_capital_gainloss)| Medium | LeetCode_Curated_SQL_70, Database | 990 | 47.36 +| 1407 |[Top Travellers](src/main/kotlin/g1401_1500/s1407_top_travellers)| Easy | LeetCode_Curated_SQL_70, Database | 2035 | 14.53 | 1158 |[Market Analysis I](src/main/kotlin/g1101_1200/s1158_market_analysis_i)| Medium | Database | 2470 | 44.76 #### Day 10 Where @@ -1369,366 +1740,136 @@ | 1046 |[Last Stone Weight](src/main/kotlin/g1001_1100/s1046_last_stone_weight)| Easy | Array, Heap_Priority_Queue | 123 | 100.00 | 0692 |[Top K Frequent Words](src/main/kotlin/g0601_0700/s0692_top_k_frequent_words)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Trie, Bucket_Sort | 239 | 81.10 -### Level 2 - -#### Day 1 Implementation/Simulation - -| | | | | | -|-|-|-|-|-|- -| 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 -| 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 224 | 62.50 - -#### Day 2 String - -| | | | | | -|-|-|-|-|-|- -| 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String | 209 | 88.86 -| 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 390 | 56.25 - -#### Day 3 Linked List - -| | | | | | -|-|-|-|-|-|- -| 0019 |[Remove Nth Node From End of List](src/main/kotlin/g0001_0100/s0019_remove_nth_node_from_end_of_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Linked_List | 180 | 91.58 -| 0234 |[Palindrome Linked List](src/main/kotlin/g0201_0300/s0234_palindrome_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Stack, Linked_List, Recursion | 641 | 79.53 - -#### Day 4 Linked List - -| | | | | | -|-|-|-|-|-|- -| 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List | 216 | 86.96 -| 0148 |[Sort List](src/main/kotlin/g0101_0200/s0148_sort_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Sorting, Two_Pointers, Linked_List, Divide_and_Conquer, Merge_Sort | 820 | 61.70 - -#### Day 5 Greedy - -| | | | | | -|-|-|-|-|-|- -| 0621 |[Task Scheduler](src/main/kotlin/g0601_0700/s0621_task_scheduler)| Medium | Array, Hash_Table, Sorting, Greedy, Heap_Priority_Queue, Counting | 266 | 98.36 - -#### Day 6 Tree - -| | | | | | -|-|-|-|-|-|- -| 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 -| 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 310 | 63.63 - -#### Day 7 Tree - -| | | | | | -|-|-|-|-|-|- -| 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 307 | 43.93 -| 0437 |[Path Sum III](src/main/kotlin/g0401_0500/s0437_path_sum_iii)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 403 | 54.12 - -#### Day 8 Binary Search - -| | | | | | -|-|-|-|-|-|- -| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 -| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 - -#### Day 9 Binary Search Tree - -| | | | | | -|-|-|-|-|-|- -| 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 -| 0230 |[Kth Smallest Element in a BST](src/main/kotlin/g0201_0300/s0230_kth_smallest_element_in_a_bst)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 393 | 33.33 -| 0173 |[Binary Search Tree Iterator](src/main/kotlin/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 563 | 46.91 - -#### Day 10 Graph/BFS/DFS - -| | | | | | -|-|-|-|-|-|- -| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 164 | 82.95 -| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 - -#### Day 11 Graph/BFS/DFS - -| | | | | | -|-|-|-|-|-|- -| 0210 |[Course Schedule II](src/main/kotlin/g0201_0300/s0210_course_schedule_ii)| Medium | Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Graph, Topological_Sort | 266 | 96.32 -| 0815 |[Bus Routes](src/main/kotlin/g0801_0900/s0815_bus_routes)| Hard | Array, Hash_Table, Breadth_First_Search | 429 | 100.00 - -#### Day 12 Dynamic Programming - -| | | | | | -|-|-|-|-|-|- -| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 -| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search | 332 | 50.68 - -#### Day 13 Dynamic Programming - -| | | | | | -|-|-|-|-|-|- -| 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming | 204 | 98.82 -| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 - -#### Day 14 Sliding Window/Two Pointer - -| | | | | | -|-|-|-|-|-|- -| 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 -| 0016 |[3Sum Closest](src/main/kotlin/g0001_0100/s0016_3sum_closest)| Medium | Array, Sorting, Two_Pointers | 413 | 95.05 -| 0076 |[Minimum Window Substring](src/main/kotlin/g0001_0100/s0076_minimum_window_substring)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 346 | 85.20 - -#### Day 15 Tree - -| | | | | | -|-|-|-|-|-|- -| 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 -| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 91.36 -| 0199 |[Binary Tree Right Side View](src/main/kotlin/g0101_0200/s0199_binary_tree_right_side_view)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 194 | 92.89 - -#### Day 16 Design - -| | | | | | -|-|-|-|-|-|- -| 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 -| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 -| 0208 |[Implement Trie (Prefix Tree)](src/main/kotlin/g0201_0300/s0208_implement_trie_prefix_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Design, Trie | 689 | 61.00 - -#### Day 17 Interval - -| | | | | | -|-|-|-|-|-|- -| 0057 |[Insert Interval](src/main/kotlin/g0001_0100/s0057_insert_interval)| Medium | Array | 257 | 99.52 -| 0056 |[Merge Intervals](src/main/kotlin/g0001_0100/s0056_merge_intervals)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting | 320 | 94.22 - -#### Day 18 Stack - -| | | | | | -|-|-|-|-|-|- -| 0735 |[Asteroid Collision](src/main/kotlin/g0701_0800/s0735_asteroid_collision)| Medium | Array, Stack | 243 | 100.00 -| 0227 |[Basic Calculator II](src/main/kotlin/g0201_0300/s0227_basic_calculator_ii)| Medium | Top_Interview_Questions, String, Math, Stack | 383 | 62.50 - -#### Day 19 Union Find - -| | | | | | -|-|-|-|-|-|- -| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 -| 0947 |[Most Stones Removed with Same Row or Column](src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column)| Medium | Depth_First_Search, Graph, Union_Find | 200 | 100.00 - -#### Day 20 Brute Force/Backtracking - -| | | | | | -|-|-|-|-|-|- -| 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 -| 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 - -### Udemy - -#### Udemy Integers - -| | | | | | -|-|-|-|-|-|- -| 0412 |[Fizz Buzz](src/main/kotlin/g0401_0500/s0412_fizz_buzz)| Easy | Top_Interview_Questions, String, Math, Simulation | 307 | 71.81 -| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 -| 0007 |[Reverse Integer](src/main/kotlin/g0001_0100/s0007_reverse_integer)| Medium | Top_Interview_Questions, Math | 245 | 60.32 -| 0009 |[Palindrome Number](src/main/kotlin/g0001_0100/s0009_palindrome_number)| Easy | Math | 238 | 96.24 -| 0172 |[Factorial Trailing Zeroes](src/main/kotlin/g0101_0200/s0172_factorial_trailing_zeroes)| Medium | Top_Interview_Questions, Math | 220 | 67.65 -| 0050 |[Pow(x, n)](src/main/kotlin/g0001_0100/s0050_powx_n)| Medium | Top_Interview_Questions, Math, Recursion | 264 | 52.98 - -#### Udemy Strings - -| | | | | | -|-|-|-|-|-|- -| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 -| 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String | 209 | 88.86 -| 0187 |[Repeated DNA Sequences](src/main/kotlin/g0101_0200/s0187_repeated_dna_sequences)| Medium | String, Hash_Table, Bit_Manipulation, Sliding_Window, Hash_Function, Rolling_Hash | 319 | 79.03 -| 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 -| 0020 |[Valid Parentheses](src/main/kotlin/g0001_0100/s0020_valid_parentheses)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, String, Stack | 226 | 72.53 -| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 -| 0394 |[Decode String](src/main/kotlin/g0301_0400/s0394_decode_string)| Medium | Top_100_Liked_Questions, String, Stack, Recursion | 224 | 64.86 -| 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 -| 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting | 506 | 86.55 -| 0151 |[Reverse Words in a String](src/main/kotlin/g0101_0200/s0151_reverse_words_in_a_string)| Medium | String, Two_Pointers | 206 | 98.90 -| 0273 |[Integer to English Words](src/main/kotlin/g0201_0300/s0273_integer_to_english_words)| Hard | String, Math, Recursion | 273 | 82.93 - -#### Udemy Binary Search - -| | | | | | -|-|-|-|-|-|- -| 0704 |[Binary Search](src/main/kotlin/g0701_0800/s0704_binary_search)| Easy | Array, Binary_Search | 261 | 77.91 -| 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 -| 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 - -#### Udemy Arrays - -| | | | | | -|-|-|-|-|-|- -| 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 609 | 94.06 -| 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers | 516 | 79.07 -| 0001 |[Two Sum](src/main/kotlin/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 234 | 92.75 -| 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 -| 0058 |[Length of Last Word](src/main/kotlin/g0001_0100/s0058_length_of_last_word)| Easy | String | 243 | 63.33 -| 0605 |[Can Place Flowers](src/main/kotlin/g0601_0700/s0605_can_place_flowers)| Easy | Array, Greedy | 209 | 85.71 -| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 -| 0080 |[Remove Duplicates from Sorted Array II](src/main/kotlin/g0001_0100/s0080_remove_duplicates_from_sorted_array_ii)| Medium | Array, Two_Pointers | 357 | 44.78 -| 0189 |[Rotate Array](src/main/kotlin/g0101_0200/s0189_rotate_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Two_Pointers | 483 | 86.95 -| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 -| 0075 |[Sort Colors](src/main/kotlin/g0001_0100/s0075_sort_colors)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 198 | 85.66 -| 0066 |[Plus One](src/main/kotlin/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 303 | 35.18 -| 0238 |[Product of Array Except Self](src/main/kotlin/g0201_0300/s0238_product_of_array_except_self)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Prefix_Sum | 669 | 48.96 -| 0448 |[Find All Numbers Disappeared in an Array](src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array)| Easy | Array, Hash_Table | 394 | 100.00 -| 0442 |[Find All Duplicates in an Array](src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array)| Medium | Array, Hash_Table | 480 | 73.81 -| 0041 |[First Missing Positive](src/main/kotlin/g0001_0100/s0041_first_missing_positive)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 345 | 100.00 -| 0697 |[Degree of an Array](src/main/kotlin/g0601_0700/s0697_degree_of_an_array)| Easy | Array, Hash_Table | 289 | 84.62 -| 0532 |[K-diff Pairs in an Array](src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array)| Medium | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 230 | 84.62 -| 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 -| 1007 |[Minimum Domino Rotations For Equal Row](src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row)| Medium | Array, Greedy | 421 | 50.00 -| 0456 |[132 Pattern](src/main/kotlin/g0401_0500/s0456_132_pattern)| Medium | Array, Binary_Search, Stack, Ordered_Set, Monotonic_Stack | 434 | 100.00 -| 0239 |[Sliding Window Maximum](src/main/kotlin/g0201_0300/s0239_sliding_window_maximum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 1059 | 86.14 - -#### Udemy Two Pointers - -| | | | | | -|-|-|-|-|-|- -| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 -| 0125 |[Valid Palindrome](src/main/kotlin/g0101_0200/s0125_valid_palindrome)| Easy | Top_Interview_Questions, String, Two_Pointers | 353 | 52.06 -| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 375 | 18.43 -| 0026 |[Remove Duplicates from Sorted Array](src/main/kotlin/g0001_0100/s0026_remove_duplicates_from_sorted_array)| Easy | Top_Interview_Questions, Array, Two_Pointers | 361 | 77.19 -| 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack | 196 | 100.00 -| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 761 | 90.55 - -#### Udemy Famous Algorithm - -| | | | | | -|-|-|-|-|-|- -| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 -| 0169 |[Majority Element](src/main/kotlin/g0101_0200/s0169_majority_element)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Counting, Divide_and_Conquer | 460 | 51.25 - -#### Udemy Sorting Algorithms - -| | | | | | -|-|-|-|-|-|- -| 0912 |[Sort an Array](src/main/kotlin/g0901_1000/s0912_sort_an_array)| Medium | Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Merge_Sort, Bucket_Sort, Counting_Sort, Radix_Sort | 606 | 98.48 - -#### Udemy 2D Arrays/Matrix - -| | | | | | -|-|-|-|-|-|- -| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 -| 0074 |[Search a 2D Matrix](src/main/kotlin/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 290 | 40.17 -| 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 224 | 62.50 -| 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix | 287 | 46.50 -| 0073 |[Set Matrix Zeroes](src/main/kotlin/g0001_0100/s0073_set_matrix_zeroes)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Matrix | 255 | 100.00 -| 0056 |[Merge Intervals](src/main/kotlin/g0001_0100/s0056_merge_intervals)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting | 320 | 94.22 - -#### Udemy Linked List - -| | | | | | -|-|-|-|-|-|- -| 0114 |[Flatten Binary Tree to Linked List](src/main/kotlin/g0101_0200/s0114_flatten_binary_tree_to_linked_list)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Stack, Linked_List | 191 | 93.10 -| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 240 | 82.61 -| 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List | 216 | 86.96 -| 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 193 | 92.16 -| 0024 |[Swap Nodes in Pairs](src/main/kotlin/g0001_0100/s0024_swap_nodes_in_pairs)| Medium | Top_100_Liked_Questions, Linked_List, Recursion | 149 | 99.39 -| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 -| 0142 |[Linked List Cycle II](src/main/kotlin/g0101_0200/s0142_linked_list_cycle_ii)| Medium | Top_100_Liked_Questions, Hash_Table, Two_Pointers, Linked_List | 192 | 63.39 -| 0141 |[Linked List Cycle](src/main/kotlin/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 223 | 91.85 -| 0206 |[Reverse Linked List](src/main/kotlin/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 279 | 45.78 -| 0021 |[Merge Two Sorted Lists](src/main/kotlin/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 176 | 96.25 -| 0160 |[Intersection of Two Linked Lists](src/main/kotlin/g0101_0200/s0160_intersection_of_two_linked_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 262 | 83.50 -| 0234 |[Palindrome Linked List](src/main/kotlin/g0201_0300/s0234_palindrome_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Stack, Linked_List, Recursion | 641 | 79.53 -| 0138 |[Copy List with Random Pointer](src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Linked_List | 274 | 80.58 -| 0025 |[Reverse Nodes in k-Group](src/main/kotlin/g0001_0100/s0025_reverse_nodes_in_k_group)| Hard | Top_100_Liked_Questions, Linked_List, Recursion | 194 | 87.72 -| 0146 |[LRU Cache](src/main/kotlin/g0101_0200/s0146_lru_cache)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Design, Linked_List, Doubly_Linked_List | 1116 | 97.93 -| 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 - -#### Udemy Tree Stack Queue - -| | | | | | -|-|-|-|-|-|- -| 0144 |[Binary Tree Preorder Traversal](src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 277 | 37.90 -| 0094 |[Binary Tree Inorder Traversal](src/main/kotlin/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 269 | 38.80 -| 0145 |[Binary Tree Postorder Traversal](src/main/kotlin/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 211 | 80.00 -| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 -| 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 316 | 34.25 -| 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 -| 1008 |[Construct Binary Search Tree from Preorder Traversal](src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal)| Medium | Array, Tree, Binary_Tree, Stack, Monotonic_Stack, Binary_Search_Tree | 145 | 100.00 -| 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 307 | 43.93 -| 0938 |[Range Sum of BST](src/main/kotlin/g0901_1000/s0938_range_sum_of_bst)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 356 | 55.36 -| 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 -| 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 -| 0111 |[Minimum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 525 | 90.51 -| 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 236 | 83.39 -| 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 310 | 63.63 -| 0701 |[Insert into a Binary Search Tree](src/main/kotlin/g0701_0800/s0701_insert_into_a_binary_search_tree)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 311 | 79.03 -| 0297 |[Serialize and Deserialize Binary Tree](src/main/kotlin/g0201_0300/s0297_serialize_and_deserialize_binary_tree)| Hard | Top_Interview_Questions, String, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Design | 475 | 78.85 -| 0124 |[Binary Tree Maximum Path Sum](src/main/kotlin/g0101_0200/s0124_binary_tree_maximum_path_sum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 331 | 74.42 -| 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 -| 0337 |[House Robber III](src/main/kotlin/g0301_0400/s0337_house_robber_iii)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 282 | 84.62 -| 0236 |[Lowest Common Ancestor of a Binary Tree](src/main/kotlin/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree | 386 | 45.21 -| 0968 |[Binary Tree Cameras](src/main/kotlin/g0901_1000/s0968_binary_tree_cameras)| Hard | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 176 | 100.00 - -#### Udemy Trie and Heap - -| | | | | | -|-|-|-|-|-|- -| 0208 |[Implement Trie (Prefix Tree)](src/main/kotlin/g0201_0300/s0208_implement_trie_prefix_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Design, Trie | 689 | 61.00 -| 0745 |[Prefix and Suffix Search](src/main/kotlin/g0701_0800/s0745_prefix_and_suffix_search)| Hard | String, Design, Trie | 1638 | 100.00 - -#### Udemy Graph - -| | | | | | -|-|-|-|-|-|- -| 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 252 | 95.41 -| 0133 |[Clone Graph](src/main/kotlin/g0101_0200/s0133_clone_graph)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Graph | 351 | 60.91 -| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 - -#### Udemy Dynamic Programming - -| | | | | | -|-|-|-|-|-|- -| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 -| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 -| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 -| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 -| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 -| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 -| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 -| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 -| 0064 |[Minimum Path Sum](src/main/kotlin/g0001_0100/s0064_minimum_path_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix | 222 | 95.70 -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 -| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 -| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 -| 0044 |[Wildcard Matching](src/main/kotlin/g0001_0100/s0044_wildcard_matching)| Hard | Top_Interview_Questions, String, Dynamic_Programming, Greedy, Recursion | 401 | 86.11 -| 0010 |[Regular Expression Matching](src/main/kotlin/g0001_0100/s0010_regular_expression_matching)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Recursion | 292 | 58.58 - -#### Udemy Backtracking/Recursion - -| | | | | | -|-|-|-|-|-|- -| 0022 |[Generate Parentheses](src/main/kotlin/g0001_0100/s0022_generate_parentheses)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Backtracking | 210 | 78.51 -| 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 -| 0216 |[Combination Sum III](src/main/kotlin/g0201_0300/s0216_combination_sum_iii)| Medium | Array, Backtracking | 175 | 90.91 -| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 191 | 97.44 -| 0017 |[Letter Combinations of a Phone Number](src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Backtracking | 262 | 73.59 -| 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 - -#### Udemy Bit Manipulation - -| | | | | | -|-|-|-|-|-|- -| 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 -| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 -| 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 -| 0461 |[Hamming Distance](src/main/kotlin/g0401_0500/s0461_hamming_distance)| Easy | Bit_Manipulation | 150 | 96.15 -| 1009 |[Complement of Base 10 Integer](src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer)| Easy | Bit_Manipulation | 126 | 72.73 -| 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation | 186 | 99.26 -| 0371 |[Sum of Two Integers](src/main/kotlin/g0301_0400/s0371_sum_of_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 129 | 95.45 -| 0029 |[Divide Two Integers](src/main/kotlin/g0001_0100/s0029_divide_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 281 | 31.67 - -#### Udemy Design - -| | | | | | -|-|-|-|-|-|- -| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 - ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 1450 |[Number of Students Doing Homework at a Given Time](src/main/kotlin/g1401_1500/s1450_number_of_students_doing_homework_at_a_given_time)| Easy | Array | 180 | 10.00 +| 1449 |[Form Largest Integer With Digits That Add up to Target](src/main/kotlin/g1401_1500/s1449_form_largest_integer_with_digits_that_add_up_to_target)| Hard | Array, Dynamic_Programming | 201 | 100.00 +| 1448 |[Count Good Nodes in Binary Tree](src/main/kotlin/g1401_1500/s1448_count_good_nodes_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 384 | 68.52 +| 1447 |[Simplified Fractions](src/main/kotlin/g1401_1500/s1447_simplified_fractions)| Medium | String, Math, Number_Theory | 338 | 100.00 +| 1446 |[Consecutive Characters](src/main/kotlin/g1401_1500/s1446_consecutive_characters)| Easy | String | 141 | 100.00 +| 1444 |[Number of Ways of Cutting a Pizza](src/main/kotlin/g1401_1500/s1444_number_of_ways_of_cutting_a_pizza)| Hard | Array, Dynamic_Programming, Matrix, Memoization | 175 | 75.00 +| 1443 |[Minimum Time to Collect All Apples in a Tree](src/main/kotlin/g1401_1500/s1443_minimum_time_to_collect_all_apples_in_a_tree)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree | 793 | 85.71 +| 1442 |[Count Triplets That Can Form Two Arrays of Equal XOR](src/main/kotlin/g1401_1500/s1442_count_triplets_that_can_form_two_arrays_of_equal_xor)| Medium | Array, Hash_Table, Math, Bit_Manipulation, Prefix_Sum | 145 | 100.00 +| 1441 |[Build an Array With Stack Operations](src/main/kotlin/g1401_1500/s1441_build_an_array_with_stack_operations)| Easy | Array, Stack, Simulation | 160 | 100.00 +| 1439 |[Find the Kth Smallest Sum of a Matrix With Sorted Rows](src/main/kotlin/g1401_1500/s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows)| Hard | Array, Binary_Search, Matrix, Heap_Priority_Queue | 225 | 100.00 +| 1438 |[Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](src/main/kotlin/g1401_1500/s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit)| Medium | Array, Heap_Priority_Queue, Sliding_Window, Ordered_Set, Queue, Monotonic_Queue | 479 | 75.00 +| 1437 |[Check If All 1's Are at Least Length K Places Away](src/main/kotlin/g1401_1500/s1437_check_if_all_1s_are_at_least_length_k_places_away)| Easy | Array | 345 | 66.67 +| 1436 |[Destination City](src/main/kotlin/g1401_1500/s1436_destination_city)| Easy | String, Hash_Table | 174 | 77.78 +| 1434 |[Number of Ways to Wear Different Hats to Each Other](src/main/kotlin/g1401_1500/s1434_number_of_ways_to_wear_different_hats_to_each_other)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Bitmask | 206 | 100.00 +| 1433 |[Check If a String Can Break Another String](src/main/kotlin/g1401_1500/s1433_check_if_a_string_can_break_another_string)| Medium | String, Sorting, Greedy | 221 | 100.00 +| 1432 |[Max Difference You Can Get From Changing an Integer](src/main/kotlin/g1401_1500/s1432_max_difference_you_can_get_from_changing_an_integer)| Medium | Math, Greedy | 147 | 100.00 +| 1431 |[Kids With the Greatest Number of Candies](src/main/kotlin/g1401_1500/s1431_kids_with_the_greatest_number_of_candies)| Easy | Array | 152 | 99.61 +| 1425 |[Constrained Subsequence Sum](src/main/kotlin/g1401_1500/s1425_constrained_subsequence_sum)| Hard | Array, Dynamic_Programming, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 649 | 33.33 +| 1424 |[Diagonal Traverse II](src/main/kotlin/g1401_1500/s1424_diagonal_traverse_ii)| Medium | Array, Sorting, Heap_Priority_Queue | 706 | 100.00 +| 1423 |[Maximum Points You Can Obtain from Cards](src/main/kotlin/g1401_1500/s1423_maximum_points_you_can_obtain_from_cards)| Medium | Array, Prefix_Sum, Sliding_Window | 349 | 78.57 +| 1422 |[Maximum Score After Splitting a String](src/main/kotlin/g1401_1500/s1422_maximum_score_after_splitting_a_string)| Easy | String | 145 | 100.00 +| 1420 |[Build Array Where You Can Find The Maximum Exactly K Comparisons](src/main/kotlin/g1401_1500/s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons)| Hard | Dynamic_Programming | 153 | 100.00 +| 1419 |[Minimum Number of Frogs Croaking](src/main/kotlin/g1401_1500/s1419_minimum_number_of_frogs_croaking)| Medium | String, Counting | 210 | 90.91 +| 1418 |[Display Table of Food Orders in a Restaurant](src/main/kotlin/g1401_1500/s1418_display_table_of_food_orders_in_a_restaurant)| Medium | Array, String, Hash_Table, Sorting, Ordered_Set | 710 | 100.00 +| 1417 |[Reformat The String](src/main/kotlin/g1401_1500/s1417_reformat_the_string)| Easy | String | 174 | 100.00 +| 1416 |[Restore The Array](src/main/kotlin/g1401_1500/s1416_restore_the_array)| Hard | String, Dynamic_Programming | 279 | 51.85 +| 1415 |[The k-th Lexicographical String of All Happy Strings of Length n](src/main/kotlin/g1401_1500/s1415_the_k_th_lexicographical_string_of_all_happy_strings_of_length_n)| Medium | String, Backtracking | 160 | 100.00 +| 1414 |[Find the Minimum Number of Fibonacci Numbers Whose Sum Is K](src/main/kotlin/g1401_1500/s1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k)| Medium | Greedy | 165 | 100.00 +| 1413 |[Minimum Value to Get Positive Step by Step Sum](src/main/kotlin/g1401_1500/s1413_minimum_value_to_get_positive_step_by_step_sum)| Easy | Array, Prefix_Sum | 127 | 97.22 +| 1411 |[Number of Ways to Paint N × 3 Grid](src/main/kotlin/g1401_1500/s1411_number_of_ways_to_paint_n_3_grid)| Hard | Dynamic_Programming | 201 | 100.00 +| 1410 |[HTML Entity Parser](src/main/kotlin/g1401_1500/s1410_html_entity_parser)| Medium | String, Hash_Table | 334 | 100.00 +| 1409 |[Queries on a Permutation With Key](src/main/kotlin/g1401_1500/s1409_queries_on_a_permutation_with_key)| Medium | Array, Simulation, Binary_Indexed_Tree | 209 | 100.00 +| 1408 |[String Matching in an Array](src/main/kotlin/g1401_1500/s1408_string_matching_in_an_array)| Easy | String, String_Matching | 194 | 77.78 +| 1407 |[Top Travellers](src/main/kotlin/g1401_1500/s1407_top_travellers)| Easy | LeetCode_Curated_SQL_70, Database, SQL_I_Day_9_Control_of_Flow | 2035 | 14.53 +| 1406 |[Stone Game III](src/main/kotlin/g1401_1500/s1406_stone_game_iii)| Hard | Array, Dynamic_Programming, Math, Game_Theory | 699 | 90.70 +| 1405 |[Longest Happy String](src/main/kotlin/g1401_1500/s1405_longest_happy_string)| Medium | String, Greedy, Heap_Priority_Queue | 119 | 100.00 +| 1404 |[Number of Steps to Reduce a Number in Binary Representation to One](src/main/kotlin/g1401_1500/s1404_number_of_steps_to_reduce_a_number_in_binary_representation_to_one)| Medium | String, Bit_Manipulation | 144 | 100.00 +| 1403 |[Minimum Subsequence in Non-Increasing Order](src/main/kotlin/g1401_1500/s1403_minimum_subsequence_in_non_increasing_order)| Easy | Array, Sorting, Greedy | 190 | 100.00 +| 1402 |[Reducing Dishes](src/main/kotlin/g1401_1500/s1402_reducing_dishes)| Hard | Array, Dynamic_Programming, Sorting, Greedy | 151 | 100.00 +| 1401 |[Circle and Rectangle Overlapping](src/main/kotlin/g1401_1500/s1401_circle_and_rectangle_overlapping)| Medium | Math, Geometry | 116 | 100.00 +| 1400 |[Construct K Palindrome Strings](src/main/kotlin/g1301_1400/s1400_construct_k_palindrome_strings)| Medium | String, Hash_Table, Greedy, Counting | 204 | 90.00 +| 1399 |[Count Largest Group](src/main/kotlin/g1301_1400/s1399_count_largest_group)| Easy | Hash_Table, Math | 136 | 100.00 +| 1397 |[Find All Good Strings](src/main/kotlin/g1301_1400/s1397_find_all_good_strings)| Hard | String, Dynamic_Programming, String_Matching | 273 | 100.00 +| 1396 |[Design Underground System](src/main/kotlin/g1301_1400/s1396_design_underground_system)| Medium | String, Hash_Table, Design | 703 | 99.29 +| 1395 |[Count Number of Teams](src/main/kotlin/g1301_1400/s1395_count_number_of_teams)| Medium | Array, Dynamic_Programming, Binary_Indexed_Tree | 192 | 100.00 +| 1394 |[Find Lucky Integer in an Array](src/main/kotlin/g1301_1400/s1394_find_lucky_integer_in_an_array)| Easy | Array, Hash_Table, Counting | 161 | 100.00 +| 1393 |[Capital Gain/Loss](src/main/kotlin/g1301_1400/s1393_capital_gainloss)| Medium | LeetCode_Curated_SQL_70, Database, SQL_I_Day_9_Control_of_Flow | 990 | 47.36 +| 1392 |[Longest Happy Prefix](src/main/kotlin/g1301_1400/s1392_longest_happy_prefix)| Hard | String, Hash_Function, String_Matching, Rolling_Hash | 291 | 50.00 +| 1391 |[Check if There is a Valid Path in a Grid](src/main/kotlin/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 636 | 100.00 +| 1390 |[Four Divisors](src/main/kotlin/g1301_1400/s1390_four_divisors)| Medium | Array, Math | 255 | 100.00 +| 1389 |[Create Target Array in the Given Order](src/main/kotlin/g1301_1400/s1389_create_target_array_in_the_given_order)| Easy | Array, Simulation | 155 | 91.67 +| 1388 |[Pizza With 3n Slices](src/main/kotlin/g1301_1400/s1388_pizza_with_3n_slices)| Hard | Array, Dynamic_Programming, Greedy, Heap_Priority_Queue | 170 | 100.00 +| 1387 |[Sort Integers by The Power Value](src/main/kotlin/g1301_1400/s1387_sort_integers_by_the_power_value)| Medium | Dynamic_Programming, Sorting, Memoization | 370 | 100.00 +| 1386 |[Cinema Seat Allocation](src/main/kotlin/g1301_1400/s1386_cinema_seat_allocation)| Medium | Array, Hash_Table, Greedy, Bit_Manipulation | 397 | 100.00 +| 1385 |[Find the Distance Value Between Two Arrays](src/main/kotlin/g1301_1400/s1385_find_the_distance_value_between_two_arrays)| Easy | Array, Sorting, Binary_Search, Two_Pointers, Binary_Search_I_Day_3 | 190 | 84.62 +| 1383 |[Maximum Performance of a Team](src/main/kotlin/g1301_1400/s1383_maximum_performance_of_a_team)| Hard | Array, Sorting, Greedy, Heap_Priority_Queue | 427 | 100.00 +| 1382 |[Balance a Binary Search Tree](src/main/kotlin/g1301_1400/s1382_balance_a_binary_search_tree)| Medium | Depth_First_Search, Greedy, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 369 | 85.71 +| 1381 |[Design a Stack With Increment Operation](src/main/kotlin/g1301_1400/s1381_design_a_stack_with_increment_operation)| Medium | Array, Stack, Design | 267 | 100.00 +| 1380 |[Lucky Numbers in a Matrix](src/main/kotlin/g1301_1400/s1380_lucky_numbers_in_a_matrix)| Easy | Array, Matrix | 223 | 89.29 +| 1379 |[Find a Corresponding Node of a Binary Tree in a Clone of That Tree](src/main/kotlin/g1301_1400/s1379_find_a_corresponding_node_of_a_binary_tree_in_a_clone_of_that_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 1 | 100.00 +| 1377 |[Frog Position After T Seconds](src/main/kotlin/g1301_1400/s1377_frog_position_after_t_seconds)| Hard | Depth_First_Search, Breadth_First_Search, Tree, Graph | 221 | 100.00 +| 1376 |[Time Needed to Inform All Employees](src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Programming_Skills_II_Day_11, Graph_Theory_I_Day_9_Standard_Traversal | 915 | 37.62 +| 1375 |[Number of Times Binary String Is Prefix-Aligned](src/main/kotlin/g1301_1400/s1375_number_of_times_binary_string_is_prefix_aligned)| Medium | Array | 327 | 100.00 +| 1374 |[Generate a String With Characters That Have Odd Counts](src/main/kotlin/g1301_1400/s1374_generate_a_string_with_characters_that_have_odd_counts)| Easy | String | 130 | 100.00 +| 1373 |[Maximum Sum BST in Binary Tree](src/main/kotlin/g1301_1400/s1373_maximum_sum_bst_in_binary_tree)| Hard | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 451 | 100.00 +| 1372 |[Longest ZigZag Path in a Binary Tree](src/main/kotlin/g1301_1400/s1372_longest_zigzag_path_in_a_binary_tree)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 381 | 66.11 +| 1371 |[Find the Longest Substring Containing Vowels in Even Counts](src/main/kotlin/g1301_1400/s1371_find_the_longest_substring_containing_vowels_in_even_counts)| Medium | String, Hash_Table, Bit_Manipulation, Prefix_Sum | 317 | 100.00 +| 1370 |[Increasing Decreasing String](src/main/kotlin/g1301_1400/s1370_increasing_decreasing_string)| Easy | String, Hash_Table, Counting | 189 | 33.33 +| 1368 |[Minimum Cost to Make at Least One Valid Path in a Grid](src/main/kotlin/g1301_1400/s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid)| Hard | Array, Breadth_First_Search, Matrix, Heap_Priority_Queue, Graph, Shortest_Path | 220 | 100.00 +| 1367 |[Linked List in Binary Tree](src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List, Programming_Skills_II_Day_4 | 237 | 92.86 +| 1366 |[Rank Teams by Votes](src/main/kotlin/g1301_1400/s1366_rank_teams_by_votes)| Medium | Array, String, Hash_Table, Sorting, Counting | 179 | 100.00 +| 1365 |[How Many Numbers Are Smaller Than the Current Number](src/main/kotlin/g1301_1400/s1365_how_many_numbers_are_smaller_than_the_current_number)| Easy | Array, Hash_Table, Sorting, Counting | 193 | 93.33 +| 1363 |[Largest Multiple of Three](src/main/kotlin/g1301_1400/s1363_largest_multiple_of_three)| Hard | Array, Dynamic_Programming, Greedy | 267 | 100.00 +| 1362 |[Closest Divisors](src/main/kotlin/g1301_1400/s1362_closest_divisors)| Medium | Math | 167 | 100.00 +| 1361 |[Validate Binary Tree Nodes](src/main/kotlin/g1301_1400/s1361_validate_binary_tree_nodes)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Graph, Union_Find | 316 | 83.33 +| 1360 |[Number of Days Between Two Dates](src/main/kotlin/g1301_1400/s1360_number_of_days_between_two_dates)| Easy | String, Math | 166 | 100.00 +| 1359 |[Count All Valid Pickup and Delivery Options](src/main/kotlin/g1301_1400/s1359_count_all_valid_pickup_and_delivery_options)| Hard | Dynamic_Programming, Math, Combinatorics | 121 | 100.00 +| 1358 |[Number of Substrings Containing All Three Characters](src/main/kotlin/g1301_1400/s1358_number_of_substrings_containing_all_three_characters)| Medium | String, Hash_Table, Sliding_Window | 196 | 100.00 +| 1357 |[Apply Discount Every n Orders](src/main/kotlin/g1301_1400/s1357_apply_discount_every_n_orders)| Medium | Array, Hash_Table, Design | 967 | 100.00 +| 1356 |[Sort Integers by The Number of 1 Bits](src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits)| Easy | Array, Sorting, Bit_Manipulation, Counting, Programming_Skills_I_Day_11_Containers_and_Libraries | 236 | 92.31 +| 1354 |[Construct Target Array With Multiple Sums](src/main/kotlin/g1301_1400/s1354_construct_target_array_with_multiple_sums)| Hard | Array, Heap_Priority_Queue | 289 | 100.00 +| 1353 |[Maximum Number of Events That Can Be Attended](src/main/kotlin/g1301_1400/s1353_maximum_number_of_events_that_can_be_attended)| Medium | Array, Greedy, Heap_Priority_Queue | 728 | 100.00 +| 1352 |[Product of the Last K Numbers](src/main/kotlin/g1301_1400/s1352_product_of_the_last_k_numbers)| Medium | Array, Math, Design, Queue, Data_Stream | 563 | 100.00 +| 1351 |[Count Negative Numbers in a Sorted Matrix](src/main/kotlin/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix)| Easy | Array, Binary_Search, Matrix, Binary_Search_I_Day_8 | 206 | 71.43 +| 1349 |[Maximum Students Taking Exam](src/main/kotlin/g1301_1400/s1349_maximum_students_taking_exam)| Hard | Array, Dynamic_Programming, Matrix, Bit_Manipulation, Bitmask | 173 | 100.00 +| 1348 |[Tweet Counts Per Frequency](src/main/kotlin/g1301_1400/s1348_tweet_counts_per_frequency)| Medium | Hash_Table, Sorting, Binary_Search, Design, Ordered_Set | 701 | 100.00 +| 1347 |[Minimum Number of Steps to Make Two Strings Anagram](src/main/kotlin/g1301_1400/s1347_minimum_number_of_steps_to_make_two_strings_anagram)| Medium | String, Hash_Table, Counting | 271 | 23.08 +| 1346 |[Check If N and Its Double Exist](src/main/kotlin/g1301_1400/s1346_check_if_n_and_its_double_exist)| Easy | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers, Binary_Search_I_Day_9 | 175 | 70.83 +| 1345 |[Jump Game IV](src/main/kotlin/g1301_1400/s1345_jump_game_iv)| Hard | Array, Hash_Table, Breadth_First_Search | 599 | 100.00 +| 1344 |[Angle Between Hands of a Clock](src/main/kotlin/g1301_1400/s1344_angle_between_hands_of_a_clock)| Medium | Math | 118 | 83.33 +| 1343 |[Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold](src/main/kotlin/g1301_1400/s1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold)| Medium | Array, Sliding_Window | 394 | 84.62 +| 1342 |[Number of Steps to Reduce a Number to Zero](src/main/kotlin/g1301_1400/s1342_number_of_steps_to_reduce_a_number_to_zero)| Easy | Math, Bit_Manipulation | 124 | 83.18 +| 1340 |[Jump Game V](src/main/kotlin/g1301_1400/s1340_jump_game_v)| Hard | Array, Dynamic_Programming, Sorting | 208 | 100.00 +| 1339 |[Maximum Product of Splitted Binary Tree](src/main/kotlin/g1301_1400/s1339_maximum_product_of_splitted_binary_tree)| Medium | Depth_First_Search, Tree, Binary_Tree | 384 | 100.00 +| 1338 |[Reduce Array Size to The Half](src/main/kotlin/g1301_1400/s1338_reduce_array_size_to_the_half)| Medium | Array, Hash_Table, Sorting, Greedy, Heap_Priority_Queue | 579 | 71.43 +| 1337 |[The K Weakest Rows in a Matrix](src/main/kotlin/g1301_1400/s1337_the_k_weakest_rows_in_a_matrix)| Easy | Array, Sorting, Binary_Search, Matrix, Heap_Priority_Queue, Binary_Search_I_Day_9 | 216 | 77.59 +| 1335 |[Minimum Difficulty of a Job Schedule](src/main/kotlin/g1301_1400/s1335_minimum_difficulty_of_a_job_schedule)| Hard | Array, Dynamic_Programming | 154 | 100.00 +| 1334 |[Find the City With the Smallest Number of Neighbors at a Threshold Distance](src/main/kotlin/g1301_1400/s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance)| Medium | Dynamic_Programming, Graph, Shortest_Path | 223 | 88.89 +| 1333 |[Filter Restaurants by Vegan-Friendly, Price and Distance](src/main/kotlin/g1301_1400/s1333_filter_restaurants_by_vegan_friendly_price_and_distance)| Medium | Array, Sorting | 326 | 100.00 +| 1332 |[Remove Palindromic Subsequences](src/main/kotlin/g1301_1400/s1332_remove_palindromic_subsequences)| Easy | String, Two_Pointers | 122 | 83.33 +| 1331 |[Rank Transform of an Array](src/main/kotlin/g1301_1400/s1331_rank_transform_of_an_array)| Easy | Array, Hash_Table, Sorting | 553 | 100.00 +| 1330 |[Reverse Subarray To Maximize Array Value](src/main/kotlin/g1301_1400/s1330_reverse_subarray_to_maximize_array_value)| Hard | Array, Math, Greedy | 347 | 100.00 +| 1329 |[Sort the Matrix Diagonally](src/main/kotlin/g1301_1400/s1329_sort_the_matrix_diagonally)| Medium | Array, Sorting, Matrix | 243 | 100.00 +| 1328 |[Break a Palindrome](src/main/kotlin/g1301_1400/s1328_break_a_palindrome)| Medium | String, Greedy | 137 | 81.82 +| 1326 |[Minimum Number of Taps to Open to Water a Garden](src/main/kotlin/g1301_1400/s1326_minimum_number_of_taps_to_open_to_water_a_garden)| Hard | Array, Dynamic_Programming, Greedy | 189 | 100.00 +| 1325 |[Delete Leaves With a Given Value](src/main/kotlin/g1301_1400/s1325_delete_leaves_with_a_given_value)| Medium | Depth_First_Search, Tree, Binary_Tree | 185 | 100.00 +| 1324 |[Print Words Vertically](src/main/kotlin/g1301_1400/s1324_print_words_vertically)| Medium | Array, String, Simulation | 149 | 66.67 +| 1323 |[Maximum 69 Number](src/main/kotlin/g1301_1400/s1323_maximum_69_number)| Easy | Math, Greedy | 118 | 90.00 +| 1320 |[Minimum Distance to Type a Word Using Two Fingers](src/main/kotlin/g1301_1400/s1320_minimum_distance_to_type_a_word_using_two_fingers)| Hard | String, Dynamic_Programming | 181 | 100.00 +| 1319 |[Number of Operations to Make Network Connected](src/main/kotlin/g1301_1400/s1319_number_of_operations_to_make_network_connected)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find, Graph_Theory_I_Day_8_Standard_Traversal | 379 | 83.33 +| 1318 |[Minimum Flips to Make a OR b Equal to c](src/main/kotlin/g1301_1400/s1318_minimum_flips_to_make_a_or_b_equal_to_c)| Medium | Bit_Manipulation | 123 | 88.89 +| 1317 |[Convert Integer to the Sum of Two No-Zero Integers](src/main/kotlin/g1301_1400/s1317_convert_integer_to_the_sum_of_two_no_zero_integers)| Easy | Math | 146 | 100.00 +| 1316 |[Distinct Echo Substrings](src/main/kotlin/g1301_1400/s1316_distinct_echo_substrings)| Hard | String, Dynamic_Programming, Sliding_Window, Trie, Hash_Function, Rolling_Hash | 371 | 100.00 +| 1315 |[Sum of Nodes with Even-Valued Grandparent](src/main/kotlin/g1301_1400/s1315_sum_of_nodes_with_even_valued_grandparent)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 257 | 82.35 +| 1314 |[Matrix Block Sum](src/main/kotlin/g1301_1400/s1314_matrix_block_sum)| Medium | Array, Matrix, Prefix_Sum, Dynamic_Programming_I_Day_14 | 235 | 100.00 +| 1313 |[Decompress Run-Length Encoded List](src/main/kotlin/g1301_1400/s1313_decompress_run_length_encoded_list)| Easy | Array | 196 | 100.00 +| 1312 |[Minimum Insertion Steps to Make a String Palindrome](src/main/kotlin/g1301_1400/s1312_minimum_insertion_steps_to_make_a_string_palindrome)| Hard | String, Dynamic_Programming | 186 | 67.70 +| 1311 |[Get Watched Videos by Your Friends](src/main/kotlin/g1301_1400/s1311_get_watched_videos_by_your_friends)| Medium | Array, Hash_Table, Sorting, Breadth_First_Search | 372 | 100.00 +| 1310 |[XOR Queries of a Subarray](src/main/kotlin/g1301_1400/s1310_xor_queries_of_a_subarray)| Medium | Array, Bit_Manipulation, Prefix_Sum | 382 | 100.00 +| 1309 |[Decrypt String from Alphabet to Integer Mapping](src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping)| Easy | String, Programming_Skills_I_Day_9_String | 129 | 95.45 +| 1307 |[Verbal Arithmetic Puzzle](src/main/kotlin/g1301_1400/s1307_verbal_arithmetic_puzzle)| Hard | Array, String, Math, Backtracking | 164 | 100.00 +| 1306 |[Jump Game III](src/main/kotlin/g1301_1400/s1306_jump_game_iii)| Medium | Array, Depth_First_Search, Breadth_First_Search, Graph_Theory_I_Day_11_Breadth_First_Search, Udemy_Arrays | 291 | 100.00 +| 1305 |[All Elements in Two Binary Search Trees](src/main/kotlin/g1301_1400/s1305_all_elements_in_two_binary_search_trees)| Medium | Sorting, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 531 | 100.00 +| 1304 |[Find N Unique Integers Sum up to Zero](src/main/kotlin/g1301_1400/s1304_find_n_unique_integers_sum_up_to_zero)| Easy | Array, Math | 142 | 100.00 +| 1302 |[Deepest Leaves Sum](src/main/kotlin/g1301_1400/s1302_deepest_leaves_sum)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 325 | 67.39 +| 1301 |[Number of Paths with Max Score](src/main/kotlin/g1301_1400/s1301_number_of_paths_with_max_score)| Hard | Array, Dynamic_Programming, Matrix | 178 | 100.00 | 1200 |[Minimum Absolute Difference](src/main/kotlin/g1101_1200/s1200_minimum_absolute_difference)| Easy | Array, Sorting | 507 | 75.00 | 1195 |[Fizz Buzz Multithreaded](src/main/kotlin/g1101_1200/s1195_fizz_buzz_multithreaded)| Medium | Concurrency | 6 | 87.26 | 1192 |[Critical Connections in a Network](src/main/kotlin/g1101_1200/s1192_critical_connections_in_a_network)| Hard | Depth_First_Search, Graph, Biconnected_Component | 1696 | 60.00 @@ -1747,6 +1888,7 @@ | 1171 |[Remove Zero Sum Consecutive Nodes from Linked List](src/main/kotlin/g1101_1200/s1171_remove_zero_sum_consecutive_nodes_from_linked_list)| Medium | Hash_Table, Linked_List | 194 | 50.00 | 1170 |[Compare Strings by Frequency of the Smallest Character](src/main/kotlin/g1101_1200/s1170_compare_strings_by_frequency_of_the_smallest_character)| Medium | Array, String, Hash_Table, Sorting, Binary_Search | 221 | 50.00 | 1169 |[Invalid Transactions](src/main/kotlin/g1101_1200/s1169_invalid_transactions)| Medium | Array, String, Hash_Table, Sorting | 362 | 57.14 +| 1164 |[Product Price at a Given Date](src/main/kotlin/g1101_1200/s1164_product_price_at_a_given_date)| Medium | Database | 774 | 91.86 | 1163 |[Last Substring in Lexicographical Order](src/main/kotlin/g1101_1200/s1163_last_substring_in_lexicographical_order)| Hard | String, Two_Pointers | 254 | 100.00 | 1162 |[As Far from Land as Possible](src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix, Graph_Theory_I_Day_4_Matrix_Related_Problems | 362 | 81.25 | 1161 |[Maximum Level Sum of a Binary Tree](src/main/kotlin/g1101_1200/s1161_maximum_level_sum_of_a_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 445 | 87.50 @@ -1787,6 +1929,9 @@ | 1105 |[Filling Bookcase Shelves](src/main/kotlin/g1101_1200/s1105_filling_bookcase_shelves)| Medium | Array, Dynamic_Programming | 175 | 33.33 | 1104 |[Path In Zigzag Labelled Binary Tree](src/main/kotlin/g1101_1200/s1104_path_in_zigzag_labelled_binary_tree)| Medium | Math, Tree, Binary_Tree | 136 | 100.00 | 1103 |[Distribute Candies to People](src/main/kotlin/g1101_1200/s1103_distribute_candies_to_people)| Easy | Math, Simulation | 129 | 100.00 +| 1096 |[Brace Expansion II](src/main/kotlin/g1001_1100/s1096_brace_expansion_ii)| Hard | String, Breadth_First_Search, Stack, Backtracking | 205 | 100.00 +| 1095 |[Find in Mountain Array](src/main/kotlin/g1001_1100/s1095_find_in_mountain_array)| Hard | Array, Binary_Search, Interactive | 173 | 100.00 +| 1094 |[Car Pooling](src/main/kotlin/g1001_1100/s1094_car_pooling)| Medium | Array, Sorting, Heap_Priority_Queue, Simulation, Prefix_Sum | 172 | 81.82 | 1093 |[Statistics from a Large Sample](src/main/kotlin/g1001_1100/s1093_statistics_from_a_large_sample)| Medium | Math, Two_Pointers, Probability_and_Statistics | 191 | 100.00 | 1092 |[Shortest Common Supersequence](src/main/kotlin/g1001_1100/s1092_shortest_common_supersequence)| Hard | String, Dynamic_Programming | 174 | 100.00 | 1091 |[Shortest Path in Binary Matrix](src/main/kotlin/g1001_1100/s1091_shortest_path_in_binary_matrix)| Medium | Array, Breadth_First_Search, Matrix, Algorithm_II_Day_8_Breadth_First_Search_Depth_First_Search, Graph_Theory_I_Day_5_Matrix_Related_Problems | 305 | 98.28 diff --git a/src/main/kotlin/g1001_1100/s1094_car_pooling/readme.md b/src/main/kotlin/g1001_1100/s1094_car_pooling/readme.md new file mode 100644 index 00000000..c9df3e08 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1094_car_pooling/readme.md @@ -0,0 +1,54 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1094\. Car Pooling + +Medium + +There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). + +You are given the integer `capacity` and an array `trips` where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. + +Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** trips = \[\[2,1,5],[3,3,7]], capacity = 4 + +**Output:** false + +**Example 2:** + +**Input:** trips = \[\[2,1,5],[3,3,7]], capacity = 5 + +**Output:** true + +**Constraints:** + +* `1 <= trips.length <= 1000` +* `trips[i].length == 3` +* 1 <= numPassengersi <= 100 +* 0 <= fromi < toi <= 1000 +* 1 <= capacity <= 105 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun carPooling(trips: Array, capacity: Int): Boolean { + var capacity = capacity + val stops = IntArray(1001) + for (t in trips) { + stops[t[1]] += t[0] + stops[t[2]] -= t[0] + } + var i = 0 + while (capacity >= 0 && i < 1001) { + capacity -= stops[i] + ++i + } + return capacity >= 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1095_find_in_mountain_array/readme.md b/src/main/kotlin/g1001_1100/s1095_find_in_mountain_array/readme.md new file mode 100644 index 00000000..d428772e --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1095_find_in_mountain_array/readme.md @@ -0,0 +1,115 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1095\. Find in Mountain Array + +Hard + +_(This problem is an **interactive problem**.)_ + +You may recall that an array `arr` is a **mountain array** if and only if: + +* `arr.length >= 3` +* There exists some `i` with `0 < i < arr.length - 1` such that: + * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` + * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + +Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. + +**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: + +* `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). +* `MountainArray.length()` returns the length of the array. + +Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. + +**Example 1:** + +**Input:** array = [1,2,3,4,5,3,1], target = 3 + +**Output:** 2 + +**Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. + +**Example 2:** + +**Input:** array = [0,1,2,4,2,1], target = 3 + +**Output:** -1 + +**Explanation:** 3 does not exist in `the array,` so we return -1. + +**Constraints:** + +* 3 <= mountain_arr.length() <= 104 +* 0 <= target <= 109 +* 0 <= mountain_arr.get(index) <= 109 + +## Solution + +```kotlin +/* + * // This is MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * class MountainArray { + * fun get(index: Int): Int {} + * fun length(): Int {} + * } + */ + +class Solution { + fun findInMountainArray(target: Int, mountainArr: MountainArray): Int { + val peakIndex = findPeak(mountainArr) + if (target == mountainArr.get(peakIndex)) { + return peakIndex + } + val leftResult = findInPeakLeft(target, peakIndex, mountainArr) + return if (leftResult != -1) { + leftResult + } else findInPeakRight(target, peakIndex, mountainArr) + } + + private fun findPeak(mountainArray: MountainArray): Int { + val len: Int = mountainArray.length() + var left = 0 + var right = len - 1 + while (left < right) { + val mid = left + (right - left) / 2 + if (mountainArray.get(mid) < mountainArray.get(mid + 1)) { + left = mid + 1 + } else { + right = mid + } + } + return left + } + + private fun findInPeakLeft(target: Int, peakIndex: Int, mountainArray: MountainArray): Int { + var leftIndex = 0 + var rightIndex = peakIndex - 1 + while (leftIndex < rightIndex) { + val midIndex = leftIndex + (rightIndex - leftIndex) / 2 + if (target > mountainArray.get(midIndex)) { + leftIndex = midIndex + 1 + } else { + rightIndex = midIndex + } + } + return if (target == mountainArray.get(leftIndex)) leftIndex else -1 + } + + private fun findInPeakRight(target: Int, peakIndex: Int, mountainArray: MountainArray): Int { + var leftIndex = peakIndex + 1 + var rightIndex: Int = mountainArray.length() - 1 + while (leftIndex < rightIndex) { + val midIndex = leftIndex + (rightIndex - leftIndex) / 2 + if (target < mountainArray.get(midIndex)) { + leftIndex = midIndex + 1 + } else { + rightIndex = midIndex + } + } + return if (target == mountainArray.get(leftIndex)) leftIndex else -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1096_brace_expansion_ii/readme.md b/src/main/kotlin/g1001_1100/s1096_brace_expansion_ii/readme.md new file mode 100644 index 00000000..933c5653 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1096_brace_expansion_ii/readme.md @@ -0,0 +1,123 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1096\. Brace Expansion II + +Hard + +Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents. + +The grammar can best be understood through simple examples: + +* Single letters represent a singleton set containing that word. + * `R("a") = {"a"}` + * `R("w") = {"w"}` +* When we take a comma-delimited list of two or more expressions, we take the union of possibilities. + * `R("{a,b,c}") = {"a","b","c"}` + * `R("{ {a,b},{b,c}}") = {"a","b","c"}` (notice the final set only contains each word at most once) +* When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. + * `R("{a,b}{c,d}") = {"ac","ad","bc","bd"}` + * `R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}` + +Formally, the three rules for our grammar: + +* For every lowercase letter `x`, we have `R(x) = {x}`. +* For expressions e1, e2, ... , ek with `k >= 2`, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... +* For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where `+` denotes concatenation, and `×` denotes the cartesian product. + +Given an expression representing a set of words under the given grammar, return _the sorted list of words that the expression represents_. + +**Example 1:** + +**Input:** expression = "{a,b}{c,{d,e}}" + +**Output:** ["ac","ad","ae","bc","bd","be"] + +**Example 2:** + +**Input:** expression = "{ {a,z},a{b,c},{ab,z}}" + +**Output:** ["a","ab","ac","z"] + +**Explanation:** Each distinct word is written only once in the final answer. + +**Constraints:** + +* `1 <= expression.length <= 60` +* `expression[i]` consists of `'{'`, `'}'`, `','`or lowercase English letters. +* The given `expression` represents a set of words based on the grammar given in the description. + +## Solution + +```kotlin +class Solution { + fun braceExpansionII(expression: String): List { + val res = flatten(expression) + val sorted: MutableList = ArrayList(res) + sorted.sort() + return sorted + } + + private fun flatten(expression: String): Set { + val res: MutableSet = HashSet() + // A temp set to store cartesian product results. + var curSet: MutableSet = HashSet() + var idx = 0 + while (idx < expression.length) { + if (expression[idx] == '{') { + // end will be the index of matching "}" + val end = findClosingBrace(expression, idx) + val set = flatten(expression.substring(idx + 1, end)) + curSet = concatenateSet(curSet, set) + idx = end + 1 + } else if (Character.isLowerCase(expression[idx])) { + // Create set with single element + val set: Set = HashSet( + listOf( + expression[idx].toString() + ) + ) + curSet = concatenateSet(curSet, set) + idx++ + } else if (expression[idx] == ',') { + res.addAll(curSet) + curSet.clear() + idx++ + } + } + // Don't forget! + res.addAll(curSet) + return res + } + + private fun concatenateSet(set1: Set, set2: Set): MutableSet { + if (set1.isEmpty() || set2.isEmpty()) { + return if (set2.isNotEmpty()) HashSet(set2) else HashSet(set1) + } + val res: MutableSet = HashSet() + for (s1 in set1) { + for (s2 in set2) { + res.add(s1 + s2) + } + } + return res + } + + private fun findClosingBrace(expression: String, start: Int): Int { + var count = 0 + var idx = start + while (idx < expression.length) { + if (expression[idx] == '{') { + count++ + } else if (expression[idx] == '}') { + count-- + } + if (count == 0) { + break + } + idx++ + } + return idx + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1106_parsing_a_boolean_expression/readme.md b/src/main/kotlin/g1101_1200/s1106_parsing_a_boolean_expression/readme.md index ec67e20d..52d7eefb 100644 --- a/src/main/kotlin/g1101_1200/s1106_parsing_a_boolean_expression/readme.md +++ b/src/main/kotlin/g1101_1200/s1106_parsing_a_boolean_expression/readme.md @@ -66,7 +66,7 @@ class Solution { return res } - private operator fun not(): Boolean { + private fun not(): Boolean { consume('!') return !group()[0] } @@ -109,7 +109,7 @@ class Solution { } private val isAtEnd: Boolean - private get() = index >= source!!.length + get() = index >= source!!.length private fun advance() { if (isAtEnd) { diff --git a/src/main/kotlin/g1101_1200/s1164_product_price_at_a_given_date/readme.md b/src/main/kotlin/g1101_1200/s1164_product_price_at_a_given_date/readme.md new file mode 100644 index 00000000..25ac58a4 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1164_product_price_at_a_given_date/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1164\. Product Price at a Given Date + +Medium + +SQL Schema + +Table: `Products` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | product_id | int | + | new_price | int | + | change_date | date | + +---------------+---------+ + +(product_id, change_date) is the primary key of this table. + +Each row of this table indicates that the price of some product was changed to a new price at some date. + +Write an SQL query to find the prices of all products on `2019-08-16`. Assume the price of all products before any change is `10`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** Products table: + + +------------+-----------+-------------+ + | product_id | new_price | change_date | + +------------+-----------+-------------+ + | 1 | 20 | 2019-08-14 | + | 2 | 50 | 2019-08-14 | + | 1 | 30 | 2019-08-15 | + | 1 | 35 | 2019-08-16 | + | 2 | 65 | 2019-08-17 | + | 3 | 20 | 2019-08-18 | + +------------+-----------+-------------+ + +**Output:** + + +------------+-------+ + | product_id | price | + +------------+-------+ + | 2 | 50 | + | 1 | 35 | + | 3 | 10 | + +------------+-------+ + +## Solution + +```sql +# Write your MySQL query statement below +WITH before_change_date AS ( + SELECT DISTINCT + product_id, + new_price as price, + RANK() Over(Partition By product_id Order by change_date DESC) as rnk + FROM Products + WHERE change_date <= '2019-08-16' +) + +SELECT + product_id, + price +FROM before_change_date +WHERE rnk = 1 + +UNION + +SELECT + DISTINCT product_id, + 10 as price +FROM Products +WHERE product_id not in ( + SELECT product_id + FROM Products + WHERE change_date <= '2019-08-16' +) +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1301_number_of_paths_with_max_score/readme.md b/src/main/kotlin/g1301_1400/s1301_number_of_paths_with_max_score/readme.md new file mode 100644 index 00000000..aff7ca7c --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1301_number_of_paths_with_max_score/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1301\. Number of Paths with Max Score + +Hard + +You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`. + +You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'`. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. + +Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, **taken modulo `10^9 + 7`**. + +In case there is no path, return `[0, 0]`. + +**Example 1:** + +**Input:** board = ["E23","2X2","12S"] + +**Output:** [7,1] + +**Example 2:** + +**Input:** board = ["E12","1X1","21S"] + +**Output:** [4,2] + +**Example 3:** + +**Input:** board = ["E11","XXX","11S"] + +**Output:** [0,0] + +**Constraints:** + +* `2 <= board.length == board[i].length <= 100` + +## Solution + +```kotlin +class Solution { + fun pathsWithMaxScore(board: List): IntArray { + val rows = board.size + val columns = board[0].length + val dp = Array(rows) { Array(columns) { IntArray(2) } } + for (r in rows - 1 downTo 0) { + for (c in columns - 1 downTo 0) { + val current = board[r][c] + if (current == 'S') { + dp[r][c][0] = 0 + dp[r][c][1] = 1 + } else if (current != 'X') { + var maxScore = 0 + var paths = 0 + val currentScore = if (current == 'E') 0 else current.code - '0'.code + for (dir in DIRECTIONS) { + val nextR = r + dir[0] + val nextC = c + dir[1] + if (nextR < rows && nextC < columns && dp[nextR][nextC][1] > 0) { + if (dp[nextR][nextC][0] + currentScore > maxScore) { + maxScore = dp[nextR][nextC][0] + currentScore + paths = dp[nextR][nextC][1] + } else if (dp[nextR][nextC][0] + currentScore == maxScore) { + paths = (paths + dp[nextR][nextC][1]) % 1000000007 + } + } + } + dp[r][c][0] = maxScore + dp[r][c][1] = paths + } + } + } + return intArrayOf(dp[0][0][0], dp[0][0][1]) + } + + companion object { + private val DIRECTIONS = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(1, 1)) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1302_deepest_leaves_sum/readme.md b/src/main/kotlin/g1301_1400/s1302_deepest_leaves_sum/readme.md new file mode 100644 index 00000000..85ba8236 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1302_deepest_leaves_sum/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1302\. Deepest Leaves Sum + +Medium + +Given the `root` of a binary tree, return _the sum of values of its deepest leaves_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png) + +**Input:** root = [1,2,3,4,5,null,6,7,null,null,null,null,8] + +**Output:** 15 + +**Example 2:** + +**Input:** root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] + +**Output:** 19 + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* `1 <= Node.val <= 100` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList +import java.util.Objects +import java.util.Queue + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun deepestLeavesSum(root: TreeNode?): Int { + val queue: Queue = LinkedList() + queue.offer(root) + var sum = 0 + while (queue.isNotEmpty()) { + val size = queue.size + sum = 0 + for (i in 0 until size) { + val curr = queue.poll() + sum += Objects.requireNonNull(curr)!!.`val` + if (curr!!.left != null) { + queue.offer(curr.left) + } + if (curr.right != null) { + queue.offer(curr.right) + } + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1304_find_n_unique_integers_sum_up_to_zero/readme.md b/src/main/kotlin/g1301_1400/s1304_find_n_unique_integers_sum_up_to_zero/readme.md new file mode 100644 index 00000000..75353ee5 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1304_find_n_unique_integers_sum_up_to_zero/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1304\. Find N Unique Integers Sum up to Zero + +Easy + +Given an integer `n`, return **any** array containing `n` **unique** integers such that they add up to `0`. + +**Example 1:** + +**Input:** n = 5 + +**Output:** [-7,-1,1,3,4] + +**Explanation:** These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. + +**Example 2:** + +**Input:** n = 3 + +**Output:** [-1,0,1] + +**Example 3:** + +**Input:** n = 1 + +**Output:** [0] + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + fun sumZero(n: Int): IntArray { + val result = IntArray(n) + var start = -n / 2 + for (i in 0 until n / 2) { + result[i] = start++ + } + if (n % 2 == 0) { + start++ + } + for (i in n / 2 until n) { + result[i] = start++ + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1305_all_elements_in_two_binary_search_trees/readme.md b/src/main/kotlin/g1301_1400/s1305_all_elements_in_two_binary_search_trees/readme.md new file mode 100644 index 00000000..c5a801d6 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1305_all_elements_in_two_binary_search_trees/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1305\. All Elements in Two Binary Search Trees + +Medium + +Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png) + +**Input:** root1 = [2,1,4], root2 = [1,0,3] + +**Output:** [0,1,1,2,3,4] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png) + +**Input:** root1 = [1,null,8], root2 = [8,1] + +**Output:** [1,1,8,8] + +**Constraints:** + +* The number of nodes in each tree is in the range `[0, 5000]`. +* -105 <= Node.val <= 105 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun getAllElements(root1: TreeNode?, root2: TreeNode?): List { + val list1 = getAllNodes(root1) + val list2 = getAllNodes(root2) + val merged: MutableList = ArrayList() + merged.addAll(list1) + merged.addAll(list2) + merged.sort() + return merged + } + + private fun getAllNodes(root: TreeNode?): List { + val list: MutableList = ArrayList() + return inorder(root, list) + } + + private fun inorder(root: TreeNode?, result: MutableList): List { + if (root == null) { + return result + } + inorder(root.left, result) + result.add(root.`val`) + return inorder(root.right, result) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1306_jump_game_iii/readme.md b/src/main/kotlin/g1301_1400/s1306_jump_game_iii/readme.md new file mode 100644 index 00000000..7bff233c --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1306_jump_game_iii/readme.md @@ -0,0 +1,91 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1306\. Jump Game III + +Medium + +Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0. + +Notice that you can not jump outside of the array at any time. + +**Example 1:** + +**Input:** arr = [4,2,3,0,3,1,2], start = 5 + +**Output:** true + +**Explanation:** + +All possible ways to reach at index 3 with value 0 are: + +index 5 -> index 4 -> index 1 -> index 3 + +index 5 -> index 6 -> index 4 -> index 1 -> index 3 + +**Example 2:** + +**Input:** arr = [4,2,3,0,3,1,2], start = 0 + +**Output:** true + +**Explanation:** + +One possible way to reach at index 3 with value 0 is: + +index 0 -> index 4 -> index 1 -> index 3 + +**Example 3:** + +**Input:** arr = [3,0,2,1,2], start = 2 + +**Output:** false + +**Explanation:** There is no way to reach at index 1 with value 0. + +**Constraints:** + +* 1 <= arr.length <= 5 * 104 +* `0 <= arr[i] < arr.length` +* `0 <= start < arr.length` + +## Solution + +```kotlin +class Solution { + private lateinit var dp: BooleanArray + private var found = false + + fun canReach(arr: IntArray, start: Int): Boolean { + if (arr[start] == 0) { + return true + } + dp = BooleanArray(arr.size) + dp[start] = true + recurse(arr, start) + return found + } + + private fun recurse(arr: IntArray, index: Int) { + if (found) { + return + } + if (index - arr[index] >= 0 && !dp[index - arr[index]]) { + if (arr[index - arr[index]] == 0) { + found = true + return + } + dp[index - arr[index]] = true + recurse(arr, index - arr[index]) + } + if (index + arr[index] < arr.size && !dp[index + arr[index]]) { + if (arr[index + arr[index]] == 0) { + found = true + return + } + dp[index + arr[index]] = true + recurse(arr, index + arr[index]) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1307_verbal_arithmetic_puzzle/readme.md b/src/main/kotlin/g1301_1400/s1307_verbal_arithmetic_puzzle/readme.md new file mode 100644 index 00000000..734dcd5f --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1307_verbal_arithmetic_puzzle/readme.md @@ -0,0 +1,168 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1307\. Verbal Arithmetic Puzzle + +Hard + +Given an equation, represented by `words` on the left side and the `result` on the right side. + +You need to check if the equation is solvable under the following rules: + +* Each character is decoded as one digit (0 - 9). +* Every pair of different characters must map to different digits. +* Each `words[i]` and `result` are decoded as one number **without** leading zeros. +* Sum of numbers on the left side (`words`) will equal to the number on the right side (`result`). + +Return `true` _if the equation is solvable, otherwise return_ `false`. + +**Example 1:** + +**Input:** words = ["SEND","MORE"], result = "MONEY" + +**Output:** true + +**Explanation:** Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2' Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652 + +**Example 2:** + +**Input:** words = ["SIX","SEVEN","SEVEN"], result = "TWENTY" + +**Output:** true + +**Explanation:** Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214 + +**Example 3:** + +**Input:** words = ["LEET","CODE"], result = "POINT" + +**Output:** false + +**Constraints:** + +* `2 <= words.length <= 5` +* `1 <= words[i].length, result.length <= 7` +* `words[i], result` contain only uppercase English letters. +* The number of different characters used in the expression is at most `10`. + +## Solution + +```kotlin +class Solution { + private lateinit var map: IntArray + private lateinit var grid: Array + private var solved = false + private lateinit var usedDigit: BooleanArray + private lateinit var mustNotBeZero: BooleanArray + private var cols = 0 + private var resultRow = 0 + + fun isSolvable(words: Array, result: String): Boolean { + solved = false + val rows = words.size + 1 + cols = result.length + grid = Array(rows) { CharArray(cols) } + mustNotBeZero = BooleanArray(26) + usedDigit = BooleanArray(10) + resultRow = rows - 1 + map = IntArray(26) + map.fill(-1) + var maxLength = 0 + for (i in words.indices) { + var j = words[i].length + if (j > maxLength) { + maxLength = j + } + if (j > 1) { + mustNotBeZero[words[i][0].code - 'A'.code] = true + } + if (j > cols) { + return false + } + for (c in words[i].toCharArray()) { + grid[i][--j] = c + } + } + if (maxLength + 1 < cols) { + return false + } + var j = cols + if (j > 1) { + mustNotBeZero[result[0].code - 'A'.code] = true + } + for (c in result.toCharArray()) { + grid[resultRow][--j] = c + } + backtrack(0, 0, 0) + return solved + } + + private fun canPlace(ci: Int, d: Int): Boolean { + return !usedDigit[d] && map[ci] == -1 || map[ci] == d + } + + private fun placeNum(ci: Int, d: Int) { + usedDigit[d] = true + map[ci] = d + } + + private fun removeNum(ci: Int, d: Int) { + usedDigit[d] = false + map[ci] = -1 + } + + private fun placeNextNum(r: Int, c: Int, sum: Int) { + if (r == resultRow && c == cols - 1) { + solved = sum == 0 + } else { + if (r == resultRow) { + backtrack(0, c + 1, sum) + } else { + backtrack(r + 1, c, sum) + } + } + } + + private fun backtrack(r: Int, c: Int, sum: Int) { + val unused = '\u0000' + if (grid[r][c] == unused) { + placeNextNum(r, c, sum) + } else { + val ci = grid[r][c].code - 'A'.code + if (r == resultRow) { + val d = sum % 10 + if (map[ci] == -1) { + if (canPlace(ci, d)) { + placeNum(ci, d) + placeNextNum(r, c, sum / 10) + if (solved) { + return + } + removeNum(ci, d) + } + } else { + if (map[ci] == d) { + placeNextNum(r, c, sum / 10) + } + } + } else { + if (map[ci] == -1) { + val startIndex = if (mustNotBeZero[ci]) 1 else 0 + for (d in startIndex..9) { + if (canPlace(ci, d)) { + placeNum(ci, d) + placeNextNum(r, c, sum + d) + if (solved) { + return + } + removeNum(ci, d) + } + } + } else { + placeNextNum(r, c, sum + map[ci]) + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping/readme.md b/src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping/readme.md new file mode 100644 index 00000000..43ae7792 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1309\. Decrypt String from Alphabet to Integer Mapping + +Easy + +You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows: + +* Characters (`'a'` to `'i')` are represented by (`'1'` to `'9'`) respectively. +* Characters (`'j'` to `'z')` are represented by (`'10#'` to `'26#'`) respectively. + +Return _the string formed after mapping_. + +The test cases are generated so that a unique mapping will always exist. + +**Example 1:** + +**Input:** s = "10#11#12" + +**Output:** "jkab" + +**Explanation:** "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". + +**Example 2:** + +**Input:** s = "1326#" + +**Output:** "acz" + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s` consists of digits and the `'#'` letter. +* `s` will be a valid string such that mapping is always possible. + +## Solution + +```kotlin +class Solution { + fun freqAlphabets(s: String): String { + val map: MutableMap = HashMap() + map["1"] = "a" + map["2"] = "b" + map["3"] = "c" + map["4"] = "d" + map["5"] = "e" + map["6"] = "f" + map["7"] = "g" + map["8"] = "h" + map["9"] = "i" + map["10#"] = "j" + map["11#"] = "k" + map["12#"] = "l" + map["13#"] = "m" + map["14#"] = "n" + map["15#"] = "o" + map["16#"] = "p" + map["17#"] = "q" + map["18#"] = "r" + map["19#"] = "s" + map["20#"] = "t" + map["21#"] = "u" + map["22#"] = "v" + map["23#"] = "w" + map["24#"] = "x" + map["25#"] = "y" + map["26#"] = "z" + val sb = StringBuilder() + var i = 0 + while (i < s.length) { + if ((("" + s[i]).toInt() == 1 || ("" + s[i]).toInt() == 2) && + i + 1 < s.length && i + 2 < s.length && + s[i + 2] == '#' + ) { + sb.append(map[s.substring(i, i + 3)]) + i += 3 + } else { + sb.append(map["" + s[i]]) + i++ + } + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1310_xor_queries_of_a_subarray/readme.md b/src/main/kotlin/g1301_1400/s1310_xor_queries_of_a_subarray/readme.md new file mode 100644 index 00000000..30a118d4 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1310_xor_queries_of_a_subarray/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1310\. XOR Queries of a Subarray + +Medium + +You are given an array `arr` of positive integers. You are also given the array `queries` where queries[i] = [lefti, righti]. + +For each query `i` compute the **XOR** of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ). + +Return an array `answer` where `answer[i]` is the answer to the ith query. + +**Example 1:** + +**Input:** arr = [1,3,4,8], queries = \[\[0,1],[1,2],[0,3],[3,3]] + +**Output:** [2,7,14,8] + +**Explanation:** + +The binary representation of the elements in the array are: + +1 = 0001 + +3 = 0011 + +4 = 0100 + +8 = 1000 + +The XOR values for queries are: + +[0,1] = 1 xor 3 = 2 + +[1,2] = 3 xor 4 = 7 + +[0,3] = 1 xor 3 xor 4 xor 8 = 14 + +[3,3] = 8 + +**Example 2:** + +**Input:** arr = [4,8,2,10], queries = \[\[2,3],[1,3],[0,0],[0,3]] + +**Output:** [8,0,4,4] + +**Constraints:** + +* 1 <= arr.length, queries.length <= 3 * 104 +* 1 <= arr[i] <= 109 +* `queries[i].length == 2` +* 0 <= lefti <= righti < arr.length + +## Solution + +```kotlin +class Solution { + fun xorQueries(arr: IntArray, queries: Array): IntArray { + val res = IntArray(queries.size) + for (i in 1 until arr.size) { + arr[i] = arr[i - 1] xor arr[i] + } + for (i in queries.indices) { + val query = queries[i] + res[i] = if (query[0] == 0) arr[query[1]] else arr[query[0] - 1] xor arr[query[1]] + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1311_get_watched_videos_by_your_friends/readme.md b/src/main/kotlin/g1301_1400/s1311_get_watched_videos_by_your_friends/readme.md new file mode 100644 index 00000000..055d44be --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1311_get_watched_videos_by_your_friends/readme.md @@ -0,0 +1,121 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1311\. Get Watched Videos by Your Friends + +Medium + +There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. + +Level **1** of videos are all watched videos by your friends, level **2** of videos are all watched videos by the friends of your friends and so on. In general, the level `k` of videos are all watched videos by people with the shortest path **exactly** equal to `k` with you. Given your `id` and the `level` of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_1.png)** + +**Input:** watchedVideos = \[\["A","B"],["C"],["B","C"],["D"]], friends = \[\[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 + +**Output:** ["B","C"] + +**Explanation:** + +You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): + +Person with id = 1 -> watchedVideos = ["C"] + +Person with id = 2 -> watchedVideos = ["B","C"] + +The frequencies of watchedVideos by your friends are: + +B -> 1 + +C -> 2 + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_2.png)** + +**Input:** watchedVideos = \[\["A","B"],["C"],["B","C"],["D"]], friends = \[\[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 + +**Output:** ["D"] + +**Explanation:** You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure). + +**Constraints:** + +* `n == watchedVideos.length == friends.length` +* `2 <= n <= 100` +* `1 <= watchedVideos[i].length <= 100` +* `1 <= watchedVideos[i][j].length <= 8` +* `0 <= friends[i].length < n` +* `0 <= friends[i][j] < n` +* `0 <= id < n` +* `1 <= level < n` +* if `friends[i]` contains `j`, then `friends[j]` contains `i` + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.PriorityQueue +import java.util.Queue + +class Solution { + internal class VideoCount(var v: String, var count: Int) { + override fun toString(): String { + return "$v $count" + } + } + + fun watchedVideosByFriends( + watchedVideos: List>, + friends: Array, + id: Int, + level: Int + ): List { + val visited = BooleanArray(watchedVideos.size) + val queue: Queue = LinkedList() + queue.add(id) + visited[id] = true + var currLevel = 0 + while (queue.isNotEmpty()) { + var size = queue.size + while (size-- > 0) { + val node = queue.poll() + val nei = friends[node] + for (i in nei) { + if (!visited[i]) { + queue.add(i) + visited[i] = true + } + } + } + currLevel++ + if (currLevel == level) { + break + } + } + val map: MutableMap = HashMap() + while (queue.isNotEmpty()) { + val f = queue.poll() + val watchedVideo = watchedVideos[f] + for (video in watchedVideo) { + map.putIfAbsent(video, VideoCount(video, 0)) + map[video]!!.count++ + } + } + val pq = PriorityQueue { v1: VideoCount, v2: VideoCount + -> + if (v1.count == v2.count) v1.v.compareTo(v2.v) else v1.count - v2.count + } + for ((_, value) in map) { + pq.add(value) + } + val res: MutableList = ArrayList() + while (pq.isNotEmpty()) { + res.add(pq.poll().v) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1312_minimum_insertion_steps_to_make_a_string_palindrome/readme.md b/src/main/kotlin/g1301_1400/s1312_minimum_insertion_steps_to_make_a_string_palindrome/readme.md new file mode 100644 index 00000000..e4dafdef --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1312_minimum_insertion_steps_to_make_a_string_palindrome/readme.md @@ -0,0 +1,73 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1312\. Minimum Insertion Steps to Make a String Palindrome + +Hard + +Given a string `s`. In one step you can insert any character at any index of the string. + +Return _the minimum number of steps_ to make `s` palindrome. + +A **Palindrome String** is one that reads the same backward as well as forward. + +**Example 1:** + +**Input:** s = "zzazz" + +**Output:** 0 + +**Explanation:** The string "zzazz" is already palindrome we don't need any insertions. + +**Example 2:** + +**Input:** s = "mbadm" + +**Output:** 2 + +**Explanation:** String can be "mbdadbm" or "mdbabdm". + +**Example 3:** + +**Input:** s = "leetcode" + +**Output:** 5 + +**Explanation:** Inserting 5 characters the string becomes "leetcodocteel". + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + private fun longestPalindrome(a: String, b: String, n: Int): Int { + val dp = Array(n + 1) { IntArray(n + 1) } + for (i in 0 until n + 1) { + for (j in 0 until n + 1) { + if (i == 0 || j == 0) { + dp[i][j] = 0 + } else if (a[i - 1] == b[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1] + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + } + } + } + return dp[n][n] + } + + fun minInsertions(s: String): Int { + val n = s.length + if (n < 2) { + return 0 + } + val rs = StringBuilder(s).reverse().toString() + val l = longestPalindrome(s, rs, n) + return n - l + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1313_decompress_run_length_encoded_list/readme.md b/src/main/kotlin/g1301_1400/s1313_decompress_run_length_encoded_list/readme.md new file mode 100644 index 00000000..81a9e632 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1313_decompress_run_length_encoded_list/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1313\. Decompress Run-Length Encoded List + +Easy + +We are given a list `nums` of integers representing a list compressed with run-length encoding. + +Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. + +Return the decompressed list. + +**Example 1:** + +**Input:** nums = [1,2,3,4] + +**Output:** [2,4,4,4] + +**Explanation:** The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. + +The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. + +At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. + +**Example 2:** + +**Input:** nums = [1,1,2,3] + +**Output:** [1,3,3] + +**Constraints:** + +* `2 <= nums.length <= 100` +* `nums.length % 2 == 0` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun decompressRLElist(nums: IntArray): IntArray { + var len = 0 + run { + var i = 0 + while (i < nums.size) { + len += nums[i] + i += 2 + } + } + val ans = IntArray(len) + var index = 0 + var i = 0 + while (i < nums.size) { + var j = nums[i] + while (j > 0) { + ans[index] = nums[i + 1] + index++ + j-- + } + i += 2 + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1314_matrix_block_sum/readme.md b/src/main/kotlin/g1301_1400/s1314_matrix_block_sum/readme.md new file mode 100644 index 00000000..1ea2b752 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1314_matrix_block_sum/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1314\. Matrix Block Sum + +Medium + +Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_: + +* `i - k <= r <= i + k,` +* `j - k <= c <= j + k`, and +* `(r, c)` is a valid position in the matrix. + +**Example 1:** + +**Input:** mat = \[\[1,2,3],[4,5,6],[7,8,9]], k = 1 + +**Output:** [[12,21,16],[27,45,33],[24,39,28]] + +**Example 2:** + +**Input:** mat = \[\[1,2,3],[4,5,6],[7,8,9]], k = 2 + +**Output:** [[45,45,45],[45,45,45],[45,45,45]] + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n, k <= 100` +* `1 <= mat[i][j] <= 100` + +## Solution + +```kotlin +class Solution { + fun matrixBlockSum(mat: Array, k: Int): Array { + val rows = mat.size + val cols = mat[0].size + val prefixSum = Array(rows + 1) { IntArray(cols + 1) } + for (i in 1..rows) { + for (j in 1..cols) { + prefixSum[i][j] = ( + ( + mat[i - 1][j - 1] - + prefixSum[i - 1][j - 1] + ) + prefixSum[i - 1][j] + + prefixSum[i][j - 1] + ) + } + } + val result = Array(rows) { IntArray(cols) } + for (i in 0 until rows) { + for (j in 0 until cols) { + val iMin = Math.max(i - k, 0) + val iMax = Math.min(i + k, rows - 1) + val jMin = Math.max(j - k, 0) + val jMax = Math.min(j + k, cols - 1) + result[i][j] = ( + ( + prefixSum[iMin][jMin] + + prefixSum[iMax + 1][jMax + 1] + ) - prefixSum[iMax + 1][jMin] - + prefixSum[iMin][jMax + 1] + ) + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1315_sum_of_nodes_with_even_valued_grandparent/readme.md b/src/main/kotlin/g1301_1400/s1315_sum_of_nodes_with_even_valued_grandparent/readme.md new file mode 100644 index 00000000..f2d40484 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1315_sum_of_nodes_with_even_valued_grandparent/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1315\. Sum of Nodes with Even-Valued Grandparent + +Medium + +Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`. + +A **grandparent** of a node is the parent of its parent if it exists. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg) + +**Input:** root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] + +**Output:** 18 + +**Explanation:** The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg) + +**Input:** root = [1] + +**Output:** 0 + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* `1 <= Node.val <= 100` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +@Suppress("NAME_SHADOWING") +class Solution { + fun sumEvenGrandparent(root: TreeNode?): Int { + return if (root == null) { + 0 + } else dfs(root, root.left, 0) + dfs(root, root.right, 0) + } + + private fun dfs(grandparent: TreeNode?, parent: TreeNode?, sum: Int): Int { + var sum = sum + if (grandparent == null || parent == null) { + return sum + } + if (grandparent.`val` % 2 == 0 && parent.left != null) { + sum += parent.left!!.`val` + } + if (grandparent.`val` % 2 == 0 && parent.right != null) { + sum += parent.right!!.`val` + } + sum = dfs(parent, parent.left, sum) + sum = dfs(parent, parent.right, sum) + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1316_distinct_echo_substrings/readme.md b/src/main/kotlin/g1301_1400/s1316_distinct_echo_substrings/readme.md new file mode 100644 index 00000000..107d8c59 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1316_distinct_echo_substrings/readme.md @@ -0,0 +1,65 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1316\. Distinct Echo Substrings + +Hard + +Return the number of **distinct** non-empty substrings of `text` that can be written as the concatenation of some string with itself (i.e. it can be written as `a + a` where `a` is some string). + +**Example 1:** + +**Input:** text = "abcabcabc" + +**Output:** 3 + +**Explanation:** The 3 substrings are "abcabc", "bcabca" and "cabcab". + +**Example 2:** + +**Input:** text = "leetcodeleetcode" + +**Output:** 2 + +**Explanation:** The 2 substrings are "ee" and "leetcodeleetcode". + +**Constraints:** + +* `1 <= text.length <= 2000` +* `text` has only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun distinctEchoSubstrings(text: String): Int { + val n = text.length + val dp = Array(n) { IntArray(n) } + for (i in 0 until n) { + var hash: Long = 0 + for (j in i until n) { + hash = hash * PRIME + (text[j].code - 'a'.code + 1) + hash %= MOD.toLong() + dp[i][j] = hash.toInt() + } + } + val set: MutableSet = HashSet() + var res = 0 + for (i in 0 until n - 1) { + var j = i + while (2 * j - i + 1 < n) { + if (dp[i][j] == dp[j + 1][2 * j - i + 1] && set.add(dp[i][j])) { + res++ + } + j++ + } + } + return res + } + + companion object { + private const val PRIME = 101 + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1317_convert_integer_to_the_sum_of_two_no_zero_integers/readme.md b/src/main/kotlin/g1301_1400/s1317_convert_integer_to_the_sum_of_two_no_zero_integers/readme.md new file mode 100644 index 00000000..889b0627 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1317_convert_integer_to_the_sum_of_two_no_zero_integers/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1317\. Convert Integer to the Sum of Two No-Zero Integers + +Easy + +**No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation. + +Given an integer `n`, return _a list of two integers_ `[A, B]` _where_: + +* `A` and `B` are **No-Zero integers**. +* `A + B = n` + +The test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them. + +**Example 1:** + +**Input:** n = 2 + +**Output:** [1,1] + +**Explanation:** A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation. + +**Example 2:** + +**Input:** n = 11 + +**Output:** [2,9] + +**Constraints:** + +* 2 <= n <= 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun getNoZeroIntegers(n: Int): IntArray { + var left = 1 + var right = n - 1 + while (left <= right) { + if (noZero(left) && noZero(right)) { + return intArrayOf(left, right) + } else { + left++ + right-- + } + } + return intArrayOf() + } + + private fun noZero(num: Int): Boolean { + var num = num + while (num != 0) { + num /= if (num % 10 == 0) { + return false + } else { + 10 + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1318_minimum_flips_to_make_a_or_b_equal_to_c/readme.md b/src/main/kotlin/g1301_1400/s1318_minimum_flips_to_make_a_or_b_equal_to_c/readme.md new file mode 100644 index 00000000..838ac7c2 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1318_minimum_flips_to_make_a_or_b_equal_to_c/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1318\. Minimum Flips to Make a OR b Equal to c + +Medium + +Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation). +Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png) + +**Input:** a = 2, b = 6, c = 5 + +**Output:** 3 + +**Explanation:** After flips a = 1 , b = 4 , c = 5 such that (`a` OR `b` == `c`) + +**Example 2:** + +**Input:** a = 4, b = 2, c = 7 + +**Output:** 1 + +**Example 3:** + +**Input:** a = 1, b = 2, c = 3 + +**Output:** 0 + +**Constraints:** + +* `1 <= a <= 10^9` +* `1 <= b <= 10^9` +* `1 <= c <= 10^9` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun minFlips(a: Int, b: Int, c: Int): Int { + var ans = 0 + val or = a or b + ans += csb(or xor c) + val and = a and b + ans += csb(and and c.inv()) + return ans + } + + private fun csb(n: Int): Int { + var n = n + var cnt = 0 + while (n > 0) { + val rsb = n and -n + n -= rsb + cnt++ + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1319_number_of_operations_to_make_network_connected/readme.md b/src/main/kotlin/g1301_1400/s1319_number_of_operations_to_make_network_connected/readme.md new file mode 100644 index 00000000..93e79038 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1319_number_of_operations_to_make_network_connected/readme.md @@ -0,0 +1,102 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1319\. Number of Operations to Make Network Connected + +Medium + +There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. + +You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. + +Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png) + +**Input:** n = 4, connections = \[\[0,1],[0,2],[1,2]] + +**Output:** 1 + +**Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png) + +**Input:** n = 6, connections = \[\[0,1],[0,2],[0,3],[1,2],[1,3]] + +**Output:** 2 + +**Example 3:** + +**Input:** n = 6, connections = \[\[0,1],[0,2],[0,3],[1,2]] + +**Output:** -1 + +**Explanation:** There are not enough cables. + +**Constraints:** + +* 1 <= n <= 105 +* 1 <= connections.length <= min(n * (n - 1) / 2, 105) +* `connections[i].length == 2` +* 0 <= ai, bi < n +* ai != bi +* There are no repeated connections. +* No two computers are connected by more than one cable. + +## Solution + +```kotlin +class Solution { + private var disconnectedComputers = 0 + private lateinit var parent: IntArray + private lateinit var rank: IntArray + + fun makeConnected(totalNumberOfComputers: Int, connections: Array): Int { + if (connections.size < totalNumberOfComputers - 1) { + return IMPOSSIBLE_TO_CONNECT + } + disconnectedComputers = totalNumberOfComputers + rank = IntArray(totalNumberOfComputers) + parent = IntArray(totalNumberOfComputers) { it } + for (connection in connections) { + unionFind(connection[0], connection[1]) + } + return disconnectedComputers - 1 + } + + private fun unionFind(first: Int, second: Int) { + val parentFirst = findParent(first) + val parentSecond = findParent(second) + if (parentFirst != parentSecond) { + joinByRank(parentFirst, parentSecond) + disconnectedComputers-- + } + } + + private fun findParent(index: Int): Int { + if (parent[index] != index) { + parent[index] = findParent(parent[index]) + } + return parent[index] + } + + private fun joinByRank(first: Int, second: Int) { + if (rank[first] < rank[second]) { + parent[first] = second + } else if (rank[second] < rank[first]) { + parent[second] = first + } else { + parent[first] = second + rank[second]++ + } + } + + companion object { + private const val IMPOSSIBLE_TO_CONNECT = -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1320_minimum_distance_to_type_a_word_using_two_fingers/readme.md b/src/main/kotlin/g1301_1400/s1320_minimum_distance_to_type_a_word_using_two_fingers/readme.md new file mode 100644 index 00000000..1f01a59c --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1320_minimum_distance_to_type_a_word_using_two_fingers/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1320\. Minimum Distance to Type a Word Using Two Fingers + +Hard + +![](https://assets.leetcode.com/uploads/2020/01/02/leetcode_keyboard.png) + +You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate. + +* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `'Z'` is located at coordinate `(4, 1)`. + +Given the string `word`, return _the minimum total **distance** to type such string using only two fingers_. + +The **distance** between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. + +**Note** that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. + +**Example 1:** + +**Input:** word = "CAKE" + +**Output:** 3 + +**Explanation:** Using two fingers, one optimal way to type "CAKE" is: + +Finger 1 on letter 'C' -> cost = 0 + +Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 + +Finger 2 on letter 'K' -> cost = 0 + +Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 + +Total distance = 3 + +**Example 2:** + +**Input:** word = "HAPPY" + +**Output:** 6 + +**Explanation:** Using two fingers, one optimal way to type "HAPPY" is: + +Finger 1 on letter 'H' -> cost = 0 + +Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2 + +Finger 2 on letter 'P' -> cost = 0 + +Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0 + +Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4 + +Total distance = 6 + +**Constraints:** + +* `2 <= word.length <= 300` +* `word` consists of uppercase English letters. + +## Solution + +```kotlin +class Solution { + private var word: String? = null + private lateinit var dp: Array>> + + fun minimumDistance(word: String): Int { + this.word = word + dp = Array(27) { Array(27) { arrayOfNulls(word.length) } } + return find(null, null, 0) + } + + private fun find(f1: Char?, f2: Char?, index: Int): Int { + if (index == word!!.length) { + return 0 + } + val result = dp[if (f1 == null) 0 else f1.code - 'A'.code + 1][ + if (f2 == null) 0 else f2.code - 'A'.code + 1 + ][index] + if (result != null) { + return result + } + val ic = word!![index] + var move = move(f1, ic) + find(ic, f2, index + 1) + move = Math.min(move, move(f2, ic) + find(f1, ic, index + 1)) + dp[if (f1 == null) 0 else f1.code - 'A'.code + 1][if (f2 == null) 0 else f2.code - 'A'.code + 1][index] = move + return move + } + + private fun move(c1: Char?, c2: Char): Int { + if (c1 == null) { + return 0 + } + val c1x = (c1.code - 'A'.code) % 6 + val c1y = (c1.code - 'A'.code) / 6 + val c2x = (c2.code - 'A'.code) % 6 + val c2y = (c2.code - 'A'.code) / 6 + return Math.abs(c1x - c2x) + Math.abs(c1y - c2y) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1323_maximum_69_number/readme.md b/src/main/kotlin/g1301_1400/s1323_maximum_69_number/readme.md new file mode 100644 index 00000000..970701d6 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1323_maximum_69_number/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1323\. Maximum 69 Number + +Easy + +You are given a positive integer `num` consisting only of digits `6` and `9`. + +Return _the maximum number you can get by changing **at most** one digit (_`6` _becomes_ `9`_, and_ `9` _becomes_ `6`_)_. + +**Example 1:** + +**Input:** num = 9669 + +**Output:** 9969 + +**Explanation:** + +Changing the first digit results in 6669. + +Changing the second digit results in 9969. + +Changing the third digit results in 9699. + +Changing the fourth digit results in 9666. + +The maximum number is 9969. + +**Example 2:** + +**Input:** num = 9996 + +**Output:** 9999 + +**Explanation:** Changing the last digit 6 to 9 results in the maximum number. + +**Example 3:** + +**Input:** num = 9999 + +**Output:** 9999 + +**Explanation:** It is better not to apply any change. + +**Constraints:** + +* 1 <= num <= 104 +* `num` consists of only `6` and `9` digits. + +## Solution + +```kotlin +class Solution { + fun maximum69Number(num: Int): Int { + val chars = num.toString().toCharArray() + var foundSix = false + for (i in chars.indices) { + if (chars[i] == '6') { + chars[i] = '9' + foundSix = true + break + } + } + return if (foundSix) chars.joinToString("").toInt() else num + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1324_print_words_vertically/readme.md b/src/main/kotlin/g1301_1400/s1324_print_words_vertically/readme.md new file mode 100644 index 00000000..8274bcae --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1324_print_words_vertically/readme.md @@ -0,0 +1,94 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1324\. Print Words Vertically + +Medium + +Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. +Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). +Each word would be put on only one column and that in one column there will be only one word. + +**Example 1:** + +**Input:** s = "HOW ARE YOU" + +**Output:** ["HAY","ORO","WEU"] + +**Explanation:** Each word is printed vertically. + +"HAY" + +"ORO" + +"WEU" + +**Example 2:** + +**Input:** s = "TO BE OR NOT TO BE" + +**Output:** ["TBONTB","OEROOE"," T"] + +**Explanation:** Trailing spaces is not allowed. + +"TBONTB" + +"OEROOE" + +" T" + +**Example 3:** + +**Input:** s = "CONTEST IS COMING" + +**Output:** ["CIC","OSO","N M","T I","E N","S G","T"] + +**Constraints:** + +* `1 <= s.length <= 200` +* `s` contains only upper case English letters. +* It's guaranteed that there is only one space between 2 words. + +## Solution + +```kotlin +class Solution { + fun printVertically(s: String): List { + val words = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var columnMax = 0 + for (word in words) { + columnMax = Math.max(columnMax, word.length) + } + val matrix = Array(words.size) { CharArray(columnMax) } + for (i in words.indices) { + var j = 0 + while (j < words[i].length) { + matrix[i][j] = words[i][j] + j++ + } + while (j < columnMax) { + matrix[i][j++] = '#' + } + } + val result: MutableList = ArrayList() + for (j in 0 until columnMax) { + val sb = StringBuilder() + for (chars in matrix) { + if (chars[j] != '#') { + sb.append(chars[j]) + } else { + sb.append(' ') + } + } + val str = sb.toString() + var k = str.length - 1 + while (k >= 0 && str[k] == ' ') { + k-- + } + result.add(str.substring(0, k + 1)) + sb.setLength(0) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1325_delete_leaves_with_a_given_value/readme.md b/src/main/kotlin/g1301_1400/s1325_delete_leaves_with_a_given_value/readme.md new file mode 100644 index 00000000..d3e32c4a --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1325_delete_leaves_with_a_given_value/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1325\. Delete Leaves With a Given Value + +Medium + +Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`. + +Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot). + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/01/09/sample_1_1684.png)** + +**Input:** root = [1,2,3,2,null,2,4], target = 2 + +**Output:** [1,null,3,null,4] + +**Explanation:** Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2020/01/09/sample_2_1684.png)** + +**Input:** root = [1,3,3,3,2], target = 3 + +**Output:** [1,3,null,null,2] + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2020/01/15/sample_3_1684.png)** + +**Input:** root = [1,2,null,2,null,2], target = 2 + +**Output:** [1] + +**Explanation:** Leaf nodes in green with value (target = 2) are removed at each step. + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 3000]`. +* `1 <= Node.val, target <= 1000` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +@Suppress("NAME_SHADOWING") +class Solution { + fun removeLeafNodes(root: TreeNode?, target: Int): TreeNode? { + var root = root + while (hasTargetLeafNodes(root, target)) { + root = removeLeafNodes(target, root) + } + return root + } + + private fun removeLeafNodes(target: Int, root: TreeNode?): TreeNode? { + var root = root + if (root == null) { + return root + } + if (root.`val` == target && root.left == null && root.right == null) { + root = null + return root + } + if (root.left != null && root.left!!.`val` == target && root.left!!.left == null && root.left!!.right == null) { + root.left = null + } + if (root.right != null && root.right!!.`val` == target && root.right!!.left == null && + root.right!!.right == null + ) { + root.right = null + } + removeLeafNodes(target, root.left) + removeLeafNodes(target, root.right) + return root + } + + private fun hasTargetLeafNodes(root: TreeNode?, target: Int): Boolean { + if (root == null) { + return false + } + return if (root.left == null && root.right == null && root.`val` == target) { + true + } else hasTargetLeafNodes(root.left, target) || hasTargetLeafNodes(root.right, target) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1326_minimum_number_of_taps_to_open_to_water_a_garden/readme.md b/src/main/kotlin/g1301_1400/s1326_minimum_number_of_taps_to_open_to_water_a_garden/readme.md new file mode 100644 index 00000000..a20842a9 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1326_minimum_number_of_taps_to_open_to_water_a_garden/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1326\. Minimum Number of Taps to Open to Water a Garden + +Hard + +There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). + +There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. + +Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open. + +Return _the minimum number of taps_ that should be open to water the whole garden, If the garden cannot be watered return **\-1**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/16/1685_example_1.png) + +**Input:** n = 5, ranges = [3,4,1,1,0,0] + +**Output:** 1 + +**Explanation:** The tap at point 0 can cover the interval [-3,3] + +The tap at point 1 can cover the interval [-3,5] + +The tap at point 2 can cover the interval [1,3] + +The tap at point 3 can cover the interval [2,4] + +The tap at point 4 can cover the interval [4,4] + +The tap at point 5 can cover the interval [5,5] + +Opening Only the second tap will water the whole garden [0,5] + +**Example 2:** + +**Input:** n = 3, ranges = [0,0,0,0] + +**Output:** -1 + +**Explanation:** Even if you activate all the four taps you cannot water the whole garden. + +**Constraints:** + +* 1 <= n <= 104 +* `ranges.length == n + 1` +* `0 <= ranges[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun minTaps(n: Int, ranges: IntArray): Int { + if (n == 0 || ranges.size == 0) { + return if (n == 0) 0 else -1 + } + val dp = IntArray(n + 1) + var nxtLargest = 0 + var current = 0 + var amount = 0 + for (i in ranges.indices) { + if (ranges[i] > 0) { + val ind = Math.max(0, i - ranges[i]) + dp[ind] = Math.max(dp[ind], i + ranges[i]) + } + } + for (i in 0..n) { + nxtLargest = Math.max(nxtLargest, dp[i]) + if (i == current && i < n) { + current = nxtLargest + amount++ + } + if (current < i) { + return -1 + } + } + return amount + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1328_break_a_palindrome/readme.md b/src/main/kotlin/g1301_1400/s1328_break_a_palindrome/readme.md new file mode 100644 index 00000000..7e908bb5 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1328_break_a_palindrome/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1328\. Break a Palindrome + +Medium + +Given a palindromic string of lowercase English letters `palindrome`, replace **exactly one** character with any lowercase English letter so that the resulting string is **not** a palindrome and that it is the **lexicographically smallest** one possible. + +Return _the resulting string. If there is no way to replace a character to make it not a palindrome, return an **empty string**._ + +A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly smaller than the corresponding character in `b`. For example, `"abcc"` is lexicographically smaller than `"abcd"` because the first position they differ is at the fourth character, and `'c'` is smaller than `'d'`. + +**Example 1:** + +**Input:** palindrome = "abccba" + +**Output:** "aaccba" + +**Explanation:** There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba". Of all the ways, "aaccba" is the lexicographically smallest. + +**Example 2:** + +**Input:** palindrome = "a" + +**Output:** "" + +**Explanation:** There is no way to replace a single character to make "a" not a palindrome, so return an empty string. + +**Constraints:** + +* `1 <= palindrome.length <= 1000` +* `palindrome` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun breakPalindrome(palindrome: String): String { + if (palindrome.length <= 1) { + return "" + } + val sb = StringBuilder() + for (i in 0 until palindrome.length) { + val ch = palindrome[i] + if (ch != 'a' && i != palindrome.length - 1 - i) { + sb.append('a') + sb.append(palindrome.substring(i + 1)) + return sb.toString() + } else { + sb.append(ch) + } + } + sb.deleteCharAt(palindrome.length - 1) + sb.append('b') + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1329_sort_the_matrix_diagonally/readme.md b/src/main/kotlin/g1301_1400/s1329_sort_the_matrix_diagonally/readme.md new file mode 100644 index 00000000..5030154b --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1329_sort_the_matrix_diagonally/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1329\. Sort the Matrix Diagonally + +Medium + +A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`. + +Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return _the resulting matrix_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png) + +**Input:** mat = \[\[3,3,1,1],[2,2,1,2],[1,1,1,2]] + +**Output:** [[1,1,1,1],[1,2,2,2],[1,2,3,3]] + +**Example 2:** + +**Input:** mat = \[\[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] + +**Output:** [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]] + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n <= 100` +* `1 <= mat[i][j] <= 100` + +## Solution + +```kotlin +class Solution { + fun diagonalSort(mat: Array): Array { + val m = mat.size + val n = mat[0].size + val sorted = Array(m) { IntArray(n) } + for (i in m - 1 downTo 0) { + var iCopy = i + val list: MutableList = ArrayList() + run { + var j = 0 + while (j < n && iCopy < m) { + list.add(mat[iCopy][j]) + j++ + iCopy++ + } + } + list.sort() + iCopy = i + var j = 0 + while (j < n && iCopy < m) { + sorted[iCopy][j] = list[j] + j++ + iCopy++ + } + } + for (j in n - 1 downTo 1) { + var jCopy = j + val list: MutableList = ArrayList() + run { + var i = 0 + while (i < m && jCopy < n) { + list.add(mat[i][jCopy]) + i++ + jCopy++ + } + } + list.sort() + jCopy = j + var i = 0 + while (i < m && jCopy < n) { + sorted[i][jCopy] = list[i] + i++ + jCopy++ + } + } + return sorted + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1330_reverse_subarray_to_maximize_array_value/readme.md b/src/main/kotlin/g1301_1400/s1330_reverse_subarray_to_maximize_array_value/readme.md new file mode 100644 index 00000000..3b0548ed --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1330_reverse_subarray_to_maximize_array_value/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1330\. Reverse Subarray To Maximize Array Value + +Hard + +You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. + +You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. + +Find maximum possible value of the final array. + +**Example 1:** + +**Input:** nums = [2,3,1,5,4] + +**Output:** 10 + +**Explanation:** By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10. + +**Example 2:** + +**Input:** nums = [2,4,9,24,2,1,10] + +**Output:** 68 + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* -105 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + private fun getAbsoluteDifference(a: Int, b: Int): Int { + return Math.abs(a - b) + } + + fun maxValueAfterReverse(nums: IntArray): Int { + val n = nums.size + var result = 0 + for (i in 0 until n - 1) { + result += getAbsoluteDifference(nums[i], nums[i + 1]) + } + var minLine = Int.MIN_VALUE + var maxLine = Int.MAX_VALUE + for (i in 0 until n - 1) { + minLine = Math.max(minLine, Math.min(nums[i], nums[i + 1])) + maxLine = Math.min(maxLine, Math.max(nums[i], nums[i + 1])) + } + var diff = Math.max(0, (minLine - maxLine) * 2) + for (i in 1 until n - 1) { + diff = Math.max( + diff, + getAbsoluteDifference(nums[0], nums[i + 1]) - + getAbsoluteDifference(nums[i], nums[i + 1]) + ) + } + for (i in 0 until n - 1) { + diff = Math.max( + diff, + getAbsoluteDifference(nums[n - 1], nums[i]) - + getAbsoluteDifference(nums[i + 1], nums[i]) + ) + } + return result + diff + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1331_rank_transform_of_an_array/readme.md b/src/main/kotlin/g1301_1400/s1331_rank_transform_of_an_array/readme.md new file mode 100644 index 00000000..52f6e3c2 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1331_rank_transform_of_an_array/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1331\. Rank Transform of an Array + +Easy + +Given an array of integers `arr`, replace each element with its rank. + +The rank represents how large the element is. The rank has the following rules: + +* Rank is an integer starting from 1. +* The larger the element, the larger the rank. If two elements are equal, their rank must be the same. +* Rank should be as small as possible. + +**Example 1:** + +**Input:** arr = [40,10,20,30] + +**Output:** [4,1,2,3] + +**Explanation:** 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest. + +**Example 2:** + +**Input:** arr = [100,100,100] + +**Output:** [1,1,1] + +**Explanation:** Same elements share the same rank. + +**Example 3:** + +**Input:** arr = [37,12,28,9,100,56,80,5,12] + +**Output:** [5,3,4,2,8,6,7,1,3] + +**Constraints:** + +* 0 <= arr.length <= 105 +* -109 <= arr[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun arrayRankTransform(arr: IntArray): IntArray { + val tmp = arr.copyOf(arr.size) + tmp.sort() + val mp = HashMap() + var i = 1 + for (x in tmp) { + if (!mp.containsKey(x)) { + mp[x] = i++ + } + } + i = 0 + for (x in arr) { + arr[i++] = mp[x]!! + } + return arr + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1332_remove_palindromic_subsequences/readme.md b/src/main/kotlin/g1301_1400/s1332_remove_palindromic_subsequences/readme.md new file mode 100644 index 00000000..b30d2e72 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1332_remove_palindromic_subsequences/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1332\. Remove Palindromic Subsequences + +Easy + +You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. + +Return _the **minimum** number of steps to make the given string empty_. + +A string is a **subsequence** of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does **not** necessarily need to be contiguous. + +A string is called **palindrome** if is one that reads the same backward as well as forward. + +**Example 1:** + +**Input:** s = "ababa" + +**Output:** 1 + +**Explanation:** s is already a palindrome, so its entirety can be removed in a single step. + +**Example 2:** + +**Input:** s = "abb" + +**Output:** 2 + +**Explanation:** "abb" -> "bb" -> "". Remove palindromic subsequence "a" then "bb". + +**Example 3:** + +**Input:** s = "baabb" + +**Output:** 2 + +**Explanation:** "baabb" -> "b" -> "". Remove palindromic subsequence "baab" then "b". + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s[i]` is either `'a'` or `'b'`. + +## Solution + +```kotlin +class Solution { + fun removePalindromeSub(s: String): Int { + if (s.isEmpty()) { + return 0 + } + return if (s == StringBuilder(s).reverse().toString()) { + 1 + } else 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1333_filter_restaurants_by_vegan_friendly_price_and_distance/readme.md b/src/main/kotlin/g1301_1400/s1333_filter_restaurants_by_vegan_friendly_price_and_distance/readme.md new file mode 100644 index 00000000..259060ba --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1333_filter_restaurants_by_vegan_friendly_price_and_distance/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1333\. Filter Restaurants by Vegan-Friendly, Price and Distance + +Medium + +Given the array `restaurants` where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. + +The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with veganFriendlyi set to true) or _false_ (meaning you can include any restaurant). In addition, you have the filters `maxPrice` and `maxDistance` which are the maximum value for price and distance of restaurants you should consider respectively. + +Return the array of restaurant _**IDs**_ after filtering, ordered by **rating** from highest to lowest. For restaurants with the same rating, order them by _**id**_ from highest to lowest. For simplicity veganFriendlyi and `veganFriendly` take value _1_ when it is _true_, and _0_ when it is _false_. + +**Example 1:** + +**Input:** restaurants = \[\[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10 + +**Output:** [3,1,5] + +**Explanation:** The restaurants are: + +Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10] + +Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5] + +Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4] + +Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3] + +Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] + +After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). + +**Example 2:** + +**Input:** restaurants = \[\[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10 + +**Output:** [4,3,2,1,5] + +**Explanation:** The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered. + +**Example 3:** + +**Input:** restaurants = \[\[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3 + +**Output:** [4,5] + +**Constraints:** + +* `1 <= restaurants.length <= 10^4` +* `restaurants[i].length == 5` +* 1 <= idi, ratingi, pricei, distancei <= 10^5 +* `1 <= maxPrice, maxDistance <= 10^5` +* veganFriendlyi and `veganFriendly` are 0 or 1. +* All idi are distinct. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun filterRestaurants( + restaurants: Array, + veganFriendly: Int, + maxPrice: Int, + maxDistance: Int + ): List { + val pq = PriorityQueue { a: IntArray, b: IntArray -> if (a[1] == b[1]) b[0] - a[0] else b[1] - a[1] } + for (i in restaurants.indices) { + if (restaurants[i][3] <= maxPrice && restaurants[i][4] <= maxDistance) { + if (veganFriendly == 1) { + if (restaurants[i][2] == 1) { + pq.offer(intArrayOf(restaurants[i][0], restaurants[i][1])) + } + } else { + pq.offer(intArrayOf(restaurants[i][0], restaurants[i][1])) + } + } + } + val list: MutableList = ArrayList() + while (pq.isNotEmpty()) { + list.add(pq.poll()[0]) + } + return list + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance/readme.md b/src/main/kotlin/g1301_1400/s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance/readme.md new file mode 100644 index 00000000..17fd268c --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance/readme.md @@ -0,0 +1,131 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1334\. Find the City With the Smallest Number of Neighbors at a Threshold Distance + +Medium + +There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer `distanceThreshold`. + +Return the city with the smallest number of cities that are reachable through some path and whose distance is **at most** `distanceThreshold`, If there are multiple such cities, return the city with the greatest number. + +Notice that the distance of a path connecting cities _**i**_ and _**j**_ is equal to the sum of the edges' weights along that path. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png) + +**Input:** n = 4, edges = \[\[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 + +**Output:** 3 + +**Explanation:** The figure above describes the graph. + +The neighboring cities at a distanceThreshold = 4 for each city are: + +City 0 -> [City 1, City 2] + +City 1 -> [City 0, City 2, City 3] + +City 2 -> [City 0, City 1, City 3] + +City 3 -> [City 1, City 2] + +Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png) + +**Input:** n = 5, edges = \[\[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 + +**Output:** 0 + +**Explanation:** The figure above describes the graph. + +The neighboring cities at a distanceThreshold = 2 for each city are: + +City 0 -> [City 1] + +City 1 -> [City 0, City 4] + +City 2 -> [City 3, City 4] + +City 3 -> [City 2, City 4] + +City 4 -> [City 1, City 2, City 3] + +The city 0 has 1 neighboring city at a distanceThreshold = 2. + +**Constraints:** + +* `2 <= n <= 100` +* `1 <= edges.length <= n * (n - 1) / 2` +* `edges[i].length == 3` +* 0 <= fromi < toi < n +* 1 <= weighti, distanceThreshold <= 10^4 +* All pairs (fromi, toi) are distinct. + +## Solution + +```kotlin +class Solution { + fun findTheCity(n: Int, edges: Array, maxDist: Int): Int { + val graph = Array(n) { IntArray(n) } + for (edge in edges) { + graph[edge[0]][edge[1]] = edge[2] + graph[edge[1]][edge[0]] = edge[2] + } + return fllowdWarshall(graph, n, maxDist) + } + + private fun fllowdWarshall(graph: Array, n: Int, maxDist: Int): Int { + val inf = 10001 + val dist = Array(n) { IntArray(n) } + for (i in 0 until n) { + for (j in 0 until n) { + if (i != j && graph[i][j] == 0) { + dist[i][j] = inf + } else { + dist[i][j] = graph[i][j] + } + } + } + for (k in 0 until n) { + for (i in 0 until n) { + for (j in 0 until n) { + if (dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j] + } + } + } + } + return getList(dist, n, maxDist) + } + + private fun getList(dist: Array, n: Int, maxDist: Int): Int { + val map = HashMap>() + for (i in 0 until n) { + for (j in 0 until n) { + if (!map.containsKey(i)) { + map[i] = ArrayList() + if (dist[i][j] <= maxDist && i != j) { + map[i]!!.add(j) + } + } else if (map.containsKey(i) && dist[i][j] <= maxDist && i != j) { + map[i]!!.add(j) + } + } + } + var numOfEle = Int.MAX_VALUE + var ans = 0 + for (i in 0 until n) { + if (numOfEle >= map[i]!!.size) { + numOfEle = Math.min(numOfEle, map[i]!!.size) + ans = i + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1335_minimum_difficulty_of_a_job_schedule/readme.md b/src/main/kotlin/g1301_1400/s1335_minimum_difficulty_of_a_job_schedule/readme.md new file mode 100644 index 00000000..69b58735 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1335_minimum_difficulty_of_a_job_schedule/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1335\. Minimum Difficulty of a Job Schedule + +Hard + +You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs `j` where `0 <= j < i`). + +You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day. + +You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the ith job is `jobDifficulty[i]`. + +Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/16/untitled.png) + +**Input:** jobDifficulty = [6,5,4,3,2,1], d = 2 + +**Output:** 7 + +**Explanation:** First day you can finish the first 5 jobs, total difficulty = 6. + +Second day you can finish the last job, total difficulty = 1. + +The difficulty of the schedule = 6 + 1 = 7 + +**Example 2:** + +**Input:** jobDifficulty = [9,9,9], d = 4 + +**Output:** -1 + +**Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. + +**Example 3:** + +**Input:** jobDifficulty = [1,1,1], d = 3 + +**Output:** 3 + +**Explanation:** The schedule is one job per day. total difficulty will be 3. + +**Constraints:** + +* `1 <= jobDifficulty.length <= 300` +* `0 <= jobDifficulty[i] <= 1000` +* `1 <= d <= 10` + +## Solution + +```kotlin +class Solution { + fun minDifficulty(jobDifficulty: IntArray, d: Int): Int { + val totalJobs = jobDifficulty.size + if (totalJobs < d) { + return -1 + } + val maxJobsOneDay = totalJobs - d + 1 + val map = IntArray(totalJobs) + var maxDiff = Int.MIN_VALUE + for (k in totalJobs - 1 downTo totalJobs - 1 - maxJobsOneDay + 1) { + maxDiff = Math.max(maxDiff, jobDifficulty[k]) + map[k] = maxDiff + } + for (day in d - 1 downTo 1) { + val maxEndIndex = totalJobs - 1 - (d - day) + val maxStartIndex = maxEndIndex - maxJobsOneDay + 1 + for (startIndex in maxStartIndex..maxEndIndex) { + map[startIndex] = Int.MAX_VALUE + var maxDiffOfTheDay = Int.MIN_VALUE + for (endIndex in startIndex..maxEndIndex) { + maxDiffOfTheDay = Math.max(maxDiffOfTheDay, jobDifficulty[endIndex]) + val totalDiff = maxDiffOfTheDay + map[endIndex + 1] + map[startIndex] = Math.min(map[startIndex], totalDiff) + } + } + } + return map[0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1337_the_k_weakest_rows_in_a_matrix/readme.md b/src/main/kotlin/g1301_1400/s1337_the_k_weakest_rows_in_a_matrix/readme.md new file mode 100644 index 00000000..642ad11b --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1337_the_k_weakest_rows_in_a_matrix/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1337\. The K Weakest Rows in a Matrix + +Easy + +You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row. + +A row `i` is **weaker** than a row `j` if one of the following is true: + +* The number of soldiers in row `i` is less than the number of soldiers in row `j`. +* Both rows have the same number of soldiers and `i < j`. + +Return _the indices of the_ `k` _**weakest** rows in the matrix ordered from weakest to strongest_. + +**Example 1:** + +**Input:** mat = + +[[1,1,0,0,0], + +[1,1,1,1,0], + +[1,0,0,0,0], + +[1,1,0,0,0], + +[1,1,1,1,1]], k = 3 + +**Output:** [2,0,3] + +**Explanation:** The number of soldiers in each row is: +- Row 0: 2 +- Row 1: 4 +- Row 2: 1 +- Row 3: 2 +- Row 4: 5 + +The rows ordered from weakest to strongest are [2,0,3,1,4]. + +**Example 2:** + +**Input:** mat = \[\[1,0,0,0], [1,1,1,1], [1,0,0,0], [1,0,0,0]], k = 2 + +**Output:** [0,2] + +**Explanation:** The number of soldiers in each row is: +- Row 0: 1 +- Row 1: 4 +- Row 2: 1 +- Row 3: 1 + +The rows ordered from weakest to strongest are [0,2,3,1]. + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `2 <= n, m <= 100` +* `1 <= k <= m` +* `matrix[i][j]` is either 0 or 1. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun kWeakestRows(mat: Array, k: Int): IntArray { + val result = IntArray(mat.size) + for (i in mat.indices) { + val index = binarySearch(mat, i, mat[i].size - 1) + result[i] = index + } + var minValue = 101 + val resultK = IntArray(k) + var index = -1 + for (i in 0 until k) { + for (j in result.indices) { + if (result[j] < minValue) { + minValue = result[j] + index = j + } + } + result[index] = 110 + resultK[i] = index + index = -1 + minValue = 101 + } + return resultK + } + + private fun binarySearch(mat: Array, row: Int, end: Int): Int { + var end = end + var start = 0 + while (start <= end) { + val mid = start + (end - start) / 2 + if (mat[row][mid] == 1) { + start = mid + 1 + } else if (mat[row][mid] == 0) { + end = mid - 1 + } + } + return start + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1338_reduce_array_size_to_the_half/readme.md b/src/main/kotlin/g1301_1400/s1338_reduce_array_size_to_the_half/readme.md new file mode 100644 index 00000000..f78b318a --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1338_reduce_array_size_to_the_half/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1338\. Reduce Array Size to The Half + +Medium + +You are given an integer array `arr`. You can choose a set of integers and remove all the occurrences of these integers in the array. + +Return _the minimum size of the set so that **at least** half of the integers of the array are removed_. + +**Example 1:** + +**Input:** arr = [3,3,3,3,5,5,5,2,2,7] + +**Output:** 2 + +**Explanation:** Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array). + +Possible sets of size 2 are {3,5},{3,2},{5,2}. + +Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array. + +**Example 2:** + +**Input:** arr = [7,7,7,7,7,7] + +**Output:** 1 + +**Explanation:** The only possible set you can choose is {7}. This will make the new array empty. + +**Constraints:** + +* 2 <= arr.length <= 105 +* `arr.length` is even. +* 1 <= arr[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun minSetSize(arr: IntArray): Int { + val map: MutableMap = HashMap() + for (num in arr) { + map[num] = map.getOrDefault(num, 0) + 1 + } + val freq: MutableList = ArrayList(map.values) + freq.sortWith(reverseOrder()) + var i = 0 + var count = 0 + var totalLength = arr.size + while (totalLength > arr.size / 2) { + totalLength -= freq[i] + count++ + i++ + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1339_maximum_product_of_splitted_binary_tree/readme.md b/src/main/kotlin/g1301_1400/s1339_maximum_product_of_splitted_binary_tree/readme.md new file mode 100644 index 00000000..37ea5453 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1339_maximum_product_of_splitted_binary_tree/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1339\. Maximum Product of Splitted Binary Tree + +Medium + +Given the `root` of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. + +Return _the maximum product of the sums of the two subtrees_. Since the answer may be too large, return it **modulo** 109 + 7. + +**Note** that you need to maximize the answer before taking the mod and not after taking it. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png) + +**Input:** root = [1,2,3,4,5,6] + +**Output:** 110 + +**Explanation:** Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11\*10) + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png) + +**Input:** root = [1,null,2,3,4,null,null,5,6] + +**Output:** 90 + +**Explanation:** Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15\*6) + +**Constraints:** + +* The number of nodes in the tree is in the range [2, 5 * 104]. +* 1 <= Node.val <= 104 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var maxProduct: Long = 0 + private var total: Long = 0 + + fun sumTree(node: TreeNode?): Int { + if (node == null) { + return 0 + } + node.`val` += sumTree(node.left) + sumTree(node.right) + return node.`val` + } + + private fun helper(root: TreeNode?) { + if (root == null) { + return + } + helper(root.left) + helper(root.right) + val leftSubtreeVal = if (root.left != null) root.left!!.`val`.toLong() else 0L + val leftProduct = leftSubtreeVal * (total - leftSubtreeVal) + val rightSubtreeVal = if (root.right != null) root.right!!.`val`.toLong() else 0L + val rightProduct = rightSubtreeVal * (total - rightSubtreeVal) + maxProduct = Math.max(maxProduct, Math.max(leftProduct, rightProduct)) + } + + fun maxProduct(root: TreeNode?): Int { + if (root == null) { + return 0 + } + total = sumTree(root).toLong() + helper(root) + return (maxProduct % 1000000007L).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1340_jump_game_v/readme.md b/src/main/kotlin/g1301_1400/s1340_jump_game_v/readme.md new file mode 100644 index 00000000..7efd61fc --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1340_jump_game_v/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1340\. Jump Game V + +Hard + +Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index: + +* `i + x` where: `i + x < arr.length` and `0 < x <= d`. +* `i - x` where: `i - x >= 0` and `0 < x <= d`. + +In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`). + +You can choose any index of the array and start jumping. Return _the maximum number of indices_ you can visit. + +Notice that you can not jump outside of the array at any time. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/23/meta-chart.jpeg) + +**Input:** arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 + +**Output:** 4 + +**Explanation:** You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown. Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9. Similarly You cannot jump from index 3 to index 2 or index 1. + +**Example 2:** + +**Input:** arr = [3,3,3,3,3], d = 3 + +**Output:** 1 + +**Explanation:** You can start at any index. You always cannot jump to any index. + +**Example 3:** + +**Input:** arr = [7,6,5,4,3,2,1], d = 1 + +**Output:** 7 + +**Explanation:** Start at index 0. You can visit all the indicies. + +**Constraints:** + +* `1 <= arr.length <= 1000` +* 1 <= arr[i] <= 105 +* `1 <= d <= arr.length` + +## Solution + +```kotlin +class Solution { + fun maxJumps(arr: IntArray, d: Int): Int { + val n = arr.size + var res = 0 + var top = 0 + val dp = IntArray(n) + val stack = IntArray(n) + for (i in 0..n) { + while (top > 0 && (i == n || arr[stack[top - 1]] < arr[i])) { + val r = top - 1 + var l = r - 1 + while (l >= 0 && arr[stack[l]] == arr[stack[r]]) l-- + for (j in l + 1..r) { + if (l >= 0 && stack[j] - stack[l] <= d) dp[stack[l]] = Math.max(dp[stack[l]], 1 + dp[stack[j]]) + if (i < n && i - stack[j] <= d) dp[i] = Math.max(dp[i], 1 + dp[stack[j]]) + } + top -= r - l + } + stack[top++] = i + } + for (i in 0 until n) res = Math.max(res, dp[i]) + return res + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1342_number_of_steps_to_reduce_a_number_to_zero/readme.md b/src/main/kotlin/g1301_1400/s1342_number_of_steps_to_reduce_a_number_to_zero/readme.md new file mode 100644 index 00000000..e5ff8425 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1342_number_of_steps_to_reduce_a_number_to_zero/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1342\. Number of Steps to Reduce a Number to Zero + +Easy + +Given an integer `num`, return _the number of steps to reduce it to zero_. + +In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. + +**Example 1:** + +**Input:** num = 14 + +**Output:** 6 + +**Explanation:** + +Step 1) 14 is even; divide by 2 and obtain 7. + +Step 2) 7 is odd; subtract 1 and obtain 6. + +Step 3) 6 is even; divide by 2 and obtain 3. + +Step 4) 3 is odd; subtract 1 and obtain 2. + +Step 5) 2 is even; divide by 2 and obtain 1. + +Step 6) 1 is odd; subtract 1 and obtain 0. + +**Example 2:** + +**Input:** num = 8 + +**Output:** 4 + +**Explanation:** + +Step 1) 8 is even; divide by 2 and obtain 4. + +Step 2) 4 is even; divide by 2 and obtain 2. + +Step 3) 2 is even; divide by 2 and obtain 1. + +Step 4) 1 is odd; subtract 1 and obtain 0. + +**Example 3:** + +**Input:** num = 123 + +**Output:** 12 + +**Constraints:** + +* 0 <= num <= 106 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun numberOfSteps(num: Int): Int { + var num = num + var steps = 0 + while (num != 0) { + if (num % 2 == 0) { + num /= 2 + } else { + num-- + } + steps++ + } + return steps + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold/readme.md b/src/main/kotlin/g1301_1400/s1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold/readme.md new file mode 100644 index 00000000..a48e1de5 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1343\. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold + +Medium + +Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. + +**Example 1:** + +**Input:** arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 + +**Output:** 3 + +**Explanation:** Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold). + +**Example 2:** + +**Input:** arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 + +**Output:** 6 + +**Explanation:** The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers. + +**Constraints:** + +* 1 <= arr.length <= 105 +* 1 <= arr[i] <= 104 +* `1 <= k <= arr.length` +* 0 <= threshold <= 104 + +## Solution + +```kotlin +class Solution { + fun numOfSubarrays(arr: IntArray, k: Int, threshold: Int): Int { + var sum = 0 + for (i in 0 until k - 1) { + sum += arr[i] + } + var count = 0 + for (i in k - 1 until arr.size) { + sum += arr[i] + if (i - k >= 0) { + sum -= arr[i - k] + } + if (sum / k >= threshold) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1344_angle_between_hands_of_a_clock/readme.md b/src/main/kotlin/g1301_1400/s1344_angle_between_hands_of_a_clock/readme.md new file mode 100644 index 00000000..fcc53756 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1344_angle_between_hands_of_a_clock/readme.md @@ -0,0 +1,54 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1344\. Angle Between Hands of a Clock + +Medium + +Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. + +Answers within 10-5 of the actual value will be accepted as correct. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png) + +**Input:** hour = 12, minutes = 30 + +**Output:** 165 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png) + +**Input:** hour = 3, minutes = 30 + +**Output:** 75 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png) + +**Input:** hour = 3, minutes = 15 + +**Output:** 7.5 + +**Constraints:** + +* `1 <= hour <= 12` +* `0 <= minutes <= 59` + +## Solution + +```kotlin +class Solution { + fun angleClock(hour: Int, minutes: Int): Double { + val minAngle = minutes * 360.0 / 60 + val hourAnglePart1: Double = if (hour != 12) hour * 360.0 / 12 else 0.0 + val hourAnglePart2 = (30 * minutes).toDouble() / 60.0 + val hourAngle = hourAnglePart1 + hourAnglePart2 + val preResult = Math.abs(minAngle - hourAngle) + return if (preResult > 180) 360 - preResult else preResult + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1345_jump_game_iv/readme.md b/src/main/kotlin/g1301_1400/s1345_jump_game_iv/readme.md new file mode 100644 index 00000000..6d65db77 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1345_jump_game_iv/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1345\. Jump Game IV + +Hard + +Given an array of integers `arr`, you are initially positioned at the first index of the array. + +In one step you can jump from index `i` to index: + +* `i + 1` where: `i + 1 < arr.length`. +* `i - 1` where: `i - 1 >= 0`. +* `j` where: `arr[i] == arr[j]` and `i != j`. + +Return _the minimum number of steps_ to reach the **last index** of the array. + +Notice that you can not jump outside of the array at any time. + +**Example 1:** + +**Input:** arr = [100,-23,-23,404,100,23,23,23,3,404] + +**Output:** 3 + +**Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. + +**Example 2:** + +**Input:** arr = [7] + +**Output:** 0 + +**Explanation:** Start index is the last index. You do not need to jump. + +**Example 3:** + +**Input:** arr = [7,6,9,6,9,6,9,7] + +**Output:** 1 + +**Explanation:** You can jump directly from index 0 to index 7 which is last index of the array. + +**Constraints:** + +* 1 <= arr.length <= 5 * 104 +* -108 <= arr[i] <= 108 + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun minJumps(arr: IntArray): Int { + if (arr.size == 1) { + return 0 + } + val len = arr.size + val myHash = HashMap>() + var i = 0 + while (i < arr.size) { + val curList = myHash.getOrDefault(arr[i], ArrayList()) + curList.add(i) + val tempNum = arr[i] + val tempIndex = i + while (i < arr.size && arr[i] == tempNum) { + i++ + } + if (i != tempIndex + 1) { + curList.add(i - 1) + } + myHash[tempNum] = curList + } + val myQueue: Deque = LinkedList() + var step = 0 + myQueue.offerLast(0) + val visited = BooleanArray(arr.size) + visited[0] = true + while (myQueue.isNotEmpty()) { + val curCount = myQueue.size + var j = 0 + while (j < curCount) { + val curIndex = myQueue.pollFirst() + if (curIndex == len - 1) { + return step + } + if (curIndex + 1 < len && !visited[curIndex + 1]) { + myQueue.offerLast(curIndex + 1) + visited[curIndex + 1] = true + } + if (curIndex - 1 >= 0 && !visited[curIndex - 1]) { + myQueue.offerLast(curIndex - 1) + visited[curIndex - 1] = true + } + val tempList: List = myHash.getOrDefault(arr[curIndex], ArrayList()) + for (integer in tempList) { + if (!visited[integer]) { + myQueue.offerLast(integer) + visited[integer] = true + } + } + myHash.remove(arr[curIndex]) + j++ + } + step++ + } + return step + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1346_check_if_n_and_its_double_exist/readme.md b/src/main/kotlin/g1301_1400/s1346_check_if_n_and_its_double_exist/readme.md new file mode 100644 index 00000000..fbd212fa --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1346_check_if_n_and_its_double_exist/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1346\. Check If N and Its Double Exist + +Easy + +Given an array `arr` of integers, check if there exists two integers `N` and `M` such that `N` is the double of `M` ( i.e. `N = 2 * M`). + +More formally check if there exists two indices `i` and `j` such that : + +* `i != j` +* `0 <= i, j < arr.length` +* `arr[i] == 2 * arr[j]` + +**Example 1:** + +**Input:** arr = [10,2,5,3] + +**Output:** true + +**Explanation:** N `= 10` is the double of M `= 5`,that is, `10 = 2 * 5`. + +**Example 2:** + +**Input:** arr = [7,1,14,11] + +**Output:** true + +**Explanation:** N `= 14` is the double of M `= 7`,that is, `14 = 2 * 7`. + +**Example 3:** + +**Input:** arr = [3,1,7,11] + +**Output:** false + +**Explanation:** In this case does not exist N and M, such that N = 2 \* M. + +**Constraints:** + +* `2 <= arr.length <= 500` +* `-10^3 <= arr[i] <= 10^3` + +## Solution + +```kotlin +class Solution { + fun checkIfExist(arr: IntArray): Boolean { + for (i in arr.indices) { + for (j in arr.indices) { + if (i != j && (arr[i] * 2 == arr[j] || arr[i] == arr[j] * 2)) { + return true + } + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1347_minimum_number_of_steps_to_make_two_strings_anagram/readme.md b/src/main/kotlin/g1301_1400/s1347_minimum_number_of_steps_to_make_two_strings_anagram/readme.md new file mode 100644 index 00000000..a8be87c9 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1347_minimum_number_of_steps_to_make_two_strings_anagram/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1347\. Minimum Number of Steps to Make Two Strings Anagram + +Medium + +You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. + +Return _the minimum number of steps_ to make `t` an anagram of `s`. + +An **Anagram** of a string is a string that contains the same characters with a different (or the same) ordering. + +**Example 1:** + +**Input:** s = "bab", t = "aba" + +**Output:** 1 + +**Explanation:** Replace the first 'a' in t with b, t = "bba" which is anagram of s. + +**Example 2:** + +**Input:** s = "leetcode", t = "practice" + +**Output:** 5 + +**Explanation:** Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. + +**Example 3:** + +**Input:** s = "anagram", t = "mangaar" + +**Output:** 0 + +**Explanation:** "anagram" and "mangaar" are anagrams. + +**Constraints:** + +* 1 <= s.length <= 5 * 104 +* `s.length == t.length` +* `s` and `t` consist of lowercase English letters only. + +## Solution + +```kotlin +class Solution { + fun minSteps(s: String, t: String): Int { + val counts = IntArray(26) + for (c in s.toCharArray()) { + counts[c.code - 'a'.code]++ + } + for (c in t.toCharArray()) { + if (counts[c.code - 'a'.code] > 0) { + counts[c.code - 'a'.code]-- + } + } + return counts.sum() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1348_tweet_counts_per_frequency/readme.md b/src/main/kotlin/g1301_1400/s1348_tweet_counts_per_frequency/readme.md new file mode 100644 index 00000000..9d668612 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1348_tweet_counts_per_frequency/readme.md @@ -0,0 +1,140 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1348\. Tweet Counts Per Frequency + +Medium + +A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). + +For example, the period `[10, 10000]` (in **seconds**) would be partitioned into the following **time chunks** with these frequencies: + +* Every **minute** (60-second chunks): `[10,69]`, `[70,129]`, `[130,189]`, `...`, `[9970,10000]` +* Every **hour** (3600-second chunks): `[10,3609]`, `[3610,7209]`, `[7210,10000]` +* Every **day** (86400-second chunks): `[10,10000]` + +Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (`10000` in the above example). + +Design and implement an API to help the company with their analysis. + +Implement the `TweetCounts` class: + +* `TweetCounts()` Initializes the `TweetCounts` object. +* `void recordTweet(String tweetName, int time)` Stores the `tweetName` at the recorded `time` (in **seconds**). +* `List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime)` Returns a list of integers representing the number of tweets with `tweetName` in each **time chunk** for the given period of time `[startTime, endTime]` (in **seconds**) and frequency `freq`. + * `freq` is one of `"minute"`, `"hour"`, or `"day"` representing a frequency of every **minute**, **hour**, or **day** respectively. + +**Example:** + +**Input** ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"] + +[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]] + +**Output:** [null,null,null,null,[2],[2,1],null,[4]] + +**Explanation:** + +TweetCounts tweetCounts = new TweetCounts(); + +tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0 + +tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60 + +tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10 + +tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets + +tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet + +tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120 + +tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets + +**Constraints:** + +* 0 <= time, startTime, endTime <= 109 +* 0 <= endTime - startTime <= 104 +* There will be at most 104 calls **in total** to `recordTweet` and `getTweetCountsPerFrequency`. + +## Solution + +```kotlin +class TweetCounts { + private val store: MutableMap>>>> + + init { + store = HashMap() + } + + fun recordTweet(tweetName: String, time: Int) { + val d = time / DAY + val h = (time - d * DAY) / HOUR + val m = (time - d * DAY - h * HOUR) / MINUTE + val dstore = store.computeIfAbsent(tweetName) { _: String? -> HashMap() } + val hstore = dstore.computeIfAbsent(d) { _: Int? -> HashMap() } + val mstore = hstore.computeIfAbsent(h) { _: Int? -> HashMap() } + mstore.computeIfAbsent(m) { _: Int? -> ArrayList() }.add(time) + } + + fun getTweetCountsPerFrequency( + freq: String, + tweetName: String, + startTime: Int, + endTime: Int + ): List { + val sfreq = convFreqToSecond(freq) + val dstore: Map>>> = store[tweetName]!! + val chunks = IntArray((endTime - startTime) / sfreq + 1) + val sd = startTime / DAY + val ed = endTime / DAY + for (d in sd..ed) { + if (!dstore.containsKey(d)) { + continue + } + val sh = if (startTime <= d * DAY) 0 else (startTime - d * DAY) / HOUR + val eh = if (endTime > (d + 1) * DAY) DAY / HOUR else (endTime - d * DAY) / HOUR + 1 + val hstore: Map>> = dstore[d]!! + for (h in sh until eh) { + if (!hstore.containsKey(h)) { + continue + } + val sm = if (startTime <= d * DAY + h * HOUR) 0 + else (startTime - d * DAY - h * HOUR) / MINUTE + val em = if (endTime > d * DAY + (h + 1) * HOUR) HOUR / MINUTE + else (endTime - d * DAY - h * HOUR) / MINUTE + 1 + val mstore: Map> = hstore[h]!! + for (m in sm..em) { + if (!mstore.containsKey(m)) { + continue + } + for (rc in mstore[m]!!) { + if (startTime <= rc && rc <= endTime) { + chunks[(rc - startTime) / sfreq]++ + } + } + } + } + } + val ans: MutableList = ArrayList() + for (chunk in chunks) { + ans.add(chunk) + } + return ans + } + + private fun convFreqToSecond(freq: String): Int { + return when (freq) { + "minute" -> MINUTE + "hour" -> HOUR + "day" -> DAY + else -> 0 + } + } + + companion object { + private const val MINUTE = 60 + private const val HOUR = 3600 + private const val DAY = 86400 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1349_maximum_students_taking_exam/readme.md b/src/main/kotlin/g1301_1400/s1349_maximum_students_taking_exam/readme.md new file mode 100644 index 00000000..32f57a88 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1349_maximum_students_taking_exam/readme.md @@ -0,0 +1,96 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1349\. Maximum Students Taking Exam + +Hard + +Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. + +Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible.. + +Students must be placed in seats in good condition. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/29/image.png) + +**Input:** seats = \[\["#",".","#","#",".","#"], + [".","#","#","#","#","."], + ["#",".","#","#",".","#"]] + +**Output:** 4 + +**Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam. + +**Example 2:** + +**Input:** seats = \[\[".","#"], + ["#","#"], + ["#","."], + ["#","#"], + [".","#"]] + +**Output:** 3 + +**Explanation:** Place all students in available seats. + +**Example 3:** + +**Input:** seats = \[\["#",".","**.**",".","#"], + ["**.**","#","**.**","#","**.**"], + ["**.**",".","#",".","**.**"], + ["**.**","#","**.**","#","**.**"], + ["#",".","**.**",".","#"]] + +**Output:** 10 + +**Explanation:** Place students in available seats in column 1, 3 and 5. + +**Constraints:** + +* `seats` contains only characters `'.' and``'#'.` +* `m == seats.length` +* `n == seats[i].length` +* `1 <= m <= 8` +* `1 <= n <= 8` + +## Solution + +```kotlin +class Solution { + fun maxStudents(seats: Array): Int { + val m = seats.size + val n = seats[0].size + val validRows = IntArray(m) + for (i in 0 until m) { + for (j in 0 until n) { + validRows[i] = (validRows[i] shl 1) + if (seats[i][j] == '.') 1 else 0 + } + } + val stateSize = 1 shl n + val dp = Array(m) { IntArray(stateSize) } + for (i in 0 until m) { + dp[i].fill(-1) + } + var ans = 0 + for (i in 0 until m) { + for (j in 0 until stateSize) { + if (j and validRows[i] == j && j and (j shl 1) == 0) { + if (i == 0) { + dp[i][j] = Integer.bitCount(j) + } else { + for (k in 0 until stateSize) { + if (k shl 1 and j == 0 && j shl 1 and k == 0 && dp[i - 1][k] != -1) { + dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + Integer.bitCount(j)) + } + } + } + ans = Math.max(ans, dp[i][j]) + } + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix/readme.md b/src/main/kotlin/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix/readme.md new file mode 100644 index 00000000..b656302d --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix/readme.md @@ -0,0 +1,49 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1351\. Count Negative Numbers in a Sorted Matrix + +Easy + +Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. + +**Example 1:** + +**Input:** grid = \[\[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] + +**Output:** 8 + +**Explanation:** There are 8 negatives number in the matrix. + +**Example 2:** + +**Input:** grid = \[\[3,2],[1,0]] + +**Output:** 0 + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 100` +* `-100 <= grid[i][j] <= 100` + +**Follow up:** Could you find an `O(n + m)` solution? + +## Solution + +```kotlin +class Solution { + fun countNegatives(grid: Array): Int { + var count = 0 + for (row in grid) { + for (v in row) { + if (v < 0) { + count++ + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1352_product_of_the_last_k_numbers/readme.md b/src/main/kotlin/g1301_1400/s1352_product_of_the_last_k_numbers/readme.md new file mode 100644 index 00000000..c5943f5e --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1352_product_of_the_last_k_numbers/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1352\. Product of the Last K Numbers + +Medium + +Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. + +Implement the `ProductOfNumbers` class: + +* `ProductOfNumbers()` Initializes the object with an empty stream. +* `void add(int num)` Appends the integer `num` to the stream. +* `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers. + +The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. + +**Example:** + +**Input** ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] + +**Output:** [null,null,null,null,null,null,20,40,0,null,32] + +**Explanation:** ProductOfNumbers productOfNumbers = new ProductOfNumbers(); productOfNumbers.add(3); // [3] productOfNumbers.add(0); // [3,0] productOfNumbers.add(2); // [3,0,2] productOfNumbers.add(5); // [3,0,2,5] productOfNumbers.add(4); // [3,0,2,5,4] productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 \* 4 = 20 productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 \* 5 \* 4 = 40 productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 \* 2 \* 5 \* 4 = 0 productOfNumbers.add(8); // [3,0,2,5,4,8] productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 \* 8 = 32 + +**Constraints:** + +* `0 <= num <= 100` +* 1 <= k <= 4 * 104 +* At most 4 * 104 calls will be made to `add` and `getProduct`. +* The product of the stream at any point in time will fit in a **32-bit** integer. + +## Solution + +```kotlin +class ProductOfNumbers { + private var ints = ArrayList() + + fun add(num: Int) { + if (num == 0) ints.clear() else ints.add(if (ints.isEmpty()) num else num * ints[ints.size - 1]) + } + + fun getProduct(k: Int): Int { + val n = ints.size + if (k > n) return 0 + return if (k == n) ints[n - 1] else ints[n - 1] / ints[n - 1 - k] + } +} +/* + * Your ProductOfNumbers object will be instantiated and called as such: + * var obj = ProductOfNumbers() + * obj.add(num) + * var param_2 = obj.getProduct(k) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1353_maximum_number_of_events_that_can_be_attended/readme.md b/src/main/kotlin/g1301_1400/s1353_maximum_number_of_events_that_can_be_attended/readme.md new file mode 100644 index 00000000..cbd5c893 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1353_maximum_number_of_events_that_can_be_attended/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1353\. Maximum Number of Events That Can Be Attended + +Medium + +You are given an array of `events` where events[i] = [startDayi, endDayi]. Every event `i` starts at startDayi and ends at endDayi. + +You can attend an event `i` at any day `d` where startTimei <= d <= endTimei. You can only attend one event at any time `d`. + +Return _the maximum number of events you can attend_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/05/e1.png) + +**Input:** events = \[\[1,2],[2,3],[3,4]] + +**Output:** 3 + +**Explanation:** You can attend all the three events. + +One way to attend them all is as shown. + +Attend the first event on day 1. + +Attend the second event on day 2. + +Attend the third event on day 3. + +**Example 2:** + +**Input:** events= [[1,2],[2,3],[3,4],[1,2]] + +**Output:** 4 + +**Constraints:** + +* 1 <= events.length <= 105 +* `events[i].length == 2` +* 1 <= startDayi <= endDayi <= 105 + +## Solution + +```kotlin +import java.util.Arrays +import java.util.PriorityQueue + +class Solution { + fun maxEvents(events: Array): Int { + Arrays.sort(events) { a: IntArray, b: IntArray -> a[0] - b[0] } + var ans = 0 + var i = 0 + val pq = PriorityQueue() + for (day in 1..100000) { + while (i < events.size && events[i][0] == day) { + pq.add(events[i][1]) + i++ + } + while (pq.isNotEmpty() && pq.peek() < day) { + pq.poll() + } + if (pq.isNotEmpty() && pq.peek() >= day) { + pq.poll() + ans++ + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1354_construct_target_array_with_multiple_sums/readme.md b/src/main/kotlin/g1301_1400/s1354_construct_target_array_with_multiple_sums/readme.md new file mode 100644 index 00000000..4900ebc1 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1354_construct_target_array_with_multiple_sums/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1354\. Construct Target Array With Multiple Sums + +Hard + +You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : + +* let `x` be the sum of all elements currently in your array. +* choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. +* You may repeat this procedure as many times as needed. + +Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`. + +**Example 1:** + +**Input:** target = [9,3,5] + +**Output:** true + +**Explanation:** Start with arr = [1, 1, 1] + +[1, 1, 1], sum = 3 choose index 1 + +[1, 3, 1], sum = 5 choose index 2 + +[1, 3, 5], sum = 9 choose index 0 + +[9, 3, 5] Done + +**Example 2:** + +**Input:** target = [1,1,1,2] + +**Output:** false + +**Explanation:** Impossible to create target array from [1,1,1,1]. + +**Example 3:** + +**Input:** target = [8,5] + +**Output:** true + +**Constraints:** + +* `n == target.length` +* 1 <= n <= 5 * 104 +* 1 <= target[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun isPossible(target: IntArray): Boolean { + var sum = target[0].toLong() + var maxIndex = 0 + for (i in 1 until target.size) { + sum += target[i].toLong() + if (target[i] > target[maxIndex]) { + maxIndex = i + } + } + val remainingSum = sum - target[maxIndex] + if (target[maxIndex] == 1 || remainingSum == 1L) { + return true + } + if (remainingSum >= target[maxIndex] || remainingSum == 0L || target[maxIndex] % remainingSum == 0L) { + return false + } + target[maxIndex] %= remainingSum.toInt() + return isPossible(target) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits/readme.md b/src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits/readme.md new file mode 100644 index 00000000..290d3f23 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1356\. Sort Integers by The Number of 1 Bits + +Easy + +You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. + +Return _the array after sorting it_. + +**Example 1:** + +**Input:** arr = [0,1,2,3,4,5,6,7,8] + +**Output:** [0,1,2,4,8,3,5,6,7] **Explantion:** [0] is the only integer with 0 bits. + +[1,2,4,8] all have 1 bit. + +[3,5,6] have 2 bits. + +[7] has 3 bits. + +The sorted array by bits is [0,1,2,4,8,3,5,6,7] + +**Example 2:** + +**Input:** arr = [1024,512,256,128,64,32,16,8,4,2,1] + +**Output:** [1,2,4,8,16,32,64,128,256,512,1024] **Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order. + +**Constraints:** + +* `1 <= arr.length <= 500` +* 0 <= arr[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun sortByBits(arr: IntArray): IntArray { + val map: MutableMap> = HashMap() + for (num in arr) { + val count = Integer.bitCount(num) + map.putIfAbsent(count, ArrayList()) + map[count]!!.add(num) + } + val result = IntArray(arr.size) + var i = 0 + for ((_, list) in map) { + list.sort() + for (num in list) { + result[i++] = num + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1357_apply_discount_every_n_orders/readme.md b/src/main/kotlin/g1301_1400/s1357_apply_discount_every_n_orders/readme.md new file mode 100644 index 00000000..9e03bbe5 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1357_apply_discount_every_n_orders/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1357\. Apply Discount Every n Orders + +Medium + +There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the ith product has an ID of `products[i]` and a price of `prices[i]`. + +When a customer is paying, their bill is represented as two parallel integer arrays `product` and `amount`, where the jth product they purchased has an ID of `product[j]`, and `amount[j]` is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product). + +The supermarket decided to have a sale. Every nth customer paying for their groceries will be given a **percentage discount**. The discount amount is given by `discount`, where they will be given `discount` percent off their subtotal. More formally, if their subtotal is `bill`, then they would actually pay `bill * ((100 - discount) / 100)`. + +Implement the `Cashier` class: + +* `Cashier(int n, int discount, int[] products, int[] prices)` Initializes the object with `n`, the `discount`, and the `products` and their `prices`. +* `double getBill(int[] product, int[] amount)` Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted. + +**Example 1:** + +**Input** ["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"] + +[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]] + +**Output:** [null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0] + +**Explanation:** + +Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]); + +cashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount. + +// bill = 1 \* 100 + 2 \* 200 = 500. + +cashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount. + +// bill = 10 \* 300 + 10 \* 100 = 4000. + +cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount. + +// Original bill = 1600 + +// Actual bill = 1600 \* ((100 - 50) / 100) = 800. + +cashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount. + +cashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount. + +cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount. + +// Original bill = 14700, but with + +// Actual bill = 14700 \* ((100 - 50) / 100) = 7350. + +cashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6th customer, no discount. + +**Constraints:** + +* 1 <= n <= 104 +* `0 <= discount <= 100` +* `1 <= products.length <= 200` +* `prices.length == products.length` +* `1 <= products[i] <= 200` +* `1 <= prices[i] <= 1000` +* The elements in `products` are **unique**. +* `1 <= product.length <= products.length` +* `amount.length == product.length` +* `product[j]` exists in `products`. +* `1 <= amount[j] <= 1000` +* The elements of `product` are **unique**. +* At most `1000` calls will be made to `getBill`. +* Answers within 10-5 of the actual value will be accepted. + +## Solution + +```kotlin +class Cashier(private val nthCustomer: Int, discount: Int, products: IntArray, prices: IntArray) { + private val map: MutableMap + private var customerCountTrack = 0 + private val discountPercent: Double + + init { + map = HashMap() + discountPercent = discount * .01 + for (i in products.indices) { + map[products[i]] = prices[i] + } + } + + fun getBill(product: IntArray, amount: IntArray): Double { + customerCountTrack++ + var sum = 0.0 + for (i in product.indices) { + sum += (map[product[i]]!! * amount[i]).toDouble() + } + // discount customer + return if (customerCountTrack % nthCustomer == 0) { + sum - sum * discountPercent + } else sum + } +} +/* + * Your Cashier object will be instantiated and called as such: + * var obj = Cashier(n, discount, products, prices) + * var param_1 = obj.getBill(product,amount) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1358_number_of_substrings_containing_all_three_characters/readme.md b/src/main/kotlin/g1301_1400/s1358_number_of_substrings_containing_all_three_characters/readme.md new file mode 100644 index 00000000..104ab00b --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1358_number_of_substrings_containing_all_three_characters/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1358\. Number of Substrings Containing All Three Characters + +Medium + +Given a string `s` consisting only of characters _a_, _b_ and _c_. + +Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_. + +**Example 1:** + +**Input:** s = "abcabc" + +**Output:** 10 + +**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc_", "_abca_", "_abcab_", "_abcabc_", "_bca_", "_bcab_", "_bcabc_", "_cab_", "_cabc_"_ and _"_abc_"_ (**again**)_._ + +**Example 2:** + +**Input:** s = "aaacb" + +**Output:** 3 + +**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb_", "_aacb_"_ and _"_acb_"._ + +**Example 3:** + +**Input:** s = "abc" + +**Output:** 1 + +**Constraints:** + +* `3 <= s.length <= 5 x 10^4` +* `s` only consists of _a_, _b_ or _c _characters. + +## Solution + +```kotlin +class Solution { + fun numberOfSubstrings(s: String): Int { + val counts = IntArray(3) + var i = 0 + val n = s.length + var result = 0 + for (j in 0 until n) { + counts[s[j].code - 'a'.code]++ + while (counts[0] > 0 && counts[1] > 0 && counts[2] > 0) { + counts[s[i++].code - 'a'.code]-- + } + result += i + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1359_count_all_valid_pickup_and_delivery_options/readme.md b/src/main/kotlin/g1301_1400/s1359_count_all_valid_pickup_and_delivery_options/readme.md new file mode 100644 index 00000000..0949b963 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1359_count_all_valid_pickup_and_delivery_options/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1359\. Count All Valid Pickup and Delivery Options + +Hard + +Given `n` orders, each order consist in pickup and delivery services. + +Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). + +Since the answer may be too large, return it modulo 10^9 + 7. + +**Example 1:** + +**Input:** n = 1 + +**Output:** 1 + +**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1. + +**Example 2:** + +**Input:** n = 2 + +**Output:** 6 + +**Explanation:** All possible orders: + +(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). + +This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. + +**Example 3:** + +**Input:** n = 3 + +**Output:** 90 + +**Constraints:** + +* `1 <= n <= 500` + +## Solution + +```kotlin +class Solution { + fun countOrders(n: Int): Int { + val dp = LongArray(n + 1) + dp[1] = 1 + val mod = 1e9.toLong() + 7 + for (i in 2..n) { + val gaps = (i - 1) * 2L + 1 + dp[i] = gaps * (gaps + 1) / 2 * dp[i - 1] % mod + } + return dp[n].toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1360_number_of_days_between_two_dates/readme.md b/src/main/kotlin/g1301_1400/s1360_number_of_days_between_two_dates/readme.md new file mode 100644 index 00000000..eaa3f7b4 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1360_number_of_days_between_two_dates/readme.md @@ -0,0 +1,48 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1360\. Number of Days Between Two Dates + +Easy + +Write a program to count the number of days between two dates. + +The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. + +**Example 1:** + +**Input:** date1 = "2019-06-29", date2 = "2019-06-30" + +**Output:** 1 + +**Example 2:** + +**Input:** date1 = "2020-01-15", date2 = "2019-12-31" + +**Output:** 15 + +**Constraints:** + +* The given dates are valid dates between the years `1971` and `2100`. + +## Solution + +```kotlin +class Solution { + fun daysBetweenDates(date1: String, date2: String): Int { + val strings1 = date1.split("-").dropLastWhile { it.isEmpty() }.toTypedArray() + val strings2 = date2.split("-").dropLastWhile { it.isEmpty() }.toTypedArray() + return Math.abs( + julianDay(strings1[0].toInt(), strings1[1].toInt(), strings1[2].toInt()) - + julianDay(strings2[0].toInt(), strings2[1].toInt(), strings2[2].toInt()) + ) + } + + private fun julianDay(year: Int, month: Int, day: Int): Int { + val a = (14 - month) / 12 + val y = year + 4800 - a + val m = month + 12 * a - 3 + return day + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1361_validate_binary_tree_nodes/readme.md b/src/main/kotlin/g1301_1400/s1361_validate_binary_tree_nodes/readme.md new file mode 100644 index 00000000..48480c6d --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1361_validate_binary_tree_nodes/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1361\. Validate Binary Tree Nodes + +Medium + +You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. + +If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. + +Note that the nodes have no values and that we only use the node numbers in this problem. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/08/23/1503_ex1.png) + +**Input:** n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/08/23/1503_ex2.png) + +**Input:** n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] + +**Output:** false + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/08/23/1503_ex3.png) + +**Input:** n = 2, leftChild = [1,0], rightChild = [-1,-1] + +**Output:** false + +**Constraints:** + +* `n == leftChild.length == rightChild.length` +* 1 <= n <= 104 +* `-1 <= leftChild[i], rightChild[i] <= n - 1` + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque + +class Solution { + fun validateBinaryTreeNodes(n: Int, leftChild: IntArray, rightChild: IntArray): Boolean { + val inDeg = IntArray(n) + for (i in 0 until n) { + if (leftChild[i] >= 0) { + inDeg[leftChild[i]] += 1 + } + if (rightChild[i] >= 0) { + inDeg[rightChild[i]] += 1 + } + } + val queue: Deque = ArrayDeque() + for (i in 0 until n) { + if (inDeg[i] == 0) { + if (queue.isEmpty()) { + queue.offer(i) + } else { + // Violate rule 1. + return false + } + } + if (inDeg[i] > 1) { + // Violate rule 2. + return false + } + } + var tpLen = 0 + while (queue.isNotEmpty()) { + val curNode = queue.poll() + tpLen++ + val left = leftChild[curNode] + val right = rightChild[curNode] + if (left > -1 && --inDeg[left] == 0) { + queue.offer(left) + } + if (right > -1 && --inDeg[right] == 0) { + queue.offer(right) + } + } + return tpLen == n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1362_closest_divisors/readme.md b/src/main/kotlin/g1301_1400/s1362_closest_divisors/readme.md new file mode 100644 index 00000000..75ef31d1 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1362_closest_divisors/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1362\. Closest Divisors + +Medium + +Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. + +Return the two integers in any order. + +**Example 1:** + +**Input:** num = 8 + +**Output:** [3,3] + +**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. + +**Example 2:** + +**Input:** num = 123 + +**Output:** [5,25] + +**Example 3:** + +**Input:** num = 999 + +**Output:** [40,25] + +**Constraints:** + +* `1 <= num <= 10^9` + +## Solution + +```kotlin +class Solution { + fun closestDivisors(num: Int): IntArray { + val sqrt1 = Math.sqrt(num + 1.0).toInt() + val sqrt2 = Math.sqrt(num + 2.0).toInt() + if (sqrt1 * sqrt1 == num + 1) { + return intArrayOf(sqrt1, sqrt1) + } + if (sqrt2 * sqrt2 == num + 2) { + return intArrayOf(sqrt2, sqrt2) + } + var ans1 = IntArray(2) + for (i in sqrt1 downTo 1) { + if ((num + 1) % i == 0) { + ans1 = intArrayOf(i, (num + 1) / i) + break + } + } + var ans2 = IntArray(2) + for (i in sqrt2 downTo 1) { + if ((num + 2) % i == 0) { + ans2 = intArrayOf(i, (num + 2) / i) + break + } + } + return if (Math.abs(ans2[0] - ans2[1]) < Math.abs(ans1[0] - ans1[1])) ans2 else ans1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1363_largest_multiple_of_three/readme.md b/src/main/kotlin/g1301_1400/s1363_largest_multiple_of_three/readme.md new file mode 100644 index 00000000..8487c60d --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1363_largest_multiple_of_three/readme.md @@ -0,0 +1,95 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1363\. Largest Multiple of Three + +Hard + +Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. + +Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros. + +**Example 1:** + +**Input:** digits = [8,1,9] + +**Output:** "981" + +**Example 2:** + +**Input:** digits = [8,6,7,1,0] + +**Output:** "8760" + +**Example 3:** + +**Input:** digits = [1] + +**Output:** "" + +**Constraints:** + +* 1 <= digits.length <= 104 +* `0 <= digits[i] <= 9` + +## Solution + +```kotlin +class Solution { + fun largestMultipleOfThree(digits: IntArray): String { + var sum = 0 + val count = IntArray(10) + // Here we are using the property that any no is divisible by 3 when its sum of digits is + // divisible by 3 + // get sum of digits and count of each digit + for (x in digits) { + sum += x + count[x]++ + } + val sb = StringBuilder() + var copied = count.copyOf(count.size) + // if sum % 3 != 0 then processing required + if (sum % 3 != 0) { + var rem = sum % 3 + var oldRem = rem + while (oldRem != 0) { + while (rem != 0) { + // if the remainder that we are trying to delete and its required digits is not + // present + // then the value will become -ve at that digit + copied[rem % 10]-- + // increase the remainder by 3 each time a -ve value is found + // and reset the rem and copied from orig count array and break + if (copied[rem % 10] < 0) { + oldRem += 3 + rem = oldRem + copied = count.copyOf(count.size) + break + } + rem /= 10 + if (rem == 0) { + oldRem = 0 + } + } + } + } + // generate the largest number by considering from the last digit ie 9,8,7,6... + for (i in 9 downTo 0) { + var `val` = copied[i] + while (`val` > 0) { + sb.append(i) + `val`-- + } + } + // check for any leading zeroes and remove + while (sb.length > 1) { + if (sb[0] != '0') { + break + } else { + sb.deleteCharAt(0) + } + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1365_how_many_numbers_are_smaller_than_the_current_number/readme.md b/src/main/kotlin/g1301_1400/s1365_how_many_numbers_are_smaller_than_the_current_number/readme.md new file mode 100644 index 00000000..4b6c5ccf --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1365_how_many_numbers_are_smaller_than_the_current_number/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1365\. How Many Numbers Are Smaller Than the Current Number + +Easy + +Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. + +Return the answer in an array. + +**Example 1:** + +**Input:** nums = [8,1,2,2,3] + +**Output:** [4,0,1,1,3] + +**Explanation:** + +For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). + +For nums[1]=1 does not exist any smaller number than it. + +For nums[2]=2 there exist one smaller number than it (1). + +For nums[3]=2 there exist one smaller number than it (1). + +For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). + +**Example 2:** + +**Input:** nums = [6,5,4,8] + +**Output:** [2,1,0,3] + +**Example 3:** + +**Input:** nums = [7,7,7,7] + +**Output:** [0,0,0,0] + +**Constraints:** + +* `2 <= nums.length <= 500` +* `0 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun smallerNumbersThanCurrent(nums: IntArray): IntArray { + val ans = IntArray(nums.size) + val temp = IntArray(101) + for (num in nums) { + temp[num]++ + } + for (i in 1..100) { + temp[i] += temp[i - 1] + } + for (i in ans.indices) { + if (nums[i] == 0) { + ans[i] = 0 + } else { + ans[i] = temp[nums[i] - 1] + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1366_rank_teams_by_votes/readme.md b/src/main/kotlin/g1301_1400/s1366_rank_teams_by_votes/readme.md new file mode 100644 index 00000000..d74c8d55 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1366_rank_teams_by_votes/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1366\. Rank Teams by Votes + +Medium + +In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. + +The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. + +Given an array of strings `votes` which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. + +Return _a string of all teams_ **sorted** by the ranking system. + +**Example 1:** + +**Input:** votes = ["ABC","ACB","ABC","ACB","ACB"] + +**Output:** "ACB" + +**Explanation:** Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team. + +Team B was ranked second by 2 voters and was ranked third by 3 voters. + +Team C was ranked second by 3 voters and was ranked third by 2 voters. + +As most of the voters ranked C second, team C is the second team and team B is the third. + +**Example 2:** + +**Input:** votes = ["WXYZ","XYZW"] + +**Output:** "XWYZ" + +**Explanation:** X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. + +**Example 3:** + +**Input:** votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"] + +**Output:** "ZMNAGUEDSJYLBOPHRQICWFXTVK" + +**Explanation:** Only one voter so his votes are used for the ranking. + +**Constraints:** + +* `1 <= votes.length <= 1000` +* `1 <= votes[i].length <= 26` +* `votes[i].length == votes[j].length` for `0 <= i, j < votes.length`. +* `votes[i][j]` is an English **uppercase** letter. +* All characters of `votes[i]` are unique. +* All the characters that occur in `votes[0]` **also occur** in `votes[j]` where `1 <= j < votes.length`. + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + internal class Node(var c: Char) { + var count = IntArray(26) + } + + fun rankTeams(votes: Array): String { + val nodes = arrayOfNulls(26) + for (i in 0..25) { + nodes[i] = Node((i + 'A'.code).toChar()) + } + for (vote in votes) { + for (i in 0 until vote.length) { + nodes[vote[i].code - 'A'.code]!!.count[i]++ + } + } + Arrays.sort( + nodes + ) { o1: Node?, o2: Node? -> + for (i in 0..25) { + if (o1!!.count[i] != o2!!.count[i]) { + return@sort o2.count[i] - o1.count[i] + } + } + o1!!.c.code - o2!!.c.code + } + val sb = StringBuilder() + for (i in 0 until votes[0].length) { + sb.append(nodes[i]!!.c) + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree/readme.md b/src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree/readme.md new file mode 100644 index 00000000..eed2ef44 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree/readme.md @@ -0,0 +1,97 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1367\. Linked List in Binary Tree + +Medium + +Given a binary tree `root` and a linked list with `head` as the first node. + +Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False. + +In this context downward path means a path that starts at some node and goes downwards. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/02/12/sample_1_1720.png)** + +**Input:** head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] + +**Output:** true + +**Explanation:** Nodes in blue form a subpath in the binary Tree. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2020/02/12/sample_2_1720.png)** + +**Input:** head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] + +**Output:** true + +**Example 3:** + +**Input:** head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] + +**Output:** false + +**Explanation:** There is no path in the binary tree that contains all the elements of the linked list from `head`. + +**Constraints:** + +* The number of nodes in the tree will be in the range `[1, 2500]`. +* The number of nodes in the list will be in the range `[1, 100]`. +* `1 <= Node.val <= 100` for each node in the linked list and binary tree. + +## Solution + +```kotlin +import com_github_leetcode.ListNode +import com_github_leetcode.TreeNode + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun isSubPath(head: ListNode?, root: TreeNode?): Boolean { + return if (root == null) { + false + } else ( + doesRootHaveList(head, root) || + isSubPath(head, root.left) || + isSubPath(head, root.right) + ) + } + + private fun doesRootHaveList(head: ListNode?, root: TreeNode?): Boolean { + if (head == null) { + return true + } + return if (root == null) { + false + } else ( + head.`val` == root.`val` && + ( + doesRootHaveList(head.next, root.left) || + doesRootHaveList(head.next, root.right) + ) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid/readme.md b/src/main/kotlin/g1301_1400/s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid/readme.md new file mode 100644 index 00000000..bc219df8 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid/readme.md @@ -0,0 +1,118 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1368\. Minimum Cost to Make at Least One Valid Path in a Grid + +Hard + +Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be: + +* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`) +* `2` which means go to the cell to the left. (i.e go from `grid[i][j]` to `grid[i][j - 1]`) +* `3` which means go to the lower cell. (i.e go from `grid[i][j]` to `grid[i + 1][j]`) +* `4` which means go to the upper cell. (i.e go from `grid[i][j]` to `grid[i - 1][j]`) + +Notice that there could be some signs on the cells of the grid that point outside the grid. + +You will initially start at the upper left cell `(0, 0)`. A valid path in the grid is a path that starts from the upper left cell `(0, 0)` and ends at the bottom-right cell `(m - 1, n - 1)` following the signs on the grid. The valid path does not have to be the shortest. + +You can modify the sign on a cell with `cost = 1`. You can modify the sign on a cell **one time only**. + +Return _the minimum cost to make the grid have at least one valid path_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/13/grid1.png) + +**Input:** grid = \[\[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] + +**Output:** 3 + +**Explanation:** You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/02/13/grid2.png) + +**Input:** grid = \[\[1,1,3],[3,2,2],[1,1,4]] + +**Output:** 0 + +**Explanation:** You can follow the path from (0, 0) to (2, 2). + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/02/13/grid3.png) + +**Input:** grid = \[\[1,2],[4,3]] + +**Output:** 1 + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 100` +* `1 <= grid[i][j] <= 4` + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Objects +import java.util.Queue + +@Suppress("NAME_SHADOWING") +class Solution { + private val dir = arrayOf( + intArrayOf(0, 0), intArrayOf(0, 1), + intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0) + ) + + fun minCost(grid: Array): Int { + val visited = Array(grid.size) { IntArray(grid[0].size) } + val queue: Queue = LinkedList() + addAllTheNodeInRange(0, 0, grid, queue, visited) + if (visited[grid.size - 1][grid[0].size - 1] == 1) { + return 0 + } + var cost = 0 + while (queue.isNotEmpty()) { + cost++ + val size = queue.size + for (i in 0 until size) { + val pa = queue.poll() + for (k in 1 until dir.size) { + val m = Objects.requireNonNull(pa).x + dir[k][0] + val n = pa.y + dir[k][1] + addAllTheNodeInRange(m, n, grid, queue, visited) + if (visited[grid.size - 1][grid[0].size - 1] == 1) { + return cost + } + } + } + } + return -1 + } + + private fun addAllTheNodeInRange( + x: Int, + y: Int, + grid: Array, + queue: Queue, + visited: Array + ) { + var x = x + var y = y + while (x >= 0 && x < visited.size && y >= 0 && y < visited[0].size && visited[x][y] == 0) { + queue.offer(Pair(x, y)) + visited[x][y]++ + val d = dir[grid[x][y]] + x += d[0] + y += d[1] + } + } + + private class Pair(var x: Int, var y: Int) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1370_increasing_decreasing_string/readme.md b/src/main/kotlin/g1301_1400/s1370_increasing_decreasing_string/readme.md new file mode 100644 index 00000000..8fc261f5 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1370_increasing_decreasing_string/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1370\. Increasing Decreasing String + +Easy + +You are given a string `s`. Reorder the string using the following algorithm: + +1. Pick the **smallest** character from `s` and **append** it to the result. +2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. +3. Repeat step 2 until you cannot pick more characters. +4. Pick the **largest** character from `s` and **append** it to the result. +5. Pick the **largest** character from `s` which is smaller than the last appended character to the result and **append** it. +6. Repeat step 5 until you cannot pick more characters. +7. Repeat the steps from 1 to 6 until you pick all characters from `s`. + +In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result. + +Return _the result string after sorting_ `s` _with this algorithm_. + +**Example 1:** + +**Input:** s = "aaaabbbbcccc" + +**Output:** "abccbaabccba" + +**Explanation:** After steps 1, 2 and 3 of the first iteration, result = "abc" + +After steps 4, 5 and 6 of the first iteration, result = "abccba" + +First iteration is done. Now s = "aabbcc" and we go back to step 1 + +After steps 1, 2 and 3 of the second iteration, result = "abccbaabc" + +After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba" + +**Example 2:** + +**Input:** s = "rat" + +**Output:** "art" + +**Explanation:** The word "rat" becomes "art" after re-ordering it with the mentioned algorithm. + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun sortString(s: String): String { + val count = IntArray(26) + for (c in s.toCharArray()) { + count[c.code - 'a'.code]++ + } + val sb = StringBuilder() + while (sb.length < s.length) { + for (i in count.indices) { + if (count[i] != 0) { + val character = (i + 'a'.code).toChar() + sb.append(character) + count[i]-- + } + } + for (i in 25 downTo 0) { + if (count[i] > 0) { + val character = (i + 'a'.code).toChar() + sb.append(character) + count[i]-- + } + } + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1371_find_the_longest_substring_containing_vowels_in_even_counts/readme.md b/src/main/kotlin/g1301_1400/s1371_find_the_longest_substring_containing_vowels_in_even_counts/readme.md new file mode 100644 index 00000000..2b9bee8b --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1371_find_the_longest_substring_containing_vowels_in_even_counts/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1371\. Find the Longest Substring Containing Vowels in Even Counts + +Medium + +Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. + +**Example 1:** + +**Input:** s = "eleetminicoworoep" + +**Output:** 13 + +**Explanation:** The longest substring is "leetminicowor" which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**. + +**Example 2:** + +**Input:** s = "leetcodeisgreat" + +**Output:** 5 + +**Explanation:** The longest substring is "leetc" which contains two e's. + +**Example 3:** + +**Input:** s = "bcbcbc" + +**Output:** 6 + +**Explanation:** In this case, the given string "bcbcbc" is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times. + +**Constraints:** + +* `1 <= s.length <= 5 x 10^5` +* `s` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + private var result: Int? = null + + fun findTheLongestSubstring(s: String): Int { + val arr = IntArray(s.length) + var sum = 0 + val set: Set = HashSet(mutableListOf('a', 'e', 'i', 'o', 'u')) + for (i in 0 until s.length) { + val c = s[i] + if (set.contains(c)) { + sum = if (sum and (1 shl 'a'.code - c.code) == 0) sum or (1 shl 'a'.code - c.code) else + sum and (1 shl 'a'.code - c.code).inv() + } + arr[i] = sum + } + for (i in 0 until s.length) { + if (result != null && result!! > s.length - i) { + break + } + for (j in s.length - 1 downTo i) { + val e = arr[j] + val k = if (i - 1 < 0) 0 else arr[i - 1] + val m = e xor k + if (m == 0) { + result = if (result == null) j - i + 1 else Math.max(result!!, j - i + 1) + break + } + } + } + return if (result == null) 0 else result!! + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1372_longest_zigzag_path_in_a_binary_tree/readme.md b/src/main/kotlin/g1301_1400/s1372_longest_zigzag_path_in_a_binary_tree/readme.md new file mode 100644 index 00000000..75e252bf --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1372_longest_zigzag_path_in_a_binary_tree/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1372\. Longest ZigZag Path in a Binary Tree + +Medium + +You are given the `root` of a binary tree. + +A ZigZag path for a binary tree is defined as follow: + +* Choose **any** node in the binary tree and a direction (right or left). +* If the current direction is right, move to the right child of the current node; otherwise, move to the left child. +* Change the direction from right to left or from left to right. +* Repeat the second and third steps until you can't move in the tree. + +Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). + +Return _the longest **ZigZag** path contained in that tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png) + +**Input:** root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] + +**Output:** 3 + +**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png) + +**Input:** root = [1,1,1,null,1,null,null,1,1,null,1] + +**Output:** 4 + +**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right). + +**Example 3:** + +**Input:** root = [1] + +**Output:** 0 + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 5 * 104]. +* `1 <= Node.val <= 100` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var maxLength = 0 + + fun longestZigZag(root: TreeNode?): Int { + dfs(root, true) + return maxLength + } + + private fun dfs(root: TreeNode?, isLeft: Boolean): Int { + if (root == null) { + return 0 + } + val left = dfs(root.left, false) + val right = dfs(root.right, true) + maxLength = Math.max(maxLength, left) + maxLength = Math.max(maxLength, right) + return 1 + if (isLeft) left else right + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1373_maximum_sum_bst_in_binary_tree/readme.md b/src/main/kotlin/g1301_1400/s1373_maximum_sum_bst_in_binary_tree/readme.md new file mode 100644 index 00000000..e3bd6e27 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1373_maximum_sum_bst_in_binary_tree/readme.md @@ -0,0 +1,100 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1373\. Maximum Sum BST in Binary Tree + +Hard + +Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_. + +Assume a BST is defined as follows: + +* The left subtree of a node contains only nodes with keys **less than** the node's key. +* The right subtree of a node contains only nodes with keys **greater than** the node's key. +* Both the left and right subtrees must also be binary search trees. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png) + +**Input:** root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] + +**Output:** 20 + +**Explanation:** Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png) + +**Input:** root = [4,3,null,1,2] + +**Output:** 2 + +**Explanation:** Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. + +**Example 3:** + +**Input:** root = [-4,-2,-5] + +**Output:** 0 + +**Explanation:** All values are negatives. Return an empty BST. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 4 * 104]. +* -4 * 104 <= Node.val <= 4 * 104 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun maxSumBST(root: TreeNode?): Int { + val temp = checkBST(root) + return Math.max(temp.maxSum, 0) + } + + private class IsBST { + var max = Int.MIN_VALUE + var min = Int.MAX_VALUE + var isBst = true + var sum = 0 + var maxSum = Int.MIN_VALUE + } + + private fun checkBST(root: TreeNode?): IsBST { + if (root == null) { + return IsBST() + } + val lp = checkBST(root.left) + val rp = checkBST(root.right) + val mp = IsBST() + mp.max = Math.max(root.`val`, Math.max(lp.max, rp.max)) + mp.min = Math.min(root.`val`, Math.min(lp.min, rp.min)) + mp.sum = lp.sum + rp.sum + root.`val` + val check = root.`val` > lp.max && root.`val` < rp.min + if (lp.isBst && rp.isBst && check) { + mp.isBst = true + val tempMax = Math.max(mp.sum, Math.max(lp.sum, rp.sum)) + mp.maxSum = Math.max(tempMax, Math.max(lp.maxSum, rp.maxSum)) + } else { + mp.isBst = false + mp.maxSum = Math.max(lp.maxSum, rp.maxSum) + } + return mp + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1374_generate_a_string_with_characters_that_have_odd_counts/readme.md b/src/main/kotlin/g1301_1400/s1374_generate_a_string_with_characters_that_have_odd_counts/readme.md new file mode 100644 index 00000000..3ab73fe6 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1374_generate_a_string_with_characters_that_have_odd_counts/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1374\. Generate a String With Characters That Have Odd Counts + +Easy + +Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_. + +The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them. + +**Example 1:** + +**Input:** n = 4 + +**Output:** "pppz" + +**Explanation:** "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". + +**Example 2:** + +**Input:** n = 2 + +**Output:** "xy" + +**Explanation:** "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". + +**Example 3:** + +**Input:** n = 7 + +**Output:** "holasss" + +**Constraints:** + +* `1 <= n <= 500` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun generateTheString(n: Int): String { + var n = n + val sb = StringBuilder() + if (n > 1 && n % 2 == 0) { + while (n-- > 1) { + sb.append("a") + } + } else if (n > 1) { + while (n-- > 2) { + sb.append("a") + } + sb.append("b") + } + sb.append("z") + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1375_number_of_times_binary_string_is_prefix_aligned/readme.md b/src/main/kotlin/g1301_1400/s1375_number_of_times_binary_string_is_prefix_aligned/readme.md new file mode 100644 index 00000000..0317be6d --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1375_number_of_times_binary_string_is_prefix_aligned/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1375\. Number of Times Binary String Is Prefix-Aligned + +Medium + +You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the ith step. + +A binary string is **prefix-aligned** if, after the ith step, all the bits in the **inclusive** range `[1, i]` are ones and all the other bits are zeros. + +Return _the number of times the binary string is **prefix-aligned** during the flipping process_. + +**Example 1:** + +**Input:** flips = [3,2,4,1,5] + +**Output:** 2 + +**Explanation:** The binary string is initially "00000". + +After applying step 1: The string becomes "00100", which is not prefix-aligned. + +After applying step 2: The string becomes "01100", which is not prefix-aligned. + +After applying step 3: The string becomes "01110", which is not prefix-aligned. + +After applying step 4: The string becomes "11110", which is prefix-aligned. + +After applying step 5: The string becomes "11111", which is prefix-aligned. + +We can see that the string was prefix-aligned 2 times, so we return 2. + +**Example 2:** + +**Input:** flips = [4,1,2,3] + +**Output:** 1 + +**Explanation:** The binary string is initially "0000". + +After applying step 1: The string becomes "0001", which is not prefix-aligned. + +After applying step 2: The string becomes "1001", which is not prefix-aligned. + +After applying step 3: The string becomes "1101", which is not prefix-aligned. + +After applying step 4: The string becomes "1111", which is prefix-aligned. + +We can see that the string was prefix-aligned 1 time, so we return 1. + +**Constraints:** + +* `n == flips.length` +* 1 <= n <= 5 * 104 +* `flips` is a permutation of the integers in the range `[1, n]`. + +## Solution + +```kotlin +class Solution { + fun numTimesAllBlue(flips: IntArray): Int { + var ans = 0 + var max = 0 + for (i in flips.indices) { + max = Math.max(max, flips[i]) + if (max == i + 1) { + ++ans + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees/readme.md b/src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees/readme.md new file mode 100644 index 00000000..abb5e5be --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1376\. Time Needed to Inform All Employees + +Medium + +A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`. + +Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that the subordination relationships have a tree structure. + +The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. + +The `i-th` employee needs `informTime[i]` minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). + +Return _the number of minutes_ needed to inform all the employees about the urgent news. + +**Example 1:** + +**Input:** n = 1, headID = 0, manager = [-1], informTime = [0] + +**Output:** 0 + +**Explanation:** The head of the company is the only employee in the company. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/02/27/graph.png) + +**Input:** n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] + +**Output:** 1 + +**Explanation:** The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. + +The tree structure of the employees in the company is shown. + +**Constraints:** + +* 1 <= n <= 105 +* `0 <= headID < n` +* `manager.length == n` +* `0 <= manager[i] < n` +* `manager[headID] == -1` +* `informTime.length == n` +* `0 <= informTime[i] <= 1000` +* `informTime[i] == 0` if employee `i` has no subordinates. +* It is **guaranteed** that all the employees can be informed. + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Queue + +@Suppress("UNUSED_PARAMETER") +class Solution { + private class Pair(var emp: Int, var time: Int) + + fun numOfMinutes(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int { + val map = HashMap>() + var head = -1 + for (i in manager.indices) { + if (manager[i] == -1) { + head = i + continue + } + val man = manager[i] + map.putIfAbsent(man, ArrayList()) + map[man]!!.add(i) + } + var maxtime = 0 + val que: Queue = ArrayDeque() + que.add(Pair(head, informTime[head])) + while (que.isNotEmpty()) { + val rem = que.remove() + maxtime = Math.max(rem.time, maxtime) + if (map.containsKey(rem.emp)) { + for (under in map[rem.emp]!!) { + que.add(Pair(under, rem.time + informTime[under])) + } + } + } + return maxtime + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1377_frog_position_after_t_seconds/readme.md b/src/main/kotlin/g1301_1400/s1377_frog_position_after_t_seconds/readme.md new file mode 100644 index 00000000..41a027b2 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1377_frog_position_after_t_seconds/readme.md @@ -0,0 +1,91 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1377\. Frog Position After T Seconds + +Hard + +Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. + +The edges of the undirected tree are given in the array `edges`, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. + +_Return the probability that after `t` seconds the frog is on the vertex `target`._ Answers within 10-5 of the actual answer will be accepted. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/12/21/frog1.jpg) + +**Input:** n = 7, edges = \[\[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 + +**Output:** 0.16666666666666666 + +**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after **second 1** and then jumping with 1/2 probability to vertex 4 after **second 2**. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 \* 1/2 = 1/6 = 0.16666666666666666. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/12/21/frog2.jpg)** + +**Input:** n = 7, edges = \[\[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 + +**Output:** 0.3333333333333333 + +**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after **second 1**. + +**Constraints:** + +* `1 <= n <= 100` +* `edges.length == n - 1` +* `edges[i].length == 2` +* 1 <= ai, bi <= n +* `1 <= t <= 50` +* `1 <= target <= n` + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +@Suppress("NAME_SHADOWING") +class Solution { + fun frogPosition(n: Int, edges: Array, t: Int, target: Int): Double { + var t = t + val graph: Array?> = arrayOfNulls(n) + for (i in 0 until n) { + graph[i] = ArrayList() + } + for (edge in edges) { + graph[edge[0] - 1]?.add(edge[1] - 1) + graph[edge[1] - 1]?.add(edge[0] - 1) + } + val visited = BooleanArray(n) + visited[0] = true + val probabilities = DoubleArray(n) + probabilities[0] = 1.0 + val queue: Queue = LinkedList() + queue.offer(0) + while (queue.isNotEmpty() && t-- > 0) { + for (i in queue.size downTo 1) { + val vertex = queue.poll() + var nextVerticesCount = 0 + for (next in graph[vertex]!!) { + if (!visited[next]) { + nextVerticesCount++ + } + } + for (next in graph[vertex]!!) { + if (!visited[next] && nextVerticesCount > 0) { + visited[next] = true + queue.offer(next) + probabilities[next] = probabilities[vertex] / nextVerticesCount + } + } + if (nextVerticesCount > 0) { + probabilities[vertex] = 0.0 + } + } + } + return probabilities[target - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1379_find_a_corresponding_node_of_a_binary_tree_in_a_clone_of_that_tree/readme.md b/src/main/kotlin/g1301_1400/s1379_find_a_corresponding_node_of_a_binary_tree_in_a_clone_of_that_tree/readme.md new file mode 100644 index 00000000..7d2db575 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1379_find_a_corresponding_node_of_a_binary_tree_in_a_clone_of_that_tree/readme.md @@ -0,0 +1,82 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1379\. Find a Corresponding Node of a Binary Tree in a Clone of That Tree + +Medium + +Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. + +The `cloned` tree is a **copy of** the `original` tree. + +Return _a reference to the same node_ in the `cloned` tree. + +**Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/21/e1.png) + +**Input:** tree = [7,4,3,null,null,6,19], target = 3 + +**Output:** 3 + +**Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/02/21/e2.png) + +**Input:** tree = [7], target = 7 + +**Output:** 7 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/02/21/e3.png) + +**Input:** tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4 + +**Output:** 4 + +**Constraints:** + +* The number of nodes in the `tree` is in the range [1, 104]. +* The values of the nodes of the `tree` are unique. +* `target` node is a node from the `original` tree and is not `null`. + +**Follow up:** Could you solve the problem if repeated values on the tree are allowed? + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + fun getTargetCopy( + original: TreeNode?, + cloned: TreeNode?, + target: TreeNode + ): TreeNode? { + if (original == null) { + return null + } + if (original.`val` == target.`val`) { + return cloned + } + val left = getTargetCopy(original.left, cloned!!.left, target) + return if (left != null && left.`val` == target.`val`) { + left + } else getTargetCopy(original.right, cloned.right, target) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1380_lucky_numbers_in_a_matrix/readme.md b/src/main/kotlin/g1301_1400/s1380_lucky_numbers_in_a_matrix/readme.md new file mode 100644 index 00000000..a592c708 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1380_lucky_numbers_in_a_matrix/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1380\. Lucky Numbers in a Matrix + +Easy + +Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. + +A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. + +**Example 1:** + +**Input:** matrix = \[\[3,7,8],[9,11,13],[15,16,17]] + +**Output:** [15] + +**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column. + +**Example 2:** + +**Input:** matrix = \[\[1,10,4,2],[9,3,8,7],[15,16,17,12]] + +**Output:** [12] + +**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column. + +**Example 3:** + +**Input:** matrix = \[\[7,8],[1,2]] + +**Output:** [7] + +**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column. + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= n, m <= 50` +* 1 <= matrix[i][j] <= 105. +* All elements in the matrix are distinct. + +## Solution + +```kotlin +class Solution { + fun luckyNumbers(matrix: Array): List { + val mini: MutableList = ArrayList() + val maxi: MutableList = ArrayList() + for (arr in matrix) { + var min = Int.MAX_VALUE + for (j in arr) { + if (min > j) { + min = j + } + } + mini.add(min) + } + val cols = matrix[0].size + for (c in 0 until cols) { + var max = Int.MIN_VALUE + for (ints in matrix) { + if (ints[c] > max) { + max = ints[c] + } + } + maxi.add(max) + } + val res: MutableList = ArrayList() + for (value in mini) { + if (maxi.contains(value)) { + res.add(value) + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1381_design_a_stack_with_increment_operation/readme.md b/src/main/kotlin/g1301_1400/s1381_design_a_stack_with_increment_operation/readme.md new file mode 100644 index 00000000..461d4b1c --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1381_design_a_stack_with_increment_operation/readme.md @@ -0,0 +1,99 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1381\. Design a Stack With Increment Operation + +Medium + +Design a stack which supports the following operations. + +Implement the `CustomStack` class: + +* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack or do nothing if the stack reached the `maxSize`. +* `void push(int x)` Adds `x` to the top of the stack if the stack hasn't reached the `maxSize`. +* `int pop()` Pops and returns the top of stack or **\-1** if the stack is empty. +* `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, just increment all the elements in the stack. + +**Example 1:** + +**Input** + +["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] + +[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] + +**Output:** [null,null,null,2,null,null,null,null,null,103,202,201,-1] + +**Explanation:** + + CustomStack customStack = new CustomStack(3); // Stack is Empty [] + customStack.push(1); // stack becomes [1] + customStack.push(2); // stack becomes [1, 2] + customStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1] + customStack.push(2); // stack becomes [1, 2] + customStack.push(3); // stack becomes [1, 2, 3] + customStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4 + customStack.increment(5, 100); // stack becomes [101, 102, 103] + customStack.increment(2, 100); // stack becomes [201, 202, 103] + customStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202] + customStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201] + customStack.pop(); // return 201 --> Return top of the stack 101, stack becomes [] + customStack.pop(); // return -1 --> Stack is empty return -1. + +**Constraints:** + +* `1 <= maxSize <= 1000` +* `1 <= x <= 1000` +* `1 <= k <= 1000` +* `0 <= val <= 100` +* At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately. + +## Solution + +```kotlin +class CustomStack(private val maxSize: Int) { + private var top = 0 + private val stack: IntArray + + init { + stack = IntArray(maxSize) + } + + fun push(x: Int) { + if (top == maxSize) { + return + } + stack[top] = x + top++ + } + + fun pop(): Int { + if (top == 0) { + return -1 + } + val popValue = stack[top - 1] + stack[top - 1] = 0 + top-- + return popValue + } + + fun increment(k: Int, `val`: Int) { + if (top == 0 || k == 0) { + return + } + for (i in 0 until k) { + if (i == top) { + break + } + stack[i] += `val` + } + } +} +/* + * Your CustomStack object will be instantiated and called as such: + * var obj = CustomStack(maxSize) + * obj.push(x) + * var param_2 = obj.pop() + * obj.increment(k,`val`) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1382_balance_a_binary_search_tree/readme.md b/src/main/kotlin/g1301_1400/s1382_balance_a_binary_search_tree/readme.md new file mode 100644 index 00000000..4c8d39db --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1382_balance_a_binary_search_tree/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1382\. Balance a Binary Search Tree + +Medium + +Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**. + +A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/10/balance1-tree.jpg) + +**Input:** root = [1,null,2,null,3,null,4,null,null] + +**Output:** [2,1,3,null,null,null,4] + +**Explanation:** This is not the only correct answer, [3,1,4,null,2] is also correct. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/10/balanced2-tree.jpg) + +**Input:** root = [2,1,3] + +**Output:** [2,1,3] + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* 1 <= Node.val <= 105 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun balanceBST(root: TreeNode?): TreeNode? { + val inorder = inorder(root, ArrayList()) + return dfs(inorder, 0, inorder.size - 1) + } + + private fun inorder(root: TreeNode?, list: MutableList): List { + if (root == null) { + return list + } + inorder(root.left, list) + list.add(root.`val`) + return inorder(root.right, list) + } + + private fun dfs(nums: List, start: Int, end: Int): TreeNode? { + if (end < start) { + return null + } + val mid = (start + end) / 2 + val root = TreeNode(nums[mid]) + root.left = dfs(nums, start, mid - 1) + root.right = dfs(nums, mid + 1, end) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1383_maximum_performance_of_a_team/readme.md b/src/main/kotlin/g1301_1400/s1383_maximum_performance_of_a_team/readme.md new file mode 100644 index 00000000..2acec6a5 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1383_maximum_performance_of_a_team/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1383\. Maximum Performance of a Team + +Hard + +You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the ith engineer respectively. + +Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**. + +The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. + +Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 + +**Output:** 60 + +**Explanation:** + +We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60. + +**Example 2:** + +**Input:** n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 + +**Output:** 68 + +**Explanation:** + +This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68. + +**Example 3:** + +**Input:** n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 + +**Output:** 72 + +**Constraints:** + +* 1 <= k <= n <= 105 +* `speed.length == n` +* `efficiency.length == n` +* 1 <= speed[i] <= 105 +* 1 <= efficiency[i] <= 108 + +## Solution + +```kotlin +import java.util.Arrays +import java.util.PriorityQueue + +class Solution { + fun maxPerformance(n: Int, speed: IntArray, efficiency: IntArray, k: Int): Int { + val engineers = Array(n) { IntArray(2) } + for (i in 0 until n) { + engineers[i][0] = speed[i] + engineers[i][1] = efficiency[i] + } + Arrays.sort(engineers) { engineer1: IntArray, engineer2: IntArray -> engineer2[1] - engineer1[1] } + var speedSum: Long = 0 + var maximumPerformance: Long = 0 + val minHeap = PriorityQueue() + for (engineer in engineers) { + if (minHeap.size == k) { + speedSum -= minHeap.poll().toLong() + } + speedSum += engineer[0].toLong() + minHeap.offer(engineer[0]) + maximumPerformance = Math.max(maximumPerformance, speedSum * engineer[1]) + } + return (maximumPerformance % 1000000007).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1385_find_the_distance_value_between_two_arrays/readme.md b/src/main/kotlin/g1301_1400/s1385_find_the_distance_value_between_two_arrays/readme.md new file mode 100644 index 00000000..c7f7de3f --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1385_find_the_distance_value_between_two_arrays/readme.md @@ -0,0 +1,89 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1385\. Find the Distance Value Between Two Arrays + +Easy + +Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_. + +The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`. + +**Example 1:** + +**Input:** arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 + +**Output:** 2 + +**Explanation:** + +For arr1[0]=4 we have: + +\|4-10\|=6 > d=2 + +\|4-9\|=5 > d=2 + +\|4-1\|=3 > d=2 + +\|4-8\|=4 > d=2 + +For arr1[1]=5 we have: + +\|5-10\|=5 > d=2 + +\|5-9\|=4 > d=2 + +\|5-1\|=4 > d=2 + +\|5-8\|=3 > d=2 + +For arr1[2]=8 we have: + +**\|8-10\|=2 <= d=2** + +**\|8-9\|=1 <= d=2** + +\|8-1\|=7 > d=2 + +**\|8-8\|=0 <= d=2** + +**Example 2:** + +**Input:** arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3 + +**Output:** 2 + +**Example 3:** + +**Input:** arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6 + +**Output:** 1 + +**Constraints:** + +* `1 <= arr1.length, arr2.length <= 500` +* `-1000 <= arr1[i], arr2[j] <= 1000` +* `0 <= d <= 100` + +## Solution + +```kotlin +class Solution { + fun findTheDistanceValue(arr1: IntArray, arr2: IntArray, d: Int): Int { + var count = 0 + for (k in arr1) { + var j = 0 + while (j < arr2.size) { + if (Math.abs(k - arr2[j]) <= d) { + break + } + j++ + } + if (j == arr2.size) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1386_cinema_seat_allocation/readme.md b/src/main/kotlin/g1301_1400/s1386_cinema_seat_allocation/readme.md new file mode 100644 index 00000000..efa0cfb4 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1386_cinema_seat_allocation/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1386\. Cinema Seat Allocation + +Medium + +![](https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_1.png) + +A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. + +Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved. + +_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_3.png) + +**Input:** n = 3, reservedSeats = \[\[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]] + +**Output:** 4 + +**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group. + +**Example 2:** + +**Input:** n = 2, reservedSeats = \[\[2,1],[1,8],[2,6]] + +**Output:** 2 + +**Example 3:** + +**Input:** n = 4, reservedSeats = \[\[4,3],[1,4],[4,6],[1,7]] + +**Output:** 4 + +**Constraints:** + +* `1 <= n <= 10^9` +* `1 <= reservedSeats.length <= min(10*n, 10^4)` +* `reservedSeats[i].length == 2` +* `1 <= reservedSeats[i][0] <= n` +* `1 <= reservedSeats[i][1] <= 10` +* All `reservedSeats[i]` are distinct. + +## Solution + +```kotlin +class Solution { + fun maxNumberOfFamilies(n: Int, reservedSeats: Array): Int { + val occupiedFamilySeats: MutableMap = HashMap() + for (reservedSeat in reservedSeats) { + val row = reservedSeat[0] + val col = reservedSeat[1] + if (col == 1 || col == 10) { + continue + } + val rowFamilySeats = occupiedFamilySeats.getOrDefault(row, IntArray(3)) + if (col == 2 || col == 3) { + // mark left family seating as occupied + rowFamilySeats[0] = 1 + occupiedFamilySeats[row] = rowFamilySeats + } + if (col == 8 || col == 9) { + // mark right family seating as occupied + rowFamilySeats[2] = 1 + occupiedFamilySeats[row] = rowFamilySeats + } + if (col == 4 || col == 5) { + // mark left family seating as occupied + rowFamilySeats[0] = 1 + // mark min family seating as occupied + rowFamilySeats[1] = 1 + occupiedFamilySeats[row] = rowFamilySeats + } + if (col == 6 || col == 7) { + // mark min family seating as occupied + rowFamilySeats[1] = 1 + // mark right family seating as occupied + rowFamilySeats[2] = 1 + occupiedFamilySeats[row] = rowFamilySeats + } + } + // max number of family seats per row is 2, so we start that minus the rows for which we + // have reservations + var count = n * 2 - 2 * occupiedFamilySeats.size + // for each row with reservations, count remaining family seatings + for (familySeats in occupiedFamilySeats.values) { + if (familySeats[0] == 0) { + count++ + } + if (familySeats[2] == 0) { + count++ + } + if (familySeats[0] != 0 && familySeats[2] != 0 && familySeats[1] == 0) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1387_sort_integers_by_the_power_value/readme.md b/src/main/kotlin/g1301_1400/s1387_sort_integers_by_the_power_value/readme.md new file mode 100644 index 00000000..00fd7d05 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1387_sort_integers_by_the_power_value/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1387\. Sort Integers by The Power Value + +Medium + +The power of an integer `x` is defined as the number of steps needed to transform `x` into `1` using the following steps: + +* if `x` is even then `x = x / 2` +* if `x` is odd then `x = 3 * x + 1` + +For example, the power of `x = 3` is `7` because `3` needs `7` steps to become `1` (`3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1`). + +Given three integers `lo`, `hi` and `k`. The task is to sort all integers in the interval `[lo, hi]` by the power value in **ascending order**, if two or more integers have **the same** power value sort them by **ascending order**. + +Return the kth integer in the range `[lo, hi]` sorted by the power value. + +Notice that for any integer `x` `(lo <= x <= hi)` it is **guaranteed** that `x` will transform into `1` using these steps and that the power of `x` is will **fit** in a 32-bit signed integer. + +**Example 1:** + +**Input:** lo = 12, hi = 15, k = 2 + +**Output:** 13 + +**Explanation:** The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) + +The power of 13 is 9 + +The power of 14 is 17 + +The power of 15 is 17 + +The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. + +Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. + +**Example 2:** + +**Input:** lo = 7, hi = 11, k = 4 + +**Output:** 7 + +**Explanation:** The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. + +The interval sorted by power is [8, 10, 11, 7, 9]. + +The fourth number in the sorted array is 7. + +**Constraints:** + +* `1 <= lo <= hi <= 1000` +* `1 <= k <= hi - lo + 1` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + private lateinit var cacheMap: MutableMap + + fun getKth(lo: Int, hi: Int, k: Int): Int { + cacheMap = HashMap() + cacheMap[1] = 0 + val arr = Array(hi - lo + 1) { IntArray(2) } + for (i in arr.indices) { + arr[i][0] = lo + i + arr[i][1] = getStepCount(lo + i) + } + Arrays.sort(arr) { a: IntArray, b: IntArray -> a[1].compareTo(b[1]) } + return arr[k - 1][0] + } + + private fun getStepCount(`val`: Int): Int { + if (cacheMap.containsKey(`val`)) { + return cacheMap[`val`]!! + } + val step: Int = if (`val` % 2 == 0) { + // even + 1 + getStepCount(`val` / 2) + } else { + 1 + getStepCount(3 * `val` + 1) + } + cacheMap[`val`] = step + return step + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1388_pizza_with_3n_slices/readme.md b/src/main/kotlin/g1301_1400/s1388_pizza_with_3n_slices/readme.md new file mode 100644 index 00000000..3b9e7b2e --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1388_pizza_with_3n_slices/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1388\. Pizza With 3n Slices + +Hard + +There is a pizza with `3n` slices of varying size, you and your friends will take slices of pizza as follows: + +* You will pick **any** pizza slice. +* Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. +* Your friend Bob will pick the next slice in the clockwise direction of your pick. +* Repeat until there are no more slices of pizzas. + +Given an integer array `slices` that represent the sizes of the pizza slices in a clockwise direction, return _the maximum possible sum of slice sizes that you can pick_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/18/sample_3_1723.png) + +**Input:** slices = [1,2,3,4,5,6] + +**Output:** 10 + +**Explanation:** Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/02/18/sample_4_1723.png) + +**Input:** slices = [8,9,8,6,1,1] + +**Output:** 16 + +**Explanation:** Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. + +**Constraints:** + +* `3 * n == slices.length` +* `1 <= slices.length <= 500` +* `1 <= slices[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maxSizeSlices(slices: IntArray): Int { + val n = slices.size + val third = n / 3 + return Math.max( + maxSizeSlices(slices, 0, n - 2, third), maxSizeSlices(slices, 1, n - 1, third) + ) + } + + private fun maxSizeSlices(slices: IntArray, start: Int, end: Int, parts: Int): Int { + val dp = IntArray(slices.size) + var res = 0 + for (i in 0 until parts) { + var prev = 0 + var prevPrev = 0 + for (j in end downTo start) { + val curr = dp[j] + dp[j] = slices[j] + prevPrev + prevPrev = prev + prev = Math.max(curr, prev) + res = Math.max(res, dp[j]) + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1389_create_target_array_in_the_given_order/readme.md b/src/main/kotlin/g1301_1400/s1389_create_target_array_in_the_given_order/readme.md new file mode 100644 index 00000000..fded2db7 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1389_create_target_array_in_the_given_order/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1389\. Create Target Array in the Given Order + +Easy + +Given two arrays of integers `nums` and `index`. Your task is to create _target_ array under the following rules: + +* Initially _target_ array is empty. +* From left to right read nums[i] and index[i], insert at index `index[i]` the value `nums[i]` in _target_ array. +* Repeat the previous step until there are no elements to read in `nums` and `index.` + +Return the _target_ array. + +It is guaranteed that the insertion operations will be valid. + +**Example 1:** + +**Input:** nums = [0,1,2,3,4], index = [0,1,2,2,1] + +**Output:** [0,4,1,3,2] + +**Explanation:** + + nums index target + 0 0 [0] + 1 1 [0,1] + 2 2 [0,1,2] + 3 2 [0,1,3,2] + 4 1 [0,4,1,3,2] + +**Example 2:** + +**Input:** nums = [1,2,3,4,0], index = [0,1,2,3,0] + +**Output:** [0,1,2,3,4] + +**Explanation:** + + nums index target + 1 0 [1] + 2 1 [1,2] + 3 2 [1,2,3] + 4 3 [1,2,3,4] + 0 0 [0,1,2,3,4] + +**Example 3:** + +**Input:** nums = [1], index = [0] + +**Output:** [1] + +**Constraints:** + +* `1 <= nums.length, index.length <= 100` +* `nums.length == index.length` +* `0 <= nums[i] <= 100` +* `0 <= index[i] <= i` + +## Solution + +```kotlin +class Solution { + fun createTargetArray(nums: IntArray, index: IntArray): IntArray { + val list: MutableList = ArrayList() + for (i in nums.indices) { + list.add(index[i], nums[i]) + } + val target = IntArray(list.size) + for (i in target.indices) { + target[i] = list[i] + } + return target + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1390_four_divisors/readme.md b/src/main/kotlin/g1301_1400/s1390_four_divisors/readme.md new file mode 100644 index 00000000..aa7d09ba --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1390_four_divisors/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1390\. Four Divisors + +Medium + +Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`. + +**Example 1:** + +**Input:** nums = [21,4,7] + +**Output:** 32 + +**Explanation:** + +21 has 4 divisors: 1, 3, 7, 21 + +4 has 3 divisors: 1, 2, 4 + +7 has 2 divisors: 1, 7 + +The answer is the sum of divisors of 21 only. + +**Example 2:** + +**Input:** nums = [21,21] + +**Output:** 64 + +**Example 3:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** 0 + +**Constraints:** + +* 1 <= nums.length <= 104 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun sumFourDivisors(nums: IntArray): Int { + var sum = 0 + for (num in nums) { + val sqrt = Math.sqrt(num.toDouble()).toInt() + if (sqrt * sqrt == num) { + continue + } + var tmpSum = num + 1 + var count = 0 + for (i in 2..sqrt) { + if (num % i == 0) { + count++ + tmpSum += i + num / i + } + if (count > 1) { + break + } + } + if (count == 1) { + sum += tmpSum + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md b/src/main/kotlin/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md new file mode 100644 index 00000000..3e7e9e22 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md @@ -0,0 +1,114 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1391\. Check if There is a Valid Path in a Grid + +Medium + +You are given an `m x n` `grid`. Each cell of `grid` represents a street. The street of `grid[i][j]` can be: + +* `1` which means a street connecting the left cell and the right cell. +* `2` which means a street connecting the upper cell and the lower cell. +* `3` which means a street connecting the left cell and the lower cell. +* `4` which means a street connecting the right cell and the lower cell. +* `5` which means a street connecting the left cell and the upper cell. +* `6` which means a street connecting the right cell and the upper cell. + +![](https://assets.leetcode.com/uploads/2020/03/05/main.png) + +You will initially start at the street of the upper-left cell `(0, 0)`. A valid path in the grid is a path that starts from the upper left cell `(0, 0)` and ends at the bottom-right cell `(m - 1, n - 1)`. **The path should only follow the streets**. + +**Notice** that you are **not allowed** to change any street. + +Return `true` _if there is a valid path in the grid or_ `false` _otherwise_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/03/05/e1.png) + +**Input:** grid = \[\[2,4,3],[6,5,2]] + +**Output:** true + +**Explanation:** As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/03/05/e2.png) + +**Input:** grid = \[\[1,2,1],[1,2,1]] + +**Output:** false + +**Explanation:** As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0) + +**Example 3:** + +**Input:** grid = \[\[1,1,2]] + +**Output:** false + +**Explanation:** You will get stuck at cell (0, 1) and you cannot reach cell (0, 2). + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 300` +* `1 <= grid[i][j] <= 6` + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private val dirs = arrayOf( + arrayOf(intArrayOf(0, -1), intArrayOf(0, 1)), + arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0)), + arrayOf( + intArrayOf(0, -1), + intArrayOf(1, 0) + ), + arrayOf(intArrayOf(0, 1), intArrayOf(1, 0)), + arrayOf(intArrayOf(0, -1), intArrayOf(-1, 0)), + arrayOf( + intArrayOf(0, 1), + intArrayOf(-1, 0) + ) + ) + + // the idea is you need to check port direction match, you can go to next cell and check whether + // you can come back. + fun hasValidPath(grid: Array): Boolean { + val m = grid.size + val n = grid[0].size + val visited = Array(m) { BooleanArray(n) } + val q: Queue = LinkedList() + q.add(intArrayOf(0, 0)) + visited[0][0] = true + while (q.isNotEmpty()) { + val cur = q.poll() + val x = cur[0] + val y = cur[1] + val num = grid[x][y] - 1 + for (dir in dirs[num]) { + val nx = x + dir[0] + val ny = y + dir[1] + if (nx < 0 || nx >= m || ny < 0 || ny >= n || visited[nx][ny]) { + continue + } + // go to the next cell and come back to orign to see if port directions are same + for (backDir in dirs[grid[nx][ny] - 1]) { + if (nx + backDir[0] == x && ny + backDir[1] == y) { + visited[nx][ny] = true + q.add(intArrayOf(nx, ny)) + } + } + } + } + return visited[m - 1][n - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1392_longest_happy_prefix/readme.md b/src/main/kotlin/g1301_1400/s1392_longest_happy_prefix/readme.md new file mode 100644 index 00000000..5e559c07 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1392_longest_happy_prefix/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1392\. Longest Happy Prefix + +Hard + +A string is called a **happy prefix** if is a **non-empty** prefix which is also a suffix (excluding itself). + +Given a string `s`, return _the **longest happy prefix** of_ `s`. Return an empty string `""` if no such prefix exists. + +**Example 1:** + +**Input:** s = "level" + +**Output:** "l" + +**Explanation:** s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". + +**Example 2:** + +**Input:** s = "ababab" + +**Output:** "abab" + +**Explanation:** "abab" is the largest prefix which is also suffix. They can overlap in the original string. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun longestPrefix(s: String): String { + val times = 2 + var prefixHash: Long = 0 + var suffixHash: Long = 0 + var multiplier: Long = 1 + var len: Long = 0 + // use some large prime as a modulo to avoid overflow errors, e.g. 10 ^ 9 + 7. + val mod: Long = 1000000007 + for (i in 0 until s.length - 1) { + prefixHash = (prefixHash * times + s[i].code.toLong()) % mod + suffixHash = (multiplier * s[s.length - i - 1].code.toLong() + suffixHash) % mod + if (prefixHash == suffixHash) { + len = i.toLong() + 1 + } + multiplier = multiplier * times % mod + } + return s.substring(0, len.toInt()) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1393_capital_gainloss/readme.md b/src/main/kotlin/g1301_1400/s1393_capital_gainloss/readme.md new file mode 100644 index 00000000..ac4d9398 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1393_capital_gainloss/readme.md @@ -0,0 +1,82 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1393\. Capital Gain/Loss + +Medium + +SQL Schema + +Table: `Stocks` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | stock_name | varchar | + | operation | enum | + | operation_day | int | + | price | int | + +---------------+---------+ + (stock_name, operation_day) is the primary key for this table. + The operation column is an ENUM of type ('Sell', 'Buy') + Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price. + It is guaranteed that each 'Sell' operation for a stock has a corresponding 'Buy' operation in a previous day. + It is also guaranteed that each 'Buy' operation for a stock has a corresponding 'Sell' operation in an upcoming day. + +Write an SQL query to report the **Capital gain/loss** for each stock. + +The **Capital gain/loss** of a stock is the total gain or loss after buying and selling the stock one or many times. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Stocks table: + +---------------+-----------+---------------+--------+ + | stock_name | operation | operation_day | price | + +---------------+-----------+---------------+--------+ + | Leetcode | Buy | 1 | 1000 | + | Corona Masks | Buy | 2 | 10 | + | Leetcode | Sell | 5 | 9000 | + | Handbags | Buy | 17 | 30000 | + | Corona Masks | Sell | 3 | 1010 | + | Corona Masks | Buy | 4 | 1000 | + | Corona Masks | Sell | 5 | 500 | + | Corona Masks | Buy | 6 | 1000 | + | Handbags | Sell | 29 | 7000 | + | Corona Masks | Sell | 10 | 10000 | + +---------------+-----------+---------------+--------+ + +**Output:** + + +---------------+-------------------+ + | stock_name | capital_gain_loss | + +---------------+-------------------+ + | Corona Masks | 9500 | + | Leetcode | 8000 | + | Handbags | -23000 | + +---------------+-------------------+ + +**Explanation:** + +Leetcode stock was bought at day 1 for 1000$ and was sold at day 5 for 9000$. Capital gain = 9000 - 1000 = 8000$. + +Handbags stock was bought at day 17 for 30000$ and was sold at day 29 for 7000$. Capital loss = 7000 - 30000 = -23000$. + +Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$. It was bought again at day 4 for 1000$ and was sold at day 5 for 500$. + +At last, it was bought at day 6 for 1000$ and was sold at day 10 for 10000$. + +Capital gain/loss is the sum of capital gains/losses for each ('Buy' --> 'Sell') operation = (1010 - 10) + (500 - 1000) + (10000 - 1000) = 1000 - 500 + 9000 = 9500$. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT stock_name, SUM(CASE WHEN operation='Sell' THEN price ELSE -price END) AS capital_gain_loss +FROM Stocks GROUP BY stock_name; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1394_find_lucky_integer_in_an_array/readme.md b/src/main/kotlin/g1301_1400/s1394_find_lucky_integer_in_an_array/readme.md new file mode 100644 index 00000000..0367aebb --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1394_find_lucky_integer_in_an_array/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1394\. Find Lucky Integer in an Array + +Easy + +Given an array of integers `arr`, a **lucky integer** is an integer that has a frequency in the array equal to its value. + +Return _the largest **lucky integer** in the array_. If there is no **lucky integer** return `-1`. + +**Example 1:** + +**Input:** arr = [2,2,3,4] + +**Output:** 2 + +**Explanation:** The only lucky number in the array is 2 because frequency[2] == 2. + +**Example 2:** + +**Input:** arr = [1,2,2,3,3,3] + +**Output:** 3 + +**Explanation:** 1, 2 and 3 are all lucky numbers, return the largest of them. + +**Example 3:** + +**Input:** arr = [2,2,2,3,3] + +**Output:** -1 + +**Explanation:** There are no lucky numbers in the array. + +**Constraints:** + +* `1 <= arr.length <= 500` +* `1 <= arr[i] <= 500` + +## Solution + +```kotlin +class Solution { + fun findLucky(arr: IntArray): Int { + val numbers = IntArray(501) + for (j in arr) { + numbers[j]++ + } + for (i in 500 downTo 1) { + if (i == numbers[i]) { + return i + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1395_count_number_of_teams/readme.md b/src/main/kotlin/g1301_1400/s1395_count_number_of_teams/readme.md new file mode 100644 index 00000000..ac718800 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1395_count_number_of_teams/readme.md @@ -0,0 +1,114 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1395\. Count Number of Teams + +Medium + +There are `n` soldiers standing in a line. Each soldier is assigned a **unique** `rating` value. + +You have to form a team of 3 soldiers amongst them under the following rules: + +* Choose 3 soldiers with index (`i`, `j`, `k`) with rating (`rating[i]`, `rating[j]`, `rating[k]`). +* A team is valid if: (`rating[i] < rating[j] < rating[k]`) or (`rating[i] > rating[j] > rating[k]`) where (`0 <= i < j < k < n`). + +Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). + +**Example 1:** + +**Input:** rating = [2,5,3,4,1] + +**Output:** 3 + +**Explanation:** We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). + +**Example 2:** + +**Input:** rating = [2,1,3] + +**Output:** 0 + +**Explanation:** We can't form any team given the conditions. + +**Example 3:** + +**Input:** rating = [1,2,3,4] + +**Output:** 4 + +**Constraints:** + +* `n == rating.length` +* `3 <= n <= 1000` +* 1 <= rating[i] <= 105 +* All the integers in `rating` are **unique**. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun numTeams(rating: IntArray): Int { + val cp = rating.clone() + cp.sort() + // count i, j such that irating[j] + val reverseCount = Array(cp.size) { IntArray(2) } + val reverseBit = IntArray(cp.size) + for (i in cp.indices.reversed()) { + reverseCount[i][0] = count(bs(cp, rating[i] - 1), reverseBit) + reverseCount[i][1] = cp.size - 1 - i - reverseCount[i][0] + add(bs(cp, rating[i]), reverseBit) + } + var result = 0 + for (i in rating.indices) { + result += count[i][0] * reverseCount[i][1] + count[i][1] * reverseCount[i][0] + } + return result + } + + private fun count(idx: Int, bit: IntArray): Int { + var idx = idx + var sum = 0 + while (idx >= 0) { + sum += bit[idx] + idx = (idx and idx + 1) - 1 + } + return sum + } + + private fun add(idx: Int, bit: IntArray) { + var idx = idx + if (idx < 0) { + return + } + while (idx < bit.size) { + bit[idx] += 1 + idx = idx or idx + 1 + } + } + + private fun bs(arr: IntArray, `val`: Int): Int { + var l = 0 + var r = arr.size - 1 + while (l < r) { + val m = l + (r - l) / 2 + if (arr[m] == `val`) { + return m + } else if (arr[m] < `val`) { + l = m + 1 + } else { + r = m - 1 + } + } + return if (arr[l] > `val`) l - 1 else l + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1396_design_underground_system/readme.md b/src/main/kotlin/g1301_1400/s1396_design_underground_system/readme.md new file mode 100644 index 00000000..1c875f01 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1396_design_underground_system/readme.md @@ -0,0 +1,120 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1396\. Design Underground System + +Medium + +An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. + +Implement the `UndergroundSystem` class: + +* `void checkIn(int id, string stationName, int t)` + * A customer with a card ID equal to `id`, checks in at the station `stationName` at time `t`. + * A customer can only be checked into one place at a time. +* `void checkOut(int id, string stationName, int t)` + * A customer with a card ID equal to `id`, checks out from the station `stationName` at time `t`. +* `double getAverageTime(string startStation, string endStation)` + * Returns the average time it takes to travel from `startStation` to `endStation`. + * The average time is computed from all the previous traveling times from `startStation` to `endStation` that happened **directly**, meaning a check in at `startStation` followed by a check out from `endStation`. + * The time it takes to travel from `startStation` to `endStation` **may be different** from the time it takes to travel from `endStation` to `startStation`. + * There will be at least one customer that has traveled from `startStation` to `endStation` before `getAverageTime` is called. + +You may assume all calls to the `checkIn` and `checkOut` methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order. + +**Example 1:** + +**Input** ["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"] [[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]] + +**Output:** [null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000] + +**Explanation:** + + UndergroundSystem undergroundSystem = new UndergroundSystem(); + undergroundSystem.checkIn(45, "Leyton", 3); + undergroundSystem.checkIn(32, "Paradise", 8); + undergroundSystem.checkIn(27, "Leyton", 10); + undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12 + undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10 + undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14 + undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14 + undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11 + undergroundSystem.checkIn(10, "Leyton", 24); + undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000 + undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14 + undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12 + +**Example 2:** + +**Input** ["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"] [[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]] + +**Output:** [null,null,null,5.00000,null,null,5.50000,null,null,6.66667] + +**Explanation:** + + UndergroundSystem undergroundSystem = new UndergroundSystem(); + undergroundSystem.checkIn(10, "Leyton", 3); + undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5 + undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5 + undergroundSystem.checkIn(5, "Leyton", 10); + undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6 + undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5 + undergroundSystem.checkIn(2, "Leyton", 21); + undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9 + undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667 + +**Constraints:** + +* 1 <= id, t <= 106 +* `1 <= stationName.length, startStation.length, endStation.length <= 10` +* All strings consist of uppercase and lowercase English letters and digits. +* There will be at most 2 * 104 calls **in total** to `checkIn`, `checkOut`, and `getAverageTime`. +* Answers within 10-5 of the actual value will be accepted. + +## Solution + +```kotlin +import java.util.LinkedList + +class UndergroundSystem { + private class StationAndTime(var station: String, var time: Int) + + private val averageTimeMap: MutableMap + private val travelerMap: MutableMap> + + init { + averageTimeMap = HashMap() + travelerMap = HashMap() + } + + fun checkIn(id: Int, stationName: String, t: Int) { + travelerMap.putIfAbsent(id, LinkedList()) + travelerMap[id]!!.add(StationAndTime(stationName, t)) + } + + fun checkOut(id: Int, stationName: String, t: Int) { + val list = travelerMap[id]!! + val stationAndTime = list.last + val startToEndStation: String = stationAndTime.station + "->" + stationName + val duration: Int = t - stationAndTime.time + if (averageTimeMap.containsKey(startToEndStation)) { + val pair = averageTimeMap[startToEndStation] + val newAverage = (pair!![0] * pair[1] + duration) / (pair[1] + 1) + averageTimeMap[startToEndStation] = doubleArrayOf(newAverage, pair[1] + 1) + } else { + averageTimeMap[startToEndStation] = doubleArrayOf(duration.toDouble(), 1.0) + } + } + + fun getAverageTime(startStation: String, endStation: String): Double { + return averageTimeMap["$startStation->$endStation"]!![0] + } +} +/* + * Your UndergroundSystem object will be instantiated and called as such: + * var obj = UndergroundSystem() + * obj.checkIn(id,stationName,t) + * obj.checkOut(id,stationName,t) + * var param_3 = obj.getAverageTime(startStation,endStation) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1397_find_all_good_strings/readme.md b/src/main/kotlin/g1301_1400/s1397_find_all_good_strings/readme.md new file mode 100644 index 00000000..c9535ca9 --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1397_find_all_good_strings/readme.md @@ -0,0 +1,126 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1397\. Find All Good Strings + +Hard + +Given the strings `s1` and `s2` of size `n` and the string `evil`, return _the number of **good** strings_. + +A **good** string has size `n`, it is alphabetically greater than or equal to `s1`, it is alphabetically smaller than or equal to `s2`, and it does not contain the string `evil` as a substring. Since the answer can be a huge number, return this **modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 2, s1 = "aa", s2 = "da", evil = "b" + +**Output:** 51 + +**Explanation:** There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da". + +**Example 2:** + +**Input:** n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet" + +**Output:** 0 + +**Explanation:** All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string. + +**Example 3:** + +**Input:** n = 2, s1 = "gx", s2 = "gz", evil = "x" + +**Output:** 2 + +**Constraints:** + +* `s1.length == n` +* `s2.length == n` +* `s1 <= s2` +* `1 <= n <= 500` +* `1 <= evil.length <= 50` +* All strings consist of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING", "UNUSED_PARAMETER") +class Solution { + private val mod = 1000000007 + private lateinit var next: IntArray + + fun findGoodStrings(n: Int, s1: String, s2: String, evil: String): Int { + var s1 = s1 + val s1arr = s1.toCharArray() + for (i in s1.length - 1 downTo 0) { + if (s1arr[i] > 'a') { + s1arr[i] = (s1arr[i].code - 1).toChar() + break + } else { + s1arr[i] = 'z' + } + } + s1 = String(s1arr) + next = getNext(evil) + return if (s1.compareTo(s2) > 0) { + lessOrEqualThan(s2, evil) + } else (lessOrEqualThan(s2, evil) - lessOrEqualThan(s1, evil) + mod) % mod + } + + private fun lessOrEqualThan(s: String, e: String): Int { + val dp = Array(s.length + 1) { Array(e.length + 1) { LongArray(2) } } + dp[0][0][1] = 1 + var res: Long = 0 + for (i in 0 until s.length) { + for (state in 0 until e.length) { + run { + var c = 'a' + while (c <= 'z') { + val nextstate = getNextState(state, c, e) + dp[i + 1][nextstate][0] = (dp[i + 1][nextstate][0] + dp[i][state][0]) % mod + c++ + } + } + var c = 'a' + while (c < s[i]) { + val nextstate = getNextState(state, c, e) + dp[i + 1][nextstate][0] = (dp[i + 1][nextstate][0] + dp[i][state][1]) % mod + c++ + } + val nextstate = getNextState(state, s[i], e) + dp[i + 1][nextstate][1] = (dp[i + 1][nextstate][1] + dp[i][state][1]) % mod + } + } + for (i in 0 until e.length) { + res = (res + dp[s.length][i][0]) % mod + res = (res + dp[s.length][i][1]) % mod + } + return res.toInt() + } + + private fun getNextState(prevState: Int, nextChar: Char, evil: String): Int { + var idx = prevState + while (idx != -1 && evil[idx] != nextChar) { + idx = next[idx] + } + return idx + 1 + } + + private fun getNext(e: String): IntArray { + val len = e.length + val localNext = IntArray(len) + localNext[0] = -1 + var last = -1 + var i = 0 + while (i < len - 1) { + if (last == -1 || e[i] == e[last]) { + i++ + last++ + localNext[i] = last + } else { + last = localNext[last] + } + } + return localNext + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1399_count_largest_group/readme.md b/src/main/kotlin/g1301_1400/s1399_count_largest_group/readme.md new file mode 100644 index 00000000..159e465d --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1399_count_largest_group/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1399\. Count Largest Group + +Easy + +You are given an integer `n`. + +Each number from `1` to `n` is grouped according to the sum of its digits. + +Return _the number of groups that have the largest size_. + +**Example 1:** + +**Input:** n = 13 + +**Output:** 4 + +**Explanation:** There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: + +[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. + +There are 4 groups with largest size. + +**Example 2:** + +**Input:** n = 2 + +**Output:** 2 + +**Explanation:** There are 2 groups [1], [2] of size 1. + +**Constraints:** + +* 1 <= n <= 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun countLargestGroup(n: Int): Int { + var largest = 0 + val map = IntArray(37) + var sumOfDigit = 0 + for (i in 1..n) { + if (i % 10 == 0) { + // reset and start a new sum + sumOfDigit = getSumOfDigits(i) + } else { + sumOfDigit++ + } + val `val` = ++map[sumOfDigit] + largest = if (`val` > largest) `val` else largest + } + return countLargestGroup(largest, map) + } + + private fun countLargestGroup(largest: Int, arr: IntArray): Int { + var count = 0 + for (`val` in arr) { + if (`val` == largest) { + count++ + } + } + return count + } + + private fun getSumOfDigits(num: Int): Int { + var num = num + var sum = 0 + while (num > 0) { + sum += num % 10 + num /= 10 + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1301_1400/s1400_construct_k_palindrome_strings/readme.md b/src/main/kotlin/g1301_1400/s1400_construct_k_palindrome_strings/readme.md new file mode 100644 index 00000000..71cc27cf --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1400_construct_k_palindrome_strings/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1400\. Construct K Palindrome Strings + +Medium + +Given a string `s` and an integer `k`, return `true` _if you can use all the characters in_ `s` _to construct_ `k` _palindrome strings or_ `false` _otherwise_. + +**Example 1:** + +**Input:** s = "annabelle", k = 2 + +**Output:** true + +**Explanation:** You can construct two palindromes using all characters in s. Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b" + +**Example 2:** + +**Input:** s = "leetcode", k = 3 + +**Output:** false + +**Explanation:** It is impossible to construct 3 palindromes using all the characters of s. + +**Example 3:** + +**Input:** s = "true", k = 4 + +**Output:** true + +**Explanation:** The only possible solution is to put each character in a separate string. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of lowercase English letters. +* 1 <= k <= 105 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun canConstruct(s: String, k: Int): Boolean { + var k = k + if (s.length == k) { + // if size is same as k we can separate out all letters + return true + } + if (s.length < k) { + // if size is less than it is not possible + return false + } + // count occurrence of each letter + val count = IntArray(26) + for (curr in s.toCharArray()) { + count[curr.code - 'a'.code]++ + } + // reduce k whenever count is odd + for (i in 0..25) { + if (count[i] % 2 != 0) { + k-- + } + } + // we can have max k odd characters + return k >= 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1401_circle_and_rectangle_overlapping/readme.md b/src/main/kotlin/g1401_1500/s1401_circle_and_rectangle_overlapping/readme.md new file mode 100644 index 00000000..b409ee12 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1401_circle_and_rectangle_overlapping/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1401\. Circle and Rectangle Overlapping + +Medium + +You are given a circle represented as `(radius, xCenter, yCenter)` and an axis-aligned rectangle represented as `(x1, y1, x2, y2)`, where `(x1, y1)` are the coordinates of the bottom-left corner, and `(x2, y2)` are the coordinates of the top-right corner of the rectangle. + +Return `true` _if the circle and rectangle are overlapped otherwise return_ `false`. In other words, check if there is **any** point (xi, yi) that belongs to the circle and the rectangle at the same time. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/20/sample_4_1728.png) + +**Input:** radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 + +**Output:** true + +**Explanation:** Circle and rectangle share the point (1,0). + +**Example 2:** + +**Input:** radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 + +**Output:** false + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/02/20/sample_2_1728.png) + +**Input:** radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 + +**Output:** true + +**Constraints:** + +* `1 <= radius <= 2000` +* -104 <= xCenter, yCenter <= 104 +* -104 <= x1 < x2 <= 104 +* -104 <= y1 < y2 <= 104 + +## Solution + +```kotlin +class Solution { + fun checkOverlap( + radius: Int, + xCenter: Int, + yCenter: Int, + x1: Int, + y1: Int, + x2: Int, + y2: Int + ): Boolean { + // Find the closest point to the circle within the rectangle + val closestX = clamp(xCenter, x1, x2) + val closestY = clamp(yCenter, y1, y2) + // Calculate the distance between the circle's center and this closest point + val distanceX = xCenter - closestX + val distanceY = yCenter - closestY + // If the distance is less than the circle's radius, an intersection occurs + val distanceSquared = distanceX * distanceX + distanceY * distanceY + return distanceSquared <= radius * radius + } + + private fun clamp(`val`: Int, min: Int, max: Int): Int { + return Math.max(min, Math.min(max, `val`)) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1402_reducing_dishes/readme.md b/src/main/kotlin/g1401_1500/s1402_reducing_dishes/readme.md new file mode 100644 index 00000000..b666aa66 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1402_reducing_dishes/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1402\. Reducing Dishes + +Hard + +A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time. + +**Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`. + +Return _the maximum sum of **like-time coefficient** that the chef can obtain after dishes preparation_. + +Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value. + +**Example 1:** + +**Input:** satisfaction = [-1,-8,0,5,-9] + +**Output:** 14 + +**Explanation:** After Removing the second and last dish, the maximum total **like-time coefficient** will be equal to (-1\*1 + 0\*2 + 5\*3 = 14). Each dish is prepared in one unit of time. + +**Example 2:** + +**Input:** satisfaction = [4,3,2] + +**Output:** 20 + +**Explanation:** Dishes can be prepared in any order, (2\*1 + 3\*2 + 4\*3 = 20) + +**Example 3:** + +**Input:** satisfaction = [-1,-4,-5] + +**Output:** 0 + +**Explanation:** People do not like the dishes. No dish is prepared. + +**Constraints:** + +* `n == satisfaction.length` +* `1 <= n <= 500` +* `-1000 <= satisfaction[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maxSatisfaction(satisfaction: IntArray): Int { + satisfaction.sort() + var sum = 0 + var mulSum = 0 + for (i in satisfaction.indices) { + sum += satisfaction[i] + mulSum += (i + 1) * satisfaction[i] + } + var maxVal = Math.max(0, mulSum) + for (j in satisfaction) { + mulSum -= sum + sum -= j + maxVal = Math.max(maxVal, mulSum) + } + return maxVal + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1403_minimum_subsequence_in_non_increasing_order/readme.md b/src/main/kotlin/g1401_1500/s1403_minimum_subsequence_in_non_increasing_order/readme.md new file mode 100644 index 00000000..5fe9e061 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1403_minimum_subsequence_in_non_increasing_order/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1403\. Minimum Subsequence in Non-Increasing Order + +Easy + +Given the array `nums`, obtain a subsequence of the array whose sum of elements is **strictly greater** than the sum of the non included elements in such subsequence. + +If there are multiple solutions, return the subsequence with **minimum size** and if there still exist multiple solutions, return the subsequence with the **maximum total sum** of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. + +Note that the solution with the given constraints is guaranteed to be **unique**. Also return the answer sorted in **non-increasing** order. + +**Example 1:** + +**Input:** nums = [4,3,10,9,8] + +**Output:** [10,9] + +**Explanation:** The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements. + +**Example 2:** + +**Input:** nums = [4,4,7,6,7] + +**Output:** [7,7,6] + +**Explanation:** The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to returned in non-decreasing order. + +**Example 3:** + +**Input:** nums = [6] + +**Output:** [6] + +**Constraints:** + +* `1 <= nums.length <= 500` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun minSubsequence(nums: IntArray): List { + nums.sort() + var startIndex = 0 + var endIndex = nums.size - 1 + var sumOfNonIncludedElements = nums[0] + var sumOfIncludedElements = nums[endIndex] + val result: MutableList = ArrayList() + while (startIndex < endIndex) { + if (sumOfNonIncludedElements < sumOfIncludedElements) { + sumOfNonIncludedElements += nums[++startIndex] + } else { + result.add(nums[endIndex]) + sumOfIncludedElements += nums[--endIndex] + } + } + result.add(nums[startIndex]) + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1404_number_of_steps_to_reduce_a_number_in_binary_representation_to_one/readme.md b/src/main/kotlin/g1401_1500/s1404_number_of_steps_to_reduce_a_number_in_binary_representation_to_one/readme.md new file mode 100644 index 00000000..8935425b --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1404_number_of_steps_to_reduce_a_number_in_binary_representation_to_one/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1404\. Number of Steps to Reduce a Number in Binary Representation to One + +Medium + +Given the binary representation of an integer as a string `s`, return _the number of steps to reduce it to_ `1` _under the following rules_: + +* If the current number is even, you have to divide it by `2`. + +* If the current number is odd, you have to add `1` to it. + + +It is guaranteed that you can always reach one for all test cases. + +**Example 1:** + +**Input:** s = "1101" + +**Output:** 6 + +**Explanation:** "1101" corressponds to number 13 in their decimal representation. + +Step 1) 13 is odd, add 1 and obtain 14. + +Step 2) 14 is even, divide by 2 and obtain 7. + +Step 3) 7 is odd, add 1 and obtain 8. + +Step 4) 8 is even, divide by 2 and obtain 4. + +Step 5) 4 is even, divide by 2 and obtain 2. + +Step 6) 2 is even, divide by 2 and obtain 1. + +**Example 2:** + +**Input:** s = "10" + +**Output:** 1 + +**Explanation:** "10" corressponds to number 2 in their decimal representation. + +Step 1) 2 is even, divide by 2 and obtain 1. + +**Example 3:** + +**Input:** s = "1" + +**Output:** 0 + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of characters '0' or '1' +* `s[0] == '1'` + +## Solution + +```kotlin +class Solution { + fun numSteps(s: String): Int { + var steps = 0 + var carry = 0 + for (i in s.length - 1 downTo 1) { + if (carry == 0) { + if (s[i] == '1') { + steps += 2 + carry = 1 + } else { + steps++ + } + } else { + if (s[i] == '0') { + steps += 2 + } else { + steps++ + } + } + } + return steps + carry + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1405_longest_happy_string/readme.md b/src/main/kotlin/g1401_1500/s1405_longest_happy_string/readme.md new file mode 100644 index 00000000..30cfbefa --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1405_longest_happy_string/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1405\. Longest Happy String + +Medium + +A string `s` is called **happy** if it satisfies the following conditions: + +* `s` only contains the letters `'a'`, `'b'`, and `'c'`. +* `s` does not contain any of `"aaa"`, `"bbb"`, or `"ccc"` as a substring. +* `s` contains **at most** `a` occurrences of the letter `'a'`. +* `s` contains **at most** `b` occurrences of the letter `'b'`. +* `s` contains **at most** `c` occurrences of the letter `'c'`. + +Given three integers `a`, `b`, and `c`, return _the **longest possible happy** string_. If there are multiple longest happy strings, return _any of them_. If there is no such string, return _the empty string_ `""`. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** a = 1, b = 1, c = 7 + +**Output:** "ccaccbcc" + +**Explanation:** "ccbccacc" would also be a correct answer. + +**Example 2:** + +**Input:** a = 7, b = 1, c = 0 + +**Output:** "aabaa" + +**Explanation:** It is the only correct answer in this case. + +**Constraints:** + +* `0 <= a, b, c <= 100` +* `a + b + c > 0` + +## Solution + +```kotlin +class Solution { + fun longestDiverseString(a: Int, b: Int, c: Int): String { + val sb = StringBuilder() + val remains = intArrayOf(a, b, c) + val chars = charArrayOf('a', 'b', 'c') + var preIndex = -1 + do { + var index: Int + var largest: Boolean + if (preIndex != -1 && + remains[preIndex] + == Math.max(remains[0], Math.max(remains[1], remains[2])) + ) { + index = if (preIndex == 0) { + if (remains[1] > remains[2]) 1 else 2 + } else if (preIndex == 1) { + if (remains[0] > remains[2]) 0 else 2 + } else { + if (remains[0] > remains[1]) 0 else 1 + } + largest = false + } else { + index = if (remains[0] > remains[1]) 0 else 1 + index = if (remains[index] > remains[2]) index else 2 + largest = true + } + remains[index]-- + sb.append(chars[index]) + if (remains[index] > 0 && largest) { + remains[index]-- + sb.append(chars[index]) + } + preIndex = index + } while (remains[0] + remains[1] + remains[2] != remains[preIndex]) + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1406_stone_game_iii/readme.md b/src/main/kotlin/g1401_1500/s1406_stone_game_iii/readme.md new file mode 100644 index 00000000..0a020577 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1406_stone_game_iii/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1406\. Stone Game III + +Hard + +Alice and Bob continue their games with piles of stones. There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`. + +Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take `1`, `2`, or `3` stones from the **first** remaining stones in the row. + +The score of each player is the sum of the values of the stones taken. The score of each player is `0` initially. + +The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. + +Assume Alice and Bob **play optimally**. + +Return `"Alice"` _if Alice will win,_ `"Bob"` _if Bob will win, or_ `"Tie"` _if they will end the game with the same score_. + +**Example 1:** + +**Input:** values = [1,2,3,7] + +**Output:** "Bob" + +**Explanation:** Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. + +**Example 2:** + +**Input:** values = [1,2,3,-9] + +**Output:** "Alice" + +**Explanation:** Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. + +**Example 3:** + +**Input:** values = [1,2,3,6] + +**Output:** "Tie" + +**Explanation:** Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. + +**Constraints:** + +* 1 <= stoneValue.length <= 5 * 104 +* `-1000 <= stoneValue[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun stoneGameIII(stoneValue: IntArray): String { + val dp = IntArray(stoneValue.size + 1) + dp.fill(0) + var i = stoneValue.size - 1 + while (i >= 0) { + var ans = Int.MIN_VALUE + ans = Math.max(ans, stoneValue[i] - dp[i + 1]) + if (i + 1 < stoneValue.size) { + ans = Math.max(ans, stoneValue[i] + stoneValue[i + 1] - dp[i + 2]) + } + if (i + 2 < stoneValue.size) { + ans = Math.max( + ans, + stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[i + 3] + ) + } + dp[i] = ans + i-- + } + val value = dp[0] + if (value > 0) { + return "Alice" + } + return if (value == 0) "Tie" else "Bob" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1407_top_travellers/readme.md b/src/main/kotlin/g1401_1500/s1407_top_travellers/readme.md new file mode 100644 index 00000000..42d07cd6 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1407_top_travellers/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1407\. Top Travellers + +Easy + +SQL Schema + +Table: `Users` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | id | int | + | name | varchar | + +---------------+---------+ + id is the primary key for this table. + name is the name of the user. + +Table: `Rides` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | id | int | + | user_id | int | + | distance | int | + +---------------+---------+ + id is the primary key for this table. + user_id is the id of the user who traveled the distance "distance". + +Write an SQL query to report the distance traveled by each user. + +Return the result table ordered by `travelled_distance` in **descending order**, if two or more users traveled the same distance, order them by their `name` in **ascending order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + +Users table: + + +------+-----------+ + | id | name | + +------+-----------+ + | 1 | Alice | + | 2 | Bob | + | 3 | Alex | + | 4 | Donald | + | 7 | Lee | + | 13 | Jonathan | + | 19 | Elvis | + +------+-----------+ + +Rides table: + + +------+----------+----------+ + | id | user_id | distance | + +------+----------+----------+ + | 1 | 1 | 120 | + | 2 | 2 | 317 | + | 3 | 3 | 222 | + | 4 | 7 | 100 | + | 5 | 13 | 312 | + | 6 | 19 | 50 | + | 7 | 7 | 120 | + | 8 | 19 | 400 | + | 9 | 7 | 230 | + +------+----------+----------+ + +**Output:** + + +----------+--------------------+ + | name | travelled_distance | + +----------+--------------------+ + | Elvis | 450 | + | Lee | 450 | + | Bob | 317 | + | Jonathan | 312 | + | Alex | 222 | + | Alice | 120 | + | Donald | 0 | + +----------+--------------------+ + +**Explanation:** + +Elvis and Lee traveled 450 miles, Elvis is the top traveler as his name is alphabetically smaller than Lee. + +Bob, Jonathan, Alex, and Alice have only one ride and we just order them by the total distances of the ride. + +Donald did not have any rides, the distance traveled by him is 0. + +## Solution + +```sql +# Write your MySQL query statement below +select u.name,IFNULL(sum(r.distance), 0) as travelled_distance +from Users u left join Rides r +on u.id = r.user_id +group by u.id +order by travelled_distance desc,name asc +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1408_string_matching_in_an_array/readme.md b/src/main/kotlin/g1401_1500/s1408_string_matching_in_an_array/readme.md new file mode 100644 index 00000000..160e599e --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1408_string_matching_in_an_array/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1408\. String Matching in an Array + +Easy + +Given an array of string `words`. Return all strings in `words` which is substring of another word in **any** order. + +String `words[i]` is substring of `words[j]`, if can be obtained removing some characters to left and/or right side of `words[j]`. + +**Example 1:** + +**Input:** words = ["mass","as","hero","superhero"] + +**Output:** ["as","hero"] + +**Explanation:** "as" is substring of "mass" and "hero" is substring of "superhero". ["hero","as"] is also a valid answer. + +**Example 2:** + +**Input:** words = ["leetcode","et","code"] + +**Output:** ["et","code"] + +**Explanation:** "et", "code" are substring of "leetcode". + +**Example 3:** + +**Input:** words = ["blue","green","bu"] + +**Output:** [] + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 30` +* `words[i]` contains only lowercase English letters. +* It's **guaranteed** that `words[i]` will be unique. + +## Solution + +```kotlin +class Solution { + fun stringMatching(words: Array): List { + val set: MutableSet = HashSet() + for (word in words) { + for (s in words) { + if (word != s && word.length < s.length && s.contains(word)) { + set.add(word) + } + } + } + return ArrayList(set) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1409_queries_on_a_permutation_with_key/readme.md b/src/main/kotlin/g1401_1500/s1409_queries_on_a_permutation_with_key/readme.md new file mode 100644 index 00000000..0e986cfa --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1409_queries_on_a_permutation_with_key/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1409\. Queries on a Permutation With Key + +Medium + +Given the array `queries` of positive integers between `1` and `m`, you have to process all `queries[i]` (from `i=0` to `i=queries.length-1`) according to the following rules: + +* In the beginning, you have the permutation `P=[1,2,3,...,m]`. +* For the current `i`, find the position of `queries[i]` in the permutation `P` (**indexing from 0**) and then move this at the beginning of the permutation `P.` Notice that the position of `queries[i]` in `P` is the result for `queries[i]`. + +Return an array containing the result for the given `queries`. + +**Example 1:** + +**Input:** queries = [3,1,2,1], m = 5 + +**Output:** [2,1,2,1] + +**Explanation:** The queries are processed as follow: + +For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is **2**, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. + +For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is **1**, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. + +For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is **2**, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. + +For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is **1**, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. + +Therefore, the array containing the result is [2,1,2,1]. + +**Example 2:** + +**Input:** queries = [4,1,2,2], m = 4 + +**Output:** [3,1,2,0] + +**Example 3:** + +**Input:** queries = [7,5,5,8,3], m = 8 + +**Output:** [6,5,0,7,5] + +**Constraints:** + +* `1 <= m <= 10^3` +* `1 <= queries.length <= m` +* `1 <= queries[i] <= m` + +## Solution + +```kotlin +class Solution { + fun processQueries(queries: IntArray, m: Int): IntArray { + val ans = IntArray(queries.size) + val list: MutableList = ArrayList() + for (i in 0 until m) { + list.add(i + 1) + } + for (i in queries.indices) { + val index = list.indexOf(queries[i]) + ans[i] = index + list.removeAt(index) + list.add(0, queries[i]) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1410_html_entity_parser/readme.md b/src/main/kotlin/g1401_1500/s1410_html_entity_parser/readme.md new file mode 100644 index 00000000..f391a876 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1410_html_entity_parser/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1410\. HTML Entity Parser + +Medium + +**HTML entity parser** is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. + +The special characters and their entities for HTML are: + +* **Quotation Mark:** the entity is `"` and symbol character is `"`. +* **Single Quote Mark:** the entity is `'` and symbol character is `'`. +* **Ampersand:** the entity is `&` and symbol character is `&`. +* **Greater Than Sign:** the entity is `>` and symbol character is `>`. +* **Less Than Sign:** the entity is `<` and symbol character is `<`. +* **Slash:** the entity is `⁄` and symbol character is `/`. + +Given the input `text` string to the HTML parser, you have to implement the entity parser. + +Return _the text after replacing the entities by the special characters_. + +**Example 1:** + +**Input:** text = "& is an HTML entity but &ambassador; is not." + +**Output:** "& is an HTML entity but &ambassador; is not." + +**Explanation:** The parser will replace the & entity by & + +**Example 2:** + +**Input:** text = "and I quote: "..."" + +**Output:** "and I quote: \\"...\\"" + +**Constraints:** + +* 1 <= text.length <= 105 +* The string may contain any possible characters out of all the 256 ASCII characters. + +## Solution + +```kotlin +class Solution { + fun entityParser(text: String): String { + val map: MutableMap = HashMap() + map["""] = "\"" + map["'"] = "'" + map["&"] = "&" + map[">"] = ">" + map["<"] = "<" + map["⁄"] = "/" + val n = text.length + val sb = StringBuilder() + var i = 0 + while (i < n) { + val c = text[i] + if (c == '&') { + val index = text.indexOf(";", i) + if (index >= 0) { + val pattern = text.substring(i, index + 1) + if (map.containsKey(pattern)) { + sb.append(map[pattern]) + i += pattern.length + continue + } + } + } + sb.append(c) + i++ + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1411_number_of_ways_to_paint_n_3_grid/readme.md b/src/main/kotlin/g1401_1500/s1411_number_of_ways_to_paint_n_3_grid/readme.md new file mode 100644 index 00000000..47712828 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1411_number_of_ways_to_paint_n_3_grid/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1411\. Number of Ways to Paint N × 3 Grid + +Hard + +You have a `grid` of size `n x 3` and you want to paint each cell of the grid with exactly one of the three colors: **Red**, **Yellow,** or **Green** while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). + +Given `n` the number of rows of the grid, return _the number of ways_ you can paint this `grid`. As the answer may grow large, the answer **must be** computed modulo 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/03/26/e1.png) + +**Input:** n = 1 + +**Output:** 12 + +**Explanation:** There are 12 possible way to paint the grid as shown. + +**Example 2:** + +**Input:** n = 5000 + +**Output:** 30228214 + +**Constraints:** + +* `n == grid.length` +* `1 <= n <= 5000` + +## Solution + +```kotlin +class Solution { + fun numOfWays(n: Int): Int { + val dp = Array(n + 1) { IntArray(12) } + dp[1].fill(1) + val transfer = arrayOf( + intArrayOf(5, 6, 8, 9, 10), intArrayOf(5, 8, 7, 9, -1), + intArrayOf(5, 6, 9, 10, 12), intArrayOf(6, 10, 11, 12, -1), intArrayOf(1, 2, 3, 11, 12), + intArrayOf(1, 3, 4, 11, -1), intArrayOf(2, 9, 10, 12, -1), intArrayOf(1, 2, 10, 11, 12), + intArrayOf(1, 2, 3, 7, -1), intArrayOf(1, 3, 4, 7, 8), intArrayOf(4, 5, 6, 8, -1), + intArrayOf(3, 4, 5, 7, 8) + ) + for (i in 2..n) { + for (j in 0..11) { + val prevStates = transfer[j] + var sum = 0 + for (s in prevStates) { + if (s == -1) { + break + } + sum = (sum + dp[i - 1][s - 1]) % MOD + } + dp[i][j] = sum + } + } + var total = 0 + for (i in 0..11) { + total = (total + dp[n][i]) % MOD + } + return total + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1413_minimum_value_to_get_positive_step_by_step_sum/readme.md b/src/main/kotlin/g1401_1500/s1413_minimum_value_to_get_positive_step_by_step_sum/readme.md new file mode 100644 index 00000000..0300b736 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1413_minimum_value_to_get_positive_step_by_step_sum/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1413\. Minimum Value to Get Positive Step by Step Sum + +Easy + +Given an array of integers `nums`, you start with an initial **positive** value _startValue__._ + +In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right). + +Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1. + +**Example 1:** + +**Input:** nums = [-3,2,-3,4,2] + +**Output:** 5 + +**Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1. + +**step by step sum** + +**startValue = 4 \| startValue = 5 \| nums** + +(4 **\-3** ) = 1 \| (5 **\-3** ) = 2 \| -3 + +(1 **+2** ) = 3 \| (2 **+2** ) = 4 \| 2 + +(3 **\-3** ) = 0 \| (4 **\-3** ) = 1 \| -3 + +(0 **+4** ) = 4 \| (1 **+4** ) = 5 \| 4 + +(4 **+2** ) = 6 \| (5 **+2** ) = 7 \| 2 + +**Example 2:** + +**Input:** nums = [1,2] + +**Output:** 1 + +**Explanation:** Minimum start value should be positive. + +**Example 3:** + +**Input:** nums = [1,-2,-3] + +**Output:** 5 + +**Constraints:** + +* `1 <= nums.length <= 100` +* `-100 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun minStartValue(nums: IntArray): Int { + var min = Int.MAX_VALUE + var sum = 0 + for (num in nums) { + sum += num + min = Math.min(sum, min) + } + return if (min > 0) 1 else Math.abs(min) + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k/readme.md b/src/main/kotlin/g1401_1500/s1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k/readme.md new file mode 100644 index 00000000..3448a1d5 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1414\. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K + +Medium + +Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times. + +The Fibonacci numbers are defined as: + +* F1 = 1 +* F2 = 1 +* Fn = Fn-1 + Fn-2 for `n > 2.` + +It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to `k`. + +**Example 1:** + +**Input:** k = 7 + +**Output:** 2 + +**Explanation:** The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7. + +**Example 2:** + +**Input:** k = 10 + +**Output:** 2 + +**Explanation:** For k = 10 we can use 2 + 8 = 10. + +**Example 3:** + +**Input:** k = 19 + +**Output:** 3 + +**Explanation:** For k = 19 we can use 1 + 5 + 13 = 19. + +**Constraints:** + +* 1 <= k <= 109 + +## Solution + +```kotlin +class Solution { + fun findMinFibonacciNumbers(k: Int): Int { + val list: MutableList = mutableListOf(1, 1) + var prev = 1 + var curr = 1 + while (prev <= k) { + val n = prev + curr + prev = curr + curr = n + list.add(n) + } + var count = 0 + var num = k + for (i in list.indices.reversed()) { + if (list[i] <= num) { + count++ + num = num - list[i] + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1415_the_k_th_lexicographical_string_of_all_happy_strings_of_length_n/readme.md b/src/main/kotlin/g1401_1500/s1415_the_k_th_lexicographical_string_of_all_happy_strings_of_length_n/readme.md new file mode 100644 index 00000000..a17d567b --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1415_the_k_th_lexicographical_string_of_all_happy_strings_of_length_n/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1415\. The k-th Lexicographical String of All Happy Strings of Length n + +Medium + +A **happy string** is a string that: + +* consists only of letters of the set `['a', 'b', 'c']`. +* `s[i] != s[i + 1]` for all values of `i` from `1` to `s.length - 1` (string is 1-indexed). + +For example, strings **"abc", "ac", "b"** and **"abcbabcbcb"** are all happy strings and strings **"aa", "baa"** and **"ababbc"** are not happy strings. + +Given two integers `n` and `k`, consider a list of all happy strings of length `n` sorted in lexicographical order. + +Return _the kth string_ of this list or return an **empty string** if there are less than `k` happy strings of length `n`. + +**Example 1:** + +**Input:** n = 1, k = 3 + +**Output:** "c" + +**Explanation:** The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c". + +**Example 2:** + +**Input:** n = 1, k = 4 + +**Output:** "" + +**Explanation:** There are only 3 happy strings of length 1. + +**Example 3:** + +**Input:** n = 3, k = 9 + +**Output:** "cab" + +**Explanation:** There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab" + +**Constraints:** + +* `1 <= n <= 10` +* `1 <= k <= 100` + +## Solution + +```kotlin +class Solution { + private val arr = charArrayOf('a', 'b', 'c') + private var res = "" + private var k = 0 + + private operator fun get(str: StringBuilder, n: Int, index: Int) { + if (k < 1) { + return + } + if (str.length == n) { + if (k == 1) { + res = str.toString() + } + k-- + return + } + for (i in 0..2) { + if (i == index) { + continue + } + str.append(arr[i]) + get(str, n, i) + str.deleteCharAt(str.length - 1) + } + } + + fun getHappyString(n: Int, k: Int): String { + this.k = k + get(StringBuilder(), n, -1) + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1416_restore_the_array/readme.md b/src/main/kotlin/g1401_1500/s1416_restore_the_array/readme.md new file mode 100644 index 00000000..915e7441 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1416_restore_the_array/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1416\. Restore The Array + +Hard + +A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array. + +Given the string `s` and the integer `k`, return _the number of the possible arrays that can be printed as_ `s` _using the mentioned program_. Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** s = "1000", k = 10000 + +**Output:** 1 + +**Explanation:** The only possible array is [1000] + +**Example 2:** + +**Input:** s = "1000", k = 10 + +**Output:** 0 + +**Explanation:** There cannot be an array that was printed this way and has all integer >= 1 and <= 10. + +**Example 3:** + +**Input:** s = "1317", k = 2000 + +**Output:** 8 + +**Explanation:** Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7] + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of only digits and does not contain leading zeros. +* 1 <= k <= 109 + +## Solution + +```kotlin +class Solution { + fun numberOfArrays(s: String, k: Int): Int { + // dp[i] is number of ways to print valid arrays from string s start at i + val dp = arrayOfNulls(s.length) + return dfs(s, k.toLong(), 0, dp) + } + + private fun dfs(s: String, k: Long, i: Int, dp: Array): Int { + // base case -> Found a valid way + if (i == s.length) return 1 + // all numbers are in range [1, k] and there are no leading zeros -> So numbers starting with 0 mean invalid! + if (s[i] == '0') return 0 + if (dp[i] != null) return dp[i]!! + var ans = 0 + var num: Long = 0 + for (j in i until s.length) { + // num is the value of the substring s[i..j] + num = num * 10 + s[j].code.toLong() - '0'.code.toLong() + // num must be in range [1, k] + if (num > k) break + ans += dfs(s, k, j + 1, dp) + ans %= 1000000007 + } + return ans.also { dp[i] = it } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1417_reformat_the_string/readme.md b/src/main/kotlin/g1401_1500/s1417_reformat_the_string/readme.md new file mode 100644 index 00000000..20270836 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1417_reformat_the_string/readme.md @@ -0,0 +1,73 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1417\. Reformat The String + +Easy + +You are given an alphanumeric string `s`. (**Alphanumeric string** is a string consisting of lowercase English letters and digits). + +You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. + +Return _the reformatted string_ or return **an empty string** if it is impossible to reformat the string. + +**Example 1:** + +**Input:** s = "a0b1c2" + +**Output:** "0a1b2c" + +**Explanation:** No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations. + +**Example 2:** + +**Input:** s = "leetcode" + +**Output:** "" + +**Explanation:** "leetcode" has only characters so we cannot separate them by digits. + +**Example 3:** + +**Input:** s = "1229857369" + +**Output:** "" + +**Explanation:** "1229857369" has only digits so we cannot separate them by characters. + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of only lowercase English letters and/or digits. + +## Solution + +```kotlin +class Solution { + fun reformat(s: String): String { + val chars: MutableList = ArrayList() + val digits: MutableList = ArrayList() + for (c in s.toCharArray()) { + if (c in '0'..'9') { + digits.add(c) + } else { + chars.add(c) + } + } + if (Math.abs(digits.size - chars.size) > 1) { + return "" + } + var isDigit = digits.size > chars.size + val sb = StringBuilder() + for (i in s.indices) { + if (isDigit) { + sb.append(digits.removeAt(0)) + } else { + sb.append(chars.removeAt(0)) + } + isDigit = !isDigit + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1418_display_table_of_food_orders_in_a_restaurant/readme.md b/src/main/kotlin/g1401_1500/s1418_display_table_of_food_orders_in_a_restaurant/readme.md new file mode 100644 index 00000000..1257840b --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1418_display_table_of_food_orders_in_a_restaurant/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1418\. Display Table of Food Orders in a Restaurant + +Medium + +Given the array `orders`, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders. + +_Return the restaurant's “**display table**”_. The “**display table**” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. + +**Example 1:** + +**Input:** orders = \[\["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] + +**Output:** [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] + +**Explanation:** The displaying table looks like: + +**Table,Beef Burrito,Ceviche,Fried Chicken,Water** + +3 ,0 ,2 ,1 ,0 + +5 ,0 ,1 ,0 ,1 + +10 ,1 ,0 ,0 ,0 + +For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". + +For the table 5: Carla orders "Water" and "Ceviche". + +For the table 10: Corina orders "Beef Burrito". + +**Example 2:** + +**Input:** orders = \[\["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]] + +**Output:** [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] + +**Explanation:** + +For the table 1: Adam and Brianna order "Canadian Waffles". + +For the table 12: James, Ratesh and Amadeus order "Fried Chicken". + +**Example 3:** + +**Input:** orders = \[\["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] + +**Output:** [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]] + +**Constraints:** + +* `1 <= orders.length <= 5 * 10^4` +* `orders[i].length == 3` +* 1 <= customerNamei.length, foodItemi.length <= 20 +* customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character. +* tableNumberi is a valid integer between `1` and `500`. + +## Solution + +```kotlin +import java.util.TreeMap + +class Solution { + fun displayTable(orders: List>): List> { + val map = TreeMap>() + val dishSet: MutableSet = HashSet() + for (order in orders) { + val tableNumber = order[1].toInt() + val dishName = order[2] + dishSet.add(dishName) + map.putIfAbsent(tableNumber, HashMap()) + val dishCountMap = map[tableNumber]!! + if (!dishCountMap.containsKey(dishName)) { + dishCountMap[dishName] = 1 + } else { + dishCountMap[dishName] = dishCountMap[dishName]!! + 1 + } + } + val dishes: MutableList = ArrayList(dishSet) + dishes.sort() + dishes.add(0, "Table") + val result: MutableList> = ArrayList() + result.add(dishes) + for ((key) in map) { + val row: MutableList = ArrayList() + row.add("" + key) + for (i in 1 until dishes.size) { + if (map[key]!!.containsKey(dishes[i])) { + row.add(Integer.toString(map[key]!![dishes[i]]!!)) + } else { + row.add("0") + } + } + result.add(row) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1419_minimum_number_of_frogs_croaking/readme.md b/src/main/kotlin/g1401_1500/s1419_minimum_number_of_frogs_croaking/readme.md new file mode 100644 index 00000000..a246fcf0 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1419_minimum_number_of_frogs_croaking/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1419\. Minimum Number of Frogs Croaking + +Medium + +You are given the string `croakOfFrogs`, which represents a combination of the string `"croak"` from different frogs, that is, multiple frogs can croak at the same time, so multiple `"croak"` are mixed. + +_Return the minimum number of_ different _frogs to finish all the croaks in the given string._ + +A valid `"croak"` means a frog is printing five letters `'c'`, `'r'`, `'o'`, `'a'`, and `'k'` **sequentially**. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid `"croak"` return `-1`. + +**Example 1:** + +**Input:** croakOfFrogs = "croakcroak" + +**Output:** 1 + +**Explanation:** One frog yelling "croak**"** twice. + +**Example 2:** + +**Input:** croakOfFrogs = "crcoakroak" + +**Output:** 2 + +**Explanation:** The minimum number of frogs is two. The first frog could yell "**cr**c**oak**roak". The second frog could yell later "cr**c**oak**roak**". + +**Example 3:** + +**Input:** croakOfFrogs = "croakcrook" + +**Output:** -1 + +**Explanation:** The given string is an invalid combination of "croak**"** from different frogs. + +**Constraints:** + +* 1 <= croakOfFrogs.length <= 105 +* `croakOfFrogs` is either `'c'`, `'r'`, `'o'`, `'a'`, or `'k'`. + +## Solution + +```kotlin +class Solution { + fun minNumberOfFrogs(s: String): Int { + var ans = 0 + val f = IntArray(26) + for (i in 0 until s.length) { + f[s[i].code - 'a'.code]++ + if (s[i] == 'k' && checkEnough(f)) { + reduce(f) + } + if (!isValid(f)) { + return -1 + } + ans = Math.max(ans, getMax(f)) + } + return if (isEmpty(f)) ans else -1 + } + + private fun checkEnough(f: IntArray): Boolean { + return f['c'.code - 'a'.code] > 0 && f['r'.code - 'a'.code] > 0 && + f['o'.code - 'a'.code] > 0 && f[0] > 0 && f['k'.code - 'a'.code] > 0 + } + + fun reduce(f: IntArray) { + f['c'.code - 'a'.code]-- + f['r'.code - 'a'.code]-- + f['o'.code - 'a'.code]-- + f[0]-- + f['k'.code - 'a'.code]-- + } + + private fun getMax(f: IntArray): Int { + var max = 0 + for (v in f) { + max = Math.max(max, v) + } + return max + } + + private fun isEmpty(f: IntArray): Boolean { + for (v in f) { + if (v > 0) { + return false + } + } + return true + } + + private fun isValid(f: IntArray): Boolean { + if (f['r'.code - 'a'.code] > f['c'.code - 'a'.code]) { + return false + } + if (f['o'.code - 'a'.code] > f['r'.code - 'a'.code]) { + return false + } + return if (f[0] > f['o'.code - 'a'.code]) { + false + } else f['k'.code - 'a'.code] <= f[0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons/readme.md b/src/main/kotlin/g1401_1500/s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons/readme.md new file mode 100644 index 00000000..9fd86a49 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons/readme.md @@ -0,0 +1,82 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1420\. Build Array Where You Can Find The Maximum Exactly K Comparisons + +Hard + +You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers: + +![](https://assets.leetcode.com/uploads/2020/04/02/e.png) + +You should build the array arr which has the following properties: + +* `arr` has exactly `n` integers. +* `1 <= arr[i] <= m` where `(0 <= i < n)`. +* After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`. + +Return _the number of ways_ to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer **must be** computed modulo 109 + 7. + +**Example 1:** + +**Input:** n = 2, m = 3, k = 1 + +**Output:** 6 + +**Explanation:** The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3] + +**Example 2:** + +**Input:** n = 5, m = 2, k = 3 + +**Output:** 0 + +**Explanation:** There are no possible arrays that satisify the mentioned conditions. + +**Example 3:** + +**Input:** n = 9, m = 1, k = 1 + +**Output:** 1 + +**Explanation:** The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1] + +**Constraints:** + +* `1 <= n <= 50` +* `1 <= m <= 100` +* `0 <= k <= n` + +## Solution + +```kotlin +class Solution { + fun numOfArrays(n: Int, m: Int, k: Int): Int { + var ways = Array(m + 1) { LongArray(k + 1) } + var sums = Array(m + 1) { LongArray(k + 1) } + for (max in 1..m) { + ways[max][1] = 1 + sums[max][1] = ways[max][1] + sums[max - 1][1] + } + for (count in 2..n) { + val ways2 = Array(m + 1) { LongArray(k + 1) } + val sums2 = Array(m + 1) { LongArray(k + 1) } + for (max in 1..m) { + for (cost in 1..k) { + val noCost = max * ways[max][cost] % MOD + val newCost = sums[max - 1][cost - 1] + ways2[max][cost] = (noCost + newCost) % MOD + sums2[max][cost] = (sums2[max - 1][cost] + ways2[max][cost]) % MOD + } + } + ways = ways2 + sums = sums2 + } + return sums[m][k].toInt() + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1422_maximum_score_after_splitting_a_string/readme.md b/src/main/kotlin/g1401_1500/s1422_maximum_score_after_splitting_a_string/readme.md new file mode 100644 index 00000000..f674ab03 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1422_maximum_score_after_splitting_a_string/readme.md @@ -0,0 +1,73 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1422\. Maximum Score After Splitting a String + +Easy + +Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring). + +The score after splitting a string is the number of **zeros** in the **left** substring plus the number of **ones** in the **right** substring. + +**Example 1:** + +**Input:** s = "011101" + +**Output:** 5 + +**Explanation:** All possible ways of splitting s into two non-empty substrings are: + +left = "0" and right = "11101", score = 1 + 4 = 5 + +left = "01" and right = "1101", score = 1 + 3 = 4 + +left = "011" and right = "101", score = 1 + 2 = 3 + +left = "0111" and right = "01", score = 1 + 1 = 2 + +left = "01110" and right = "1", score = 2 + 1 = 3 + +**Example 2:** + +**Input:** s = "00111" + +**Output:** 5 + +**Explanation:** When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5 + +**Example 3:** + +**Input:** s = "1111" + +**Output:** 3 + +**Constraints:** + +* `2 <= s.length <= 500` +* The string `s` consists of characters `'0'` and `'1'` only. + +## Solution + +```kotlin +class Solution { + fun maxScore(s: String): Int { + var zeroes = if (s[0] == '0') 1 else 0 + var ones = 0 + for (i in 1 until s.length) { + if (s[i] == '1') { + ones++ + } + } + var maxScore = zeroes + ones + for (i in 1 until s.length - 1) { + if (s[i] == '0') { + zeroes++ + } else { + ones-- + } + maxScore = Math.max(maxScore, zeroes + ones) + } + return maxScore + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1423_maximum_points_you_can_obtain_from_cards/readme.md b/src/main/kotlin/g1401_1500/s1423_maximum_points_you_can_obtain_from_cards/readme.md new file mode 100644 index 00000000..b68a88cc --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1423_maximum_points_you_can_obtain_from_cards/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1423\. Maximum Points You Can Obtain from Cards + +Medium + +There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`. + +In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards. + +Your score is the sum of the points of the cards you have taken. + +Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain. + +**Example 1:** + +**Input:** cardPoints = [1,2,3,4,5,6,1], k = 3 + +**Output:** 12 + +**Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. + +**Example 2:** + +**Input:** cardPoints = [2,2,2], k = 2 + +**Output:** 4 + +**Explanation:** Regardless of which two cards you take, your score will always be 4. + +**Example 3:** + +**Input:** cardPoints = [9,7,7,9,7,7,9], k = 7 + +**Output:** 55 + +**Explanation:** You have to take all the cards. Your score is the sum of points of all cards. + +**Constraints:** + +* 1 <= cardPoints.length <= 105 +* 1 <= cardPoints[i] <= 104 +* `1 <= k <= cardPoints.length` + +## Solution + +```kotlin +class Solution { + fun maxScore(cardPoints: IntArray, k: Int): Int { + var currSum = 0 + var maxSum: Int + for (i in 0 until k) { + currSum += cardPoints[i] + } + if (k == cardPoints.size) { + return currSum + } + maxSum = currSum + var r = cardPoints.size - 1 + while (r >= cardPoints.size - k) { + currSum += cardPoints[r] - cardPoints[k + r - cardPoints.size] + maxSum = Math.max(currSum, maxSum) + r-- + } + return maxSum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1424_diagonal_traverse_ii/readme.md b/src/main/kotlin/g1401_1500/s1424_diagonal_traverse_ii/readme.md new file mode 100644 index 00000000..e489e876 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1424_diagonal_traverse_ii/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1424\. Diagonal Traverse II + +Medium + +Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png) + +**Input:** nums = \[\[1,2,3],[4,5,6],[7,8,9]] + +**Output:** [1,4,2,7,5,3,8,6,9] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png) + +**Input:** nums = \[\[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] + +**Output:** [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i].length <= 105 +* 1 <= sum(nums[i].length) <= 105 +* 1 <= nums[i][j] <= 105 + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Objects + +class Solution { + fun findDiagonalOrder(nums: List>): IntArray { + val ans: MutableList = ArrayList() + val queue = ArrayDeque>() + var pos = 0 + do { + if (pos < nums.size) { + queue.offerFirst(nums[pos].iterator()) + } + var sz = queue.size + while (--sz >= 0) { + val cur = queue.poll() + ans.add(Objects.requireNonNull(cur).next()) + if (cur.hasNext()) { + queue.offer(cur) + } + } + pos++ + } while (queue.isNotEmpty() || pos < nums.size) + return ans.stream().mapToInt { o: Int? -> o!! }.toArray() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1425_constrained_subsequence_sum/readme.md b/src/main/kotlin/g1401_1500/s1425_constrained_subsequence_sum/readme.md new file mode 100644 index 00000000..31f4003b --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1425_constrained_subsequence_sum/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1425\. Constrained Subsequence Sum + +Hard + +Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied. + +A _subsequence_ of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. + +**Example 1:** + +**Input:** nums = [10,2,-10,5,20], k = 2 + +**Output:** 37 + +**Explanation:** The subsequence is [10, 2, 5, 20]. + +**Example 2:** + +**Input:** nums = [-1,-2,-3], k = 1 + +**Output:** -1 + +**Explanation:** The subsequence must be non-empty, so we choose the largest number. + +**Example 3:** + +**Input:** nums = [10,-2,-10,-5,20], k = 2 + +**Output:** 23 + +**Explanation:** The subsequence is [10, -2, -5, 20]. + +**Constraints:** + +* 1 <= k <= nums.length <= 105 +* -104 <= nums[i] <= 104 + +## Solution + +```kotlin +import java.util.LinkedList + +class Solution { + fun constrainedSubsetSum(nums: IntArray, k: Int): Int { + val n = nums.size + var res = Int.MIN_VALUE + val mono = LinkedList() + for (i in 0 until n) { + var take = nums[i] + while (mono.isNotEmpty() && i - mono.first[0] > k) { + mono.removeFirst() + } + if (mono.isNotEmpty()) { + val mx = Math.max(0, mono.first[1]) + take += mx + } + while (mono.isNotEmpty() && take > mono.last[1]) { + mono.removeLast() + } + mono.add(intArrayOf(i, take)) + res = Math.max(res, take) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1431_kids_with_the_greatest_number_of_candies/readme.md b/src/main/kotlin/g1401_1500/s1431_kids_with_the_greatest_number_of_candies/readme.md new file mode 100644 index 00000000..c1fdd64a --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1431_kids_with_the_greatest_number_of_candies/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1431\. Kids With the Greatest Number of Candies + +Easy + +There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the ith kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. + +Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ ith _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_. + +Note that **multiple** kids can have the **greatest** number of candies. + +**Example 1:** + +**Input:** candies = [2,3,5,1,3], extraCandies = 3 + +**Output:** [true,true,true,false,true] + +**Explanation:** If you give all extraCandies to: +- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. +- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. +- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. +- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. +- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. + +**Example 2:** + +**Input:** candies = [4,2,1,1,2], extraCandies = 1 + +**Output:** [true,false,false,false,false] + +**Explanation:** There is only 1 extra candy. Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. + +**Example 3:** + +**Input:** candies = [12,1,12], extraCandies = 10 + +**Output:** [true,false,true] + +**Constraints:** + +* `n == candies.length` +* `2 <= n <= 100` +* `1 <= candies[i] <= 100` +* `1 <= extraCandies <= 50` + +## Solution + +```kotlin +class Solution { + fun kidsWithCandies(candies: IntArray, extraCandies: Int): List { + var max = 0 + for (i in candies) { + max = Math.max(max, i) + } + val result: MutableList = ArrayList() + for (candy in candies) { + result.add(candy + extraCandies >= max) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1432_max_difference_you_can_get_from_changing_an_integer/readme.md b/src/main/kotlin/g1401_1500/s1432_max_difference_you_can_get_from_changing_an_integer/readme.md new file mode 100644 index 00000000..be2d91c5 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1432_max_difference_you_can_get_from_changing_an_integer/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1432\. Max Difference You Can Get From Changing an Integer + +Medium + +You are given an integer `num`. You will apply the following steps exactly **two** times: + +* Pick a digit `x (0 <= x <= 9)`. +* Pick another digit `y (0 <= y <= 9)`. The digit `y` can be equal to `x`. +* Replace all the occurrences of `x` in the decimal representation of `num` by `y`. +* The new integer **cannot** have any leading zeros, also the new integer **cannot** be 0. + +Let `a` and `b` be the results of applying the operations to `num` the first and second times, respectively. + +Return _the max difference_ between `a` and `b`. + +**Example 1:** + +**Input:** num = 555 + +**Output:** 888 + +**Explanation:** The first time pick x = 5 and y = 9 and store the new integer in a. + +The second time pick x = 5 and y = 1 and store the new integer in b. + +We have now a = 999 and b = 111 and max difference = 888 + +**Example 2:** + +**Input:** num = 9 + +**Output:** 8 + +**Explanation:** The first time pick x = 9 and y = 9 and store the new integer in a. + +The second time pick x = 9 and y = 1 and store the new integer in b. + +We have now a = 9 and b = 1 and max difference = 8 + +**Constraints:** + +* `1 <= num <= 10`8 + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque + +@Suppress("NAME_SHADOWING") +class Solution { + fun maxDiff(num: Int): Int { + var num = num + val stack: Deque = ArrayDeque() + var xMax = 9 + val yMax = 9 + var xMin = 0 + var yMin = 0 + var min = 0 + var max = 0 + var areDigitsUnique = true + while (num != 0) { + if (stack.isNotEmpty() && num % 10 != stack.peek()) { + areDigitsUnique = false + } + stack.push(num % 10) + num /= 10 + if (stack.peek() != 9) { + xMax = stack.peek() + } + if (stack.peek() > 1) { + xMin = stack.peek() + } + } + if (areDigitsUnique || stack.peek() == xMin) { + // Handles no leading zeros/non zero constraints. + yMin = 1 + } + while (stack.isNotEmpty()) { + min = min * 10 + if (stack.peek() == xMin) yMin else stack.peek() + max = max * 10 + if (stack.peek() == xMax) yMax else stack.peek() + stack.pop() + } + return max - min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1433_check_if_a_string_can_break_another_string/readme.md b/src/main/kotlin/g1401_1500/s1433_check_if_a_string_can_break_another_string/readme.md new file mode 100644 index 00000000..08901145 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1433_check_if_a_string_can_break_another_string/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1433\. Check If a String Can Break Another String + +Medium + +Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. + +A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0` and `n-1`. + +**Example 1:** + +**Input:** s1 = "abc", s2 = "xya" + +**Output:** true + +**Explanation:** "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc". + +**Example 2:** + +**Input:** s1 = "abe", s2 = "acd" + +**Output:** false + +**Explanation:** All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa. + +**Example 3:** + +**Input:** s1 = "leetcodee", s2 = "interview" + +**Output:** true + +**Constraints:** + +* `s1.length == n` +* `s2.length == n` +* `1 <= n <= 10^5` +* All strings consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun checkIfCanBreak(s1: String, s2: String): Boolean { + if (s1.length == 1) { + return true + } + val count1 = IntArray(26) + val count2 = IntArray(26) + for (i in s1.length - 1 downTo 0) { + count1[s1[i].code - 'a'.code]++ + count2[s2[i].code - 'a'.code]++ + } + var isS1Greater = count1[25] >= count2[25] + var isS2Greater = count2[25] >= count1[25] + var i = 24 + while ((isS1Greater || isS2Greater) && i >= 0) { + count1[i] += count1[i + 1] + count2[i] += count2[i + 1] + isS1Greater = isS1Greater && count1[i] >= count2[i] + isS2Greater = isS2Greater && count2[i] >= count1[i] + i-- + } + return isS1Greater || isS2Greater + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1434_number_of_ways_to_wear_different_hats_to_each_other/readme.md b/src/main/kotlin/g1401_1500/s1434_number_of_ways_to_wear_different_hats_to_each_other/readme.md new file mode 100644 index 00000000..22864f11 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1434_number_of_ways_to_wear_different_hats_to_each_other/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1434\. Number of Ways to Wear Different Hats to Each Other + +Hard + +There are `n` people and `40` types of hats labeled from `1` to `40`. + +Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the ith person. + +Return _the number of ways that the `n` people wear different hats to each other_. + +Since the answer may be too large, return it modulo 109 + 7. + +**Example 1:** + +**Input:** hats = \[\[3,4],[4,5],[5]] + +**Output:** 1 + +**Explanation:** There is only one way to choose hats given the conditions. First person choose hat 3, Second person choose hat 4 and last one hat 5. + +**Example 2:** + +**Input:** hats = \[\[3,5,1],[3,5]] + +**Output:** 4 + +**Explanation:** There are 4 ways to choose hats: (3,5), (5,3), (1,3) and (1,5) + +**Example 3:** + +**Input:** hats = \[\[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] + +**Output:** 24 + +**Explanation:** Each person can choose hats labeled from 1 to 4. Number of Permutations of (1,2,3,4) = 24. + +**Constraints:** + +* `n == hats.length` +* `1 <= n <= 10` +* `1 <= hats[i].length <= 40` +* `1 <= hats[i][j] <= 40` +* `hats[i]` contains a list of **unique** integers. + +## Solution + +```kotlin +class Solution { + fun numberWays(hats: List>): Int { + val mod = 1000000007L + val size = hats.size + val possible = Array(size) { BooleanArray(41) } + for (i in 0 until size) { + for (j in hats[i]) { + possible[i][j] = true + } + } + val dp = LongArray(1 shl size) + dp[0] = 1 + for (i in 1..40) { + for (j in dp.size - 1 downTo 1) { + for (k in 0 until size) { + if (j shr k and 1 == 1 && possible[k][i]) { + dp[j] += dp[j xor (1 shl k)] + } + } + dp[j] %= mod + } + } + return dp[(1 shl size) - 1].toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1436_destination_city/readme.md b/src/main/kotlin/g1401_1500/s1436_destination_city/readme.md new file mode 100644 index 00000000..8339a561 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1436_destination_city/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1436\. Destination City + +Easy + +You are given the array `paths`, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. _Return the destination city, that is, the city without any path outgoing to another city._ + +It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. + +**Example 1:** + +**Input:** paths = \[\["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] + +**Output:** "Sao Paulo" + +**Explanation:** Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo". + +**Example 2:** + +**Input:** paths = \[\["B","C"],["D","B"],["C","A"]] + +**Output:** "A" + +**Explanation:** All possible trips are: + +"D" -> "B" -> "C" -> "A". + +"B" -> "C" -> "A". + +"C" -> "A". + +"A". Clearly the destination city is "A". + +**Example 3:** + +**Input:** paths = \[\["A","Z"]] + +**Output:** "Z" + +**Constraints:** + +* `1 <= paths.length <= 100` +* `paths[i].length == 2` +* 1 <= cityAi.length, cityBi.length <= 10 +* cityAi != cityBi +* All strings consist of lowercase and uppercase English letters and the space character. + +## Solution + +```kotlin +class Solution { + fun destCity(paths: List>): String { + val set: MutableSet = HashSet() + for (strings in paths) { + set.add(strings[0]) + } + for (path in paths) { + if (!set.contains(path[1])) { + return path[1] + } + } + return "" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1437_check_if_all_1s_are_at_least_length_k_places_away/readme.md b/src/main/kotlin/g1401_1500/s1437_check_if_all_1s_are_at_least_length_k_places_away/readme.md new file mode 100644 index 00000000..597834f6 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1437_check_if_all_1s_are_at_least_length_k_places_away/readme.md @@ -0,0 +1,54 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1437\. Check If All 1's Are at Least Length K Places Away + +Easy + +Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/04/15/sample_1_1791.png) + +**Input:** nums = [1,0,0,0,1,0,0,1], k = 2 + +**Output:** true + +**Explanation:** Each of the 1s are at least 2 places away from each other. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/04/15/sample_2_1791.png) + +**Input:** nums = [1,0,0,1,0,1], k = 2 + +**Output:** false + +**Explanation:** The second 1 and third 1 are only one apart from each other. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `0 <= k <= nums.length` +* `nums[i]` is `0` or `1` + +## Solution + +```kotlin +class Solution { + fun kLengthApart(nums: IntArray, k: Int): Boolean { + var last = -k - 1 + for (i in nums.indices) { + if (nums[i] == 1) { + last = if (i - last - 1 >= k) { + i + } else { + return false + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit/readme.md b/src/main/kotlin/g1401_1500/s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit/readme.md new file mode 100644 index 00000000..eca92353 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit/readme.md @@ -0,0 +1,94 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1438\. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit + +Medium + +Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ + +**Example 1:** + +**Input:** nums = [8,2,4,7], limit = 4 + +**Output:** 2 + +**Explanation:** All subarrays are: + +[8] with maximum absolute diff \|8-8\| = 0 <= 4. + +[8,2] with maximum absolute diff \|8-2\| = 6 > 4. + +[8,2,4] with maximum absolute diff \|8-2\| = 6 > 4. + +[8,2,4,7] with maximum absolute diff \|8-2\| = 6 > 4. + +[2] with maximum absolute diff \|2-2\| = 0 <= 4. + +[2,4] with maximum absolute diff \|2-4\| = 2 <= 4. + +[2,4,7] with maximum absolute diff \|2-7\| = 5 > 4. + +[4] with maximum absolute diff \|4-4\| = 0 <= 4. + +[4,7] with maximum absolute diff \|4-7\| = 3 <= 4. + +[7] with maximum absolute diff \|7-7\| = 0 <= 4. + +Therefore, the size of the longest subarray is 2. + +**Example 2:** + +**Input:** nums = [10,1,2,4,7,2], limit = 5 + +**Output:** 4 + +**Explanation:** The subarray [2,4,7,2] is the longest since the maximum absolute diff is \|2-7\| = 5 <= 5. + +**Example 3:** + +**Input:** nums = [4,2,2,2,4,4,2,2], limit = 0 + +**Output:** 3 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* 0 <= limit <= 109 + +## Solution + +```kotlin +import java.util.ArrayDeque + +class Solution { + fun longestSubarray(nums: IntArray, limit: Int): Int { + val maxQ = ArrayDeque() + val minQ = ArrayDeque() + var best = 0 + var left = 0 + for (right in nums.indices) { + while (maxQ.isNotEmpty() && nums[right] > nums[maxQ.peekLast()]) { + maxQ.removeLast() + } + maxQ.offerLast(right) + while (minQ.isNotEmpty() && nums[right] < nums[minQ.peekLast()]) { + minQ.removeLast() + } + minQ.offerLast(right) + while (nums[maxQ.peekFirst()] - nums[minQ.peekFirst()] > limit) { + if (maxQ.peekFirst() == left) { + maxQ.removeFirst() + } + if (minQ.peekFirst() == left) { + minQ.removeFirst() + } + left++ + } + best = Math.max(best, right - left + 1) + } + return best + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows/readme.md b/src/main/kotlin/g1401_1500/s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows/readme.md new file mode 100644 index 00000000..3ce13f44 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows/readme.md @@ -0,0 +1,97 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1439\. Find the Kth Smallest Sum of a Matrix With Sorted Rows + +Hard + +You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. + +You are allowed to choose **exactly one element** from each row to form an array. + +Return _the_ kth _smallest array sum among all possible arrays_. + +**Example 1:** + +**Input:** mat = \[\[1,3,11],[2,4,6]], k = 5 + +**Output:** 7 + +**Explanation:** Choosing one element from each row, the first k smallest sum are: [1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7. + +**Example 2:** + +**Input:** mat = \[\[1,3,11],[2,4,6]], k = 9 + +**Output:** 17 + +**Example 3:** + +**Input:** mat = \[\[1,10,10],[1,4,5],[2,3,6]], k = 7 + +**Output:** 9 + +**Explanation:** Choosing one element from each row, the first k smallest sum are: [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. + +**Constraints:** + +* `m == mat.length` +* `n == mat.length[i]` +* `1 <= m, n <= 40` +* `1 <= mat[i][j] <= 5000` +* 1 <= k <= min(200, nm) +* `mat[i]` is a non-decreasing array. + +## Solution + +```kotlin +import java.util.Objects +import java.util.TreeSet + +@Suppress("kotlin:S6510") +class Solution { + fun kthSmallest(mat: Array, k: Int): Int { + val treeSet = TreeSet( + Comparator { o1: IntArray, o2: IntArray -> + if (o1[0] != o2[0]) { + return@Comparator o1[0] - o2[0] + } else { + for (i in 1 until o1.size) { + if (o1[i] != o2[i]) { + return@Comparator o1[i] - o2[i] + } + } + return@Comparator 0 + } + } + ) + val m = mat.size + val n = mat[0].size + var sum = 0 + val entry = IntArray(m + 1) + for (ints in mat) { + sum += ints[0] + } + entry[0] = sum + treeSet.add(entry) + var count = 0 + while (count < k) { + val curr: IntArray = treeSet.pollFirst() as IntArray + count++ + if (count == k) { + return Objects.requireNonNull(curr)[0] + } + for (i in 0 until m) { + val next = Objects.requireNonNull(curr).copyOf(curr.size) + if (curr[i + 1] + 1 < n) { + next[0] -= mat[i][curr[i + 1]] + next[0] += mat[i][curr[i + 1] + 1] + next[i + 1]++ + treeSet.add(next) + } + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1441_build_an_array_with_stack_operations/readme.md b/src/main/kotlin/g1401_1500/s1441_build_an_array_with_stack_operations/readme.md new file mode 100644 index 00000000..46477486 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1441_build_an_array_with_stack_operations/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1441\. Build an Array With Stack Operations + +Easy + +You are given an array `target` and an integer `n`. + +In each iteration, you will read a number from `list = [1, 2, 3, ..., n]`. + +Build the `target` array using the following operations: + +* `"Push"`: Reads a new element from the beginning list, and pushes it in the array. +* `"Pop"`: Deletes the last element of the array. +* If the target array is already built, stop reading more elements. + +Return _a list of the operations needed to build_ `target`. The test cases are generated so that the answer is **unique**. + +**Example 1:** + +**Input:** target = [1,3], n = 3 + +**Output:** ["Push","Push","Pop","Push"] + +**Explanation:** + +Read number 1 and automatically push in the array -> [1] + +Read number 2 and automatically push in the array then Pop it -> [1] + +Read number 3 and automatically push in the array -> [1,3] + +**Example 2:** + +**Input:** target = [1,2,3], n = 3 + +**Output:** ["Push","Push","Push"] + +**Example 3:** + +**Input:** target = [1,2], n = 4 + +**Output:** ["Push","Push"] + +**Explanation:** You only need to read the first 2 numbers and stop. + +**Constraints:** + +* `1 <= target.length <= 100` +* `1 <= n <= 100` +* `1 <= target[i] <= n` +* `target` is strictly increasing. + +## Solution + +```kotlin +class Solution { + fun buildArray(target: IntArray, n: Int): List { + val result: MutableList = ArrayList() + val set: MutableSet = HashSet() + for (i in target) { + set.add(i) + } + val max = target[target.size - 1] + for (i in 1..n) { + if (!set.contains(i)) { + result.add("Push") + result.add("Pop") + } else { + result.add("Push") + } + if (i == max) { + break + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1442_count_triplets_that_can_form_two_arrays_of_equal_xor/readme.md b/src/main/kotlin/g1401_1500/s1442_count_triplets_that_can_form_two_arrays_of_equal_xor/readme.md new file mode 100644 index 00000000..e839cfdb --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1442_count_triplets_that_can_form_two_arrays_of_equal_xor/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1442\. Count Triplets That Can Form Two Arrays of Equal XOR + +Medium + +Given an array of integers `arr`. + +We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`. + +Let's define `a` and `b` as follows: + +* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]` +* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]` + +Note that **^** denotes the **bitwise-xor** operation. + +Return _the number of triplets_ (`i`, `j` and `k`) Where `a == b`. + +**Example 1:** + +**Input:** arr = [2,3,1,6,7] + +**Output:** 4 + +**Explanation:** The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4) + +**Example 2:** + +**Input:** arr = [1,1,1,1,1] + +**Output:** 10 + +**Constraints:** + +* `1 <= arr.length <= 300` +* 1 <= arr[i] <= 108 + +## Solution + +```kotlin +class Solution { + fun countTriplets(arr: IntArray): Int { + var count = 0 + for (i in arr.indices) { + var xor = arr[i] + for (k in i + 1 until arr.size) { + xor = xor xor arr[k] + if (xor == 0) { + count += k - i + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1443_minimum_time_to_collect_all_apples_in_a_tree/readme.md b/src/main/kotlin/g1401_1500/s1443_minimum_time_to_collect_all_apples_in_a_tree/readme.md new file mode 100644 index 00000000..3c948863 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1443_minimum_time_to_collect_all_apples_in_a_tree/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1443\. Minimum Time to Collect All Apples in a Tree + +Medium + +Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex._ + +The edges of the undirected tree are given in the array `edges`, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png) + +**Input:** n = 7, edges = \[\[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] + +**Output:** 8 + +**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png) + +**Input:** n = 7, edges = \[\[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] + +**Output:** 6 + +**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. + +**Example 3:** + +**Input:** n = 7, edges = \[\[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false] + +**Output:** 0 + +**Constraints:** + +* 1 <= n <= 105 +* `edges.length == n - 1` +* `edges[i].length == 2` +* 0 <= ai < bi <= n - 1 +* fromi < toi +* `hasApple.length == n` + +## Solution + +```kotlin +@Suppress("UNUSED_PARAMETER") +class Solution { + fun minTime(n: Int, edges: Array, hasApple: List): Int { + val visited: MutableSet = HashSet() + val graph: MutableMap> = HashMap() + for (edge in edges) { + val vertexA = edge[0] + val vertexB = edge[1] + graph.computeIfAbsent(vertexA) { _: Int? -> ArrayList() }.add(vertexB) + graph.computeIfAbsent(vertexB) { _: Int? -> ArrayList() }.add(vertexA) + } + visited.add(0) + val steps = helper(graph, hasApple, 0, visited) + return if (steps > 0) steps - 2 else 0 + } + + private fun helper( + graph: Map>, + hasApple: List, + node: Int, + visited: MutableSet + ): Int { + var steps = 0 + for (child in graph.getOrDefault(node, mutableListOf())) { + if (visited.contains(child)) { + continue + } else { + visited.add(child) + } + steps += helper(graph, hasApple, child, visited) + } + return if (steps > 0) { + steps + 2 + } else if (java.lang.Boolean.TRUE == hasApple[node]) { + 2 + } else { + 0 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1444_number_of_ways_of_cutting_a_pizza/readme.md b/src/main/kotlin/g1401_1500/s1444_number_of_ways_of_cutting_a_pizza/readme.md new file mode 100644 index 00000000..084e216b --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1444_number_of_ways_of_cutting_a_pizza/readme.md @@ -0,0 +1,129 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1444\. Number of Ways of Cutting a Pizza + +Hard + +Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. + +For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. + +_Return the number of ways of cutting the pizza such that each piece contains **at least** one apple. _Since the answer can be a huge number, return this modulo 10^9 + 7. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/04/23/ways_to_cut_apple_1.png)** + +**Input:** pizza = ["A..","AAA","..."], k = 3 + +**Output:** 3 + +**Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple. + +**Example 2:** + +**Input:** pizza = ["A..","AA.","..."], k = 3 + +**Output:** 1 + +**Example 3:** + +**Input:** pizza = ["A..","A..","..."], k = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= rows, cols <= 50` +* `rows == pizza.length` +* `cols == pizza[i].length` +* `1 <= k <= 10` +* `pizza` consists of characters `'A'` and `'.'` only. + +## Solution + +```kotlin +class Solution { + fun ways(pizza: Array, k: Int): Int { + if (pizza.isEmpty()) { + return 0 + } + val m = pizza.size + val n = pizza[0].length + val prefix = Array(m + 1) { IntArray(n + 1) } + for (i in 0 until m) { + for (j in 0 until n) { + prefix[i + 1][j + 1] = ( + ( + prefix[i][j + 1] + + prefix[i + 1][j] + + if (pizza[i][j] == 'A') 1 else 0 + ) - + prefix[i][j] + ) + } + } + val dp = Array(m) { Array(n) { IntArray(k) } } + for (i in 0 until m) { + for (j in 0 until n) { + for (s in 0 until k) { + dp[i][j][s] = -1 + } + } + } + return dfs(0, 0, m, n, k - 1, prefix, dp) + } + + private fun dfs( + m: Int, + n: Int, + temp1: Int, + temp2: Int, + k: Int, + prefix: Array, + dp: Array> + ): Int { + if (k == 0) { + return if (hasApple(prefix, m, n, temp1 - 1, temp2 - 1)) 1 else 0 + } + if (dp[m][n][k] != -1) { + return dp[m][n][k] + } + var local = 0 + for (x in m until temp1 - 1) { + local = ( + ( + local + + (if (hasApple(prefix, m, n, x, temp2 - 1)) 1 else 0) * + dfs(x + 1, n, temp1, temp2, k - 1, prefix, dp) + ) % + K_MOD + ) + } + for (y in n until temp2 - 1) { + local = ( + ( + local + + (if (hasApple(prefix, m, n, temp1 - 1, y)) 1 else 0) * + dfs(m, y + 1, temp1, temp2, k - 1, prefix, dp) + ) % + K_MOD + ) + } + dp[m][n][k] = local + return dp[m][n][k] + } + + private fun hasApple(prefix: Array, x1: Int, y1: Int, x2: Int, y2: Int): Boolean { + return ( + prefix[x2 + 1][y2 + 1] - prefix[x1][y2 + 1] - prefix[x2 + 1][y1] + prefix[x1][y1] + > 0 + ) + } + + companion object { + private const val K_MOD = (1e9 + 7).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1446_consecutive_characters/readme.md b/src/main/kotlin/g1401_1500/s1446_consecutive_characters/readme.md new file mode 100644 index 00000000..7091669c --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1446_consecutive_characters/readme.md @@ -0,0 +1,51 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1446\. Consecutive Characters + +Easy + +The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. + +Given a string `s`, return _the **power** of_ `s`. + +**Example 1:** + +**Input:** s = "leetcode" + +**Output:** 2 + +**Explanation:** The substring "ee" is of length 2 with the character 'e' only. + +**Example 2:** + +**Input:** s = "abbcccddddeeeeedcba" + +**Output:** 5 + +**Explanation:** The substring "eeeee" is of length 5 with the character 'e' only. + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maxPower(s: String): Int { + var max = 0 + var i = 0 + while (i < s.length) { + val start = i + while (i + 1 < s.length && s[i] == s[i + 1]) { + i++ + } + max = Math.max(max, i - start + 1) + i++ + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1447_simplified_fractions/readme.md b/src/main/kotlin/g1401_1500/s1447_simplified_fractions/readme.md new file mode 100644 index 00000000..c2268673 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1447_simplified_fractions/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1447\. Simplified Fractions + +Medium + +Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. + +**Example 1:** + +**Input:** n = 2 + +**Output:** ["1/2"] + +**Explanation:** "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2. + +**Example 2:** + +**Input:** n = 3 + +**Output:** ["1/2","1/3","2/3"] + +**Example 3:** + +**Input:** n = 4 + +**Output:** ["1/2","1/3","1/4","2/3","3/4"] + +**Explanation:** "2/4" is not a simplified fraction because it can be simplified to "1/2". + +**Constraints:** + +* `1 <= n <= 100` + +## Solution + +```kotlin +class Solution { + fun simplifiedFractions(n: Int): List { + val result: MutableList = ArrayList() + if (n == 1) { + return result + } + val str = StringBuilder() + for (denom in 2..n) { + for (num in 1 until denom) { + if (checkGCD(num, denom) == 1) { + result.add(str.append(num).append("/").append(denom).toString()) + } + str.setLength(0) + } + } + return result + } + + private fun checkGCD(a: Int, b: Int): Int { + if (a < b) { + return checkGCD(b, a) + } + return if (a == b || a % b == 0 || b == 1) { + b + } else checkGCD(a % b, b) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1448_count_good_nodes_in_binary_tree/readme.md b/src/main/kotlin/g1401_1500/s1448_count_good_nodes_in_binary_tree/readme.md new file mode 100644 index 00000000..ec5e5dde --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1448_count_good_nodes_in_binary_tree/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1448\. Count Good Nodes in Binary Tree + +Medium + +Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. + +Return the number of **good** nodes in the binary tree. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png)** + +**Input:** root = [3,1,4,3,null,1,5] + +**Output:** 4 + +**Explanation:** Nodes in blue are **good**. + +Root Node (3) is always a good node. + +Node 4 -> (3,4) is the maximum value in the path starting from the root. + +Node 5 -> (3,4,5) is the maximum value in the path + +Node 3 -> (3,1,3) is the maximum value in the path. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png)** + +**Input:** root = [3,3,null,4,2] + +**Output:** 3 + +**Explanation:** Node 2 -> (3, 3, 2) is not good, because "3" is higher than it. + +**Example 3:** + +**Input:** root = [1] + +**Output:** 1 + +**Explanation:** Root is considered as **good**. + +**Constraints:** + +* The number of nodes in the binary tree is in the range `[1, 10^5]`. +* Each node's value is between `[-10^4, 10^4]`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +@Suppress("NAME_SHADOWING") +class Solution { + private var count = 0 + + private fun traverse(root: TreeNode?, max: Int) { + var max = max + if (root == null) { + return + } + if (root.`val` >= max) { + count += 1 + max = root.`val` + } + traverse(root.left, max) + traverse(root.right, max) + } + + fun goodNodes(root: TreeNode?): Int { + traverse(root, Int.MIN_VALUE) + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1449_form_largest_integer_with_digits_that_add_up_to_target/readme.md b/src/main/kotlin/g1401_1500/s1449_form_largest_integer_with_digits_that_add_up_to_target/readme.md new file mode 100644 index 00000000..a92efc13 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1449_form_largest_integer_with_digits_that_add_up_to_target/readme.md @@ -0,0 +1,117 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1449\. Form Largest Integer With Digits That Add up to Target + +Hard + +Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: + +* The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). +* The total cost used must be equal to `target`. +* The integer does not have `0` digits. + +Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return `"0"`. + +**Example 1:** + +**Input:** cost = [4,3,2,5,6,7,2,5,5], target = 9 + +**Output:** "7772" + +**Explanation:** The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2\*3+ 3\*1 = 9. You could also paint "977", but "7772" is the largest number. + +**Digit cost** + +1 -> 4 + +2 -> 3 + +3 -> 2 + +4 -> 5 + +5 -> 6 + +6 -> 7 + +7 -> 2 + +8 -> 5 + +9 -> 5 + +**Example 2:** + +**Input:** cost = [7,6,5,5,5,6,8,7,8], target = 12 + +**Output:** "85" + +**Explanation:** The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12. + +**Example 3:** + +**Input:** cost = [2,4,6,2,4,6,4,4,4], target = 5 + +**Output:** "0" + +**Explanation:** It is impossible to paint any integer with total cost equal to target. + +**Constraints:** + +* `cost.length == 9` +* `1 <= cost[i], target <= 5000` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun largestNumber(cost: IntArray, target: Int): String { + var target = target + val dp = Array(10) { IntArray(5001) } + dp[0].fill(-1) + for (i in 1..cost.size) { + for (j in 1..target) { + if (cost[i - 1] > j) { + dp[i][j] = dp[i - 1][j] + } else { + var temp = if (dp[i - 1][j - cost[i - 1]] == -1) -1 else 1 + dp[i - 1][j - cost[i - 1]] + val t = if (dp[i][j - cost[i - 1]] == -1) -1 else 1 + dp[i][j - cost[i - 1]] + temp = if (t != -1 && temp == -1) { + t + } else { + Math.max(t, temp) + } + if (dp[i - 1][j] == -1) { + dp[i][j] = temp + } else if (temp == -1) { + dp[i][j] = dp[i - 1][j] + } else { + dp[i][j] = Math.max(temp, dp[i - 1][j]) + } + } + } + } + if (dp[9][target] == -1) { + return "0" + } + var i = 9 + val result = StringBuilder() + while (target > 0) { + if (target - cost[i - 1] >= 0 && dp[i][target - cost[i - 1]] + 1 == dp[i][target] || + ( + target - cost[i - 1] >= 0 && + dp[i - 1][target - cost[i - 1]] + 1 == dp[i][target] + ) + ) { + result.append(i) + target -= cost[i - 1] + } else { + i-- + } + } + return result.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1401_1500/s1450_number_of_students_doing_homework_at_a_given_time/readme.md b/src/main/kotlin/g1401_1500/s1450_number_of_students_doing_homework_at_a_given_time/readme.md new file mode 100644 index 00000000..3ad51132 --- /dev/null +++ b/src/main/kotlin/g1401_1500/s1450_number_of_students_doing_homework_at_a_given_time/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1450\. Number of Students Doing Homework at a Given Time + +Easy + +Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. + +The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. + +Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students where `queryTime` lays in the interval `[startTime[i], endTime[i]]` inclusive. + +**Example 1:** + +**Input:** startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 + +**Output:** 1 + +**Explanation:** We have 3 students where: + +The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. + +The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. + +The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4. + +**Example 2:** + +**Input:** startTime = [4], endTime = [4], queryTime = 4 + +**Output:** 1 + +**Explanation:** The only student was doing their homework at the queryTime. + +**Constraints:** + +* `startTime.length == endTime.length` +* `1 <= startTime.length <= 100` +* `1 <= startTime[i] <= endTime[i] <= 1000` +* `1 <= queryTime <= 1000` + +## Solution + +```kotlin +class Solution { + fun busyStudent(startTime: IntArray, endTime: IntArray, queryTime: Int): Int { + var count = 0 + for (i in startTime.indices) { + if (startTime[i] <= queryTime && endTime[i] >= queryTime) { + count++ + } + } + return count + } +} +``` \ No newline at end of file