Skip to content

Commit 4a4a339

Browse files
authored
Added tasks 1801-2050
1 parent 35c1901 commit 4a4a339

File tree

189 files changed

+17182
-0
lines changed
  • src/main/kotlin
    • g1801_1900
      • s1801_number_of_orders_in_the_backlog
      • s1802_maximum_value_at_a_given_index_in_a_bounded_array
      • s1803_count_pairs_with_xor_in_a_range
      • s1805_number_of_different_integers_in_a_string
      • s1806_minimum_number_of_operations_to_reinitialize_a_permutation
      • s1807_evaluate_the_bracket_pairs_of_a_string
      • s1808_maximize_number_of_nice_divisors
      • s1812_determine_color_of_a_chessboard_square
      • s1813_sentence_similarity_iii
      • s1814_count_nice_pairs_in_an_array
      • s1815_maximum_number_of_groups_getting_fresh_donuts
      • s1816_truncate_sentence
      • s1817_finding_the_users_active_minutes
      • s1818_minimum_absolute_sum_difference
      • s1819_number_of_different_subsequences_gcds
      • s1822_sign_of_the_product_of_an_array
      • s1823_find_the_winner_of_the_circular_game
      • s1824_minimum_sideway_jumps
      • s1825_finding_mk_average
      • s1827_minimum_operations_to_make_the_array_increasing
      • s1828_queries_on_number_of_points_inside_a_circle
      • s1829_maximum_xor_for_each_query
      • s1830_minimum_number_of_operations_to_make_string_sorted
      • s1832_check_if_the_sentence_is_pangram
      • s1833_maximum_ice_cream_bars
      • s1834_single_threaded_cpu
      • s1835_find_xor_sum_of_all_pairs_bitwise_and
      • s1837_sum_of_digits_in_base_k
      • s1838_frequency_of_the_most_frequent_element
      • s1839_longest_substring_of_all_vowels_in_order
      • s1840_maximum_building_height
      • s1844_replace_all_digits_with_characters
      • s1845_seat_reservation_manager
      • s1846_maximum_element_after_decreasing_and_rearranging
      • s1847_closest_room
      • s1848_minimum_distance_to_the_target_element
      • s1849_splitting_a_string_into_descending_consecutive_values
      • s1850_minimum_adjacent_swaps_to_reach_the_kth_smallest_number
      • s1851_minimum_interval_to_include_each_query
      • s1854_maximum_population_year
      • s1855_maximum_distance_between_a_pair_of_values
      • s1856_maximum_subarray_min_product
      • s1857_largest_color_value_in_a_directed_graph
      • s1859_sorting_the_sentence
      • s1860_incremental_memory_leak
      • s1861_rotating_the_box
      • s1862_sum_of_floored_pairs
      • s1863_sum_of_all_subset_xor_totals
      • s1864_minimum_number_of_swaps_to_make_the_binary_string_alternating
      • s1865_finding_pairs_with_a_certain_sum
      • s1866_number_of_ways_to_rearrange_sticks_with_k_sticks_visible
      • s1869_longer_contiguous_segments_of_ones_than_zeros
      • s1870_minimum_speed_to_arrive_on_time
      • s1871_jump_game_vii
      • s1872_stone_game_viii
      • s1873_calculate_special_bonus
      • s1876_substrings_of_size_three_with_distinct_characters
      • s1877_minimize_maximum_pair_sum_in_array
      • s1878_get_biggest_three_rhombus_sums_in_a_grid
      • s1879_minimum_xor_sum_of_two_arrays
      • s1880_check_if_word_equals_summation_of_two_words
      • s1881_maximum_value_after_insertion
      • s1882_process_tasks_using_servers
      • s1883_minimum_skips_to_arrive_at_meeting_on_time
      • s1884_egg_drop_with_2_eggs_and_n_floors
      • s1886_determine_whether_matrix_can_be_obtained_by_rotation
      • s1887_reduction_operations_to_make_the_array_elements_equal
      • s1888_minimum_number_of_flips_to_make_the_binary_string_alternating
      • s1889_minimum_space_wasted_from_packaging
      • s1890_the_latest_login_in_2020
      • s1893_check_if_all_the_integers_in_a_range_are_covered
      • s1894_find_the_student_that_will_replace_the_chalk
      • s1895_largest_magic_square
      • s1896_minimum_cost_to_change_the_final_value_of_expression
      • s1897_redistribute_characters_to_make_all_strings_equal
      • s1898_maximum_number_of_removable_characters
      • s1899_merge_triplets_to_form_target_triplet
      • s1900_the_earliest_and_latest_rounds_where_players_compete
    • g1901_2000
      • s1901_find_a_peak_element_ii
      • s1903_largest_odd_number_in_string
      • s1904_the_number_of_full_rounds_you_have_played
      • s1905_count_sub_islands
      • s1906_minimum_absolute_difference_queries
      • s1907_count_salary_categories
      • s1909_remove_one_element_to_make_the_array_strictly_increasing
      • s1910_remove_all_occurrences_of_a_substring
      • s1911_maximum_alternating_subsequence_sum
      • s1912_design_movie_rental_system
      • s1913_maximum_product_difference_between_two_pairs
      • s1914_cyclically_rotating_a_grid
      • s1915_number_of_wonderful_substrings
      • s1916_count_ways_to_build_rooms_in_an_ant_colony
      • s1920_build_array_from_permutation
      • s1921_eliminate_maximum_number_of_monsters
      • s1922_count_good_numbers
      • s1923_longest_common_subpath
      • s1925_count_square_sum_triples
      • s1926_nearest_exit_from_entrance_in_maze
      • s1927_sum_game
      • s1928_minimum_cost_to_reach_destination_in_time
      • s1929_concatenation_of_array
      • s1930_unique_length_3_palindromic_subsequences
      • s1931_painting_a_grid_with_three_different_colors
      • s1932_merge_bsts_to_create_single_bst
      • s1934_confirmation_rate
      • s1935_maximum_number_of_words_you_can_type
      • s1936_add_minimum_number_of_rungs
      • s1937_maximum_number_of_points_with_cost
      • s1938_maximum_genetic_difference_query
      • s1941_check_if_all_characters_have_equal_number_of_occurrences
      • s1942_the_number_of_the_smallest_unoccupied_chair
      • s1943_describe_the_painting
      • s1944_number_of_visible_people_in_a_queue
      • s1945_sum_of_digits_of_string_after_convert
      • s1946_largest_number_after_mutating_substring
      • s1947_maximum_compatibility_score_sum
      • s1948_delete_duplicate_folders_in_system
      • s1952_three_divisors
      • s1953_maximum_number_of_weeks_for_which_you_can_work
      • s1954_minimum_garden_perimeter_to_collect_enough_apples
      • s1955_count_number_of_special_subsequences
      • s1957_delete_characters_to_make_fancy_string
      • s1959_minimum_total_space_wasted_with_k_resizing_operations
      • s1960_maximum_product_of_the_length_of_two_palindromic_substrings
      • s1961_check_if_string_is_a_prefix_of_array
      • s1962_remove_stones_to_minimize_the_total
      • s1963_minimum_number_of_swaps_to_make_the_string_balanced
      • s1964_find_the_longest_valid_obstacle_course_at_each_position
      • s1965_employees_with_missing_information
      • s1967_number_of_strings_that_appear_as_substrings_in_word
      • s1968_array_with_elements_not_equal_to_average_of_neighbors
      • s1969_minimum_non_zero_product_of_the_array_elements
      • s1970_last_day_where_you_can_still_cross
      • s1971_find_if_path_exists_in_graph
      • s1974_minimum_time_to_type_word_using_special_typewriter
      • s1975_maximum_matrix_sum
      • s1976_number_of_ways_to_arrive_at_destination
      • s1977_number_of_ways_to_separate_numbers
      • s1979_find_greatest_common_divisor_of_array
      • s1980_find_unique_binary_string
      • s1981_minimize_the_difference_between_target_and_chosen_elements
      • s1982_find_array_given_subset_sums
      • s1984_minimum_difference_between_highest_and_lowest_of_k_scores
      • s1985_find_the_kth_largest_integer_in_the_array
      • s1986_minimum_number_of_work_sessions_to_finish_the_tasks
      • s1987_number_of_unique_good_subsequences
      • s1991_find_the_middle_index_in_array
      • s1992_find_all_groups_of_farmland
      • s1993_operations_on_tree
      • s1994_the_number_of_good_subsets
      • s1995_count_special_quadruplets
      • s1996_the_number_of_weak_characters_in_the_game
      • s1997_first_day_where_you_have_been_in_all_the_rooms
      • s1998_gcd_sort_of_an_array
      • s2000_reverse_prefix_of_word
    • g2001_2100
      • s2011_final_value_of_variable_after_performing_operations
      • s2012_sum_of_beauty_in_the_array
      • s2013_detect_squares
      • s2014_longest_subsequence_repeated_k_times
      • s2016_maximum_difference_between_increasing_elements
      • s2017_grid_game
      • s2018_check_if_word_can_be_placed_in_crossword
      • s2019_the_score_of_students_solving_math_expression
      • s2022_convert_1d_array_into_2d_array
      • s2023_number_of_pairs_of_strings_with_concatenation_equal_to_target
      • s2024_maximize_the_confusion_of_an_exam
      • s2025_maximum_number_of_ways_to_partition_an_array
      • s2027_minimum_moves_to_convert_string
      • s2028_find_missing_observations
      • s2029_stone_game_ix
      • s2030_smallest_k_length_subsequence_with_occurrences_of_a_letter
      • s2032_two_out_of_three
      • s2033_minimum_operations_to_make_a_uni_value_grid
      • s2034_stock_price_fluctuation
      • s2035_partition_array_into_two_arrays_to_minimize_sum_difference
      • s2037_minimum_number_of_moves_to_seat_everyone
      • s2038_remove_colored_pieces_if_both_neighbors_are_the_same_color
      • s2039_the_time_when_the_network_becomes_idle
      • s2040_kth_smallest_product_of_two_sorted_arrays
      • s2042_check_if_numbers_are_ascending_in_a_sentence
      • s2043_simple_bank_system
      • s2044_count_number_of_maximum_bitwise_or_subsets
      • s2045_second_minimum_time_to_reach_destination
      • s2047_number_of_valid_words_in_a_sentence
      • s2048_next_greater_numerically_balanced_number
      • s2049_count_nodes_with_the_highest_score
      • s2050_parallel_courses_iii

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

189 files changed

+17182
-0
lines changed

README.md

Lines changed: 205 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](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)
3+
4+
## 1801\. Number of Orders in the Backlog
5+
6+
Medium
7+
8+
You are given a 2D integer array `orders`, where each <code>orders[i] = [price<sub>i</sub>, amount<sub>i</sub>, orderType<sub>i</sub>]</code> denotes that <code>amount<sub>i</sub></code> orders have been placed of type <code>orderType<sub>i</sub></code> at the price <code>price<sub>i</sub></code>. The <code>orderType<sub>i</sub></code> is:
9+
10+
* `0` if it is a batch of `buy` orders, or
11+
* `1` if it is a batch of `sell` orders.
12+
13+
Note that `orders[i]` represents a batch of <code>amount<sub>i</sub></code> independent orders with the same price and order type. All orders represented by `orders[i]` will be placed before all orders represented by `orders[i+1]` for all valid `i`.
14+
15+
There is a **backlog** that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
16+
17+
* If the order is a `buy` order, you look at the `sell` order with the **smallest** price in the backlog. If that `sell` order's price is **smaller than or equal to** the current `buy` order's price, they will match and be executed, and that `sell` order will be removed from the backlog. Else, the `buy` order is added to the backlog.
18+
* Vice versa, if the order is a `sell` order, you look at the `buy` order with the **largest** price in the backlog. If that `buy` order's price is **larger than or equal to** the current `sell` order's price, they will match and be executed, and that `buy` order will be removed from the backlog. Else, the `sell` order is added to the backlog.
19+
20+
Return _the total **amount** of orders in the backlog after placing all the orders from the input_. Since this number can be large, return it **modulo** <code>10<sup>9</sup> + 7</code>.
21+
22+
**Example 1:**
23+
24+
![](https://assets.leetcode.com/uploads/2021/03/11/ex1.png)
25+
26+
**Input:** orders = \[\[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
27+
28+
**Output:** 6
29+
30+
**Explanation:** Here is what happens with the orders:
31+
32+
- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.
33+
34+
- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.
35+
36+
- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.
37+
38+
- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3<sup>rd</sup> order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4<sup>th</sup> order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.
39+
40+
**Example 2:**
41+
42+
![](https://assets.leetcode.com/uploads/2021/03/11/ex2.png)
43+
44+
**Input:** orders = \[\[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
45+
46+
**Output:** 999999984
47+
48+
**Explanation:** Here is what happens with the orders:
49+
50+
- 10<sup>9</sup> orders of type sell with price 7 are placed. There are no buy orders, so the 10<sup>9</sup> orders are added to the backlog.
51+
52+
- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.
53+
54+
- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (10<sup>9</sup> + 7).
55+
56+
**Constraints:**
57+
58+
* <code>1 <= orders.length <= 10<sup>5</sup></code>
59+
* `orders[i].length == 3`
60+
* <code>1 <= price<sub>i</sub>, amount<sub>i</sub> <= 10<sup>9</sup></code>
61+
* <code>orderType<sub>i</sub></code> is either `0` or `1`.
62+
63+
## Solution
64+
65+
```kotlin
66+
import java.util.PriorityQueue
67+
68+
class Solution {
69+
private class Order(var price: Int, var qty: Int)
70+
71+
fun getNumberOfBacklogOrders(orders: Array<IntArray>): Int {
72+
val sell = PriorityQueue(
73+
compareBy { a: Order -> a.price }
74+
)
75+
val buy = PriorityQueue { a: Order, b: Order -> b.price - a.price }
76+
for (order in orders) {
77+
val price = order[0]
78+
var amount = order[1]
79+
val type = order[2]
80+
if (type == 0) {
81+
while (sell.isNotEmpty() && sell.peek().price <= price && amount > 0) {
82+
val ord = sell.peek()
83+
val toRemove = amount.coerceAtMost(ord.qty)
84+
ord.qty -= toRemove
85+
amount -= toRemove
86+
if (ord.qty == 0) {
87+
sell.poll()
88+
}
89+
}
90+
if (amount > 0) {
91+
buy.add(Order(price, amount))
92+
}
93+
} else {
94+
while (buy.isNotEmpty() && buy.peek().price >= price && amount > 0) {
95+
val ord = buy.peek()
96+
val toRemove = amount.coerceAtMost(ord.qty)
97+
ord.qty -= toRemove
98+
amount -= toRemove
99+
if (ord.qty == 0) {
100+
buy.poll()
101+
}
102+
}
103+
if (amount > 0) {
104+
sell.add(Order(price, amount))
105+
}
106+
}
107+
}
108+
var sellCount: Long = 0
109+
for (ord in sell) {
110+
sellCount += ord.qty.toLong()
111+
}
112+
var buyCount: Long = 0
113+
for (ord in buy) {
114+
buyCount += ord.qty.toLong()
115+
}
116+
val total = sellCount + buyCount
117+
return (total % 1000000007L).toInt()
118+
}
119+
}
120+
```
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](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)
3+
4+
## 1802\. Maximum Value at a Given Index in a Bounded Array
5+
6+
Medium
7+
8+
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions:
9+
10+
* `nums.length == n`
11+
* `nums[i]` is a **positive** integer where `0 <= i < n`.
12+
* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`.
13+
* The sum of all the elements of `nums` does not exceed `maxSum`.
14+
* `nums[index]` is **maximized**.
15+
16+
Return `nums[index]` _of the constructed array_.
17+
18+
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
19+
20+
**Example 1:**
21+
22+
**Input:** n = 4, index = 2, maxSum = 6
23+
24+
**Output:** 2
25+
26+
**Explanation:** nums = [1,2,**2**,1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].
27+
28+
**Example 2:**
29+
30+
**Input:** n = 6, index = 1, maxSum = 10
31+
32+
**Output:** 3
33+
34+
**Constraints:**
35+
36+
* <code>1 <= n <= maxSum <= 10<sup>9</sup></code>
37+
* `0 <= index < n`
38+
39+
## Solution
40+
41+
```kotlin
42+
class Solution {
43+
private fun isPossible(n: Int, index: Int, maxSum: Int, value: Int): Boolean {
44+
val leftValue = (value - index).coerceAtLeast(0)
45+
val rightValue = (value - (n - 1 - index)).coerceAtLeast(0)
46+
val sumBefore = (value + leftValue).toLong() * (value - leftValue + 1) / 2
47+
val sumAfter = (value + rightValue).toLong() * (value - rightValue + 1) / 2
48+
return sumBefore + sumAfter - value <= maxSum
49+
}
50+
51+
fun maxValue(n: Int, index: Int, maxSum: Int): Int {
52+
var left = 0
53+
var right = maxSum - n
54+
while (left < right) {
55+
val middle = (left + right + 1) / 2
56+
if (isPossible(n, index, maxSum - n, middle)) {
57+
left = middle
58+
} else {
59+
right = middle - 1
60+
}
61+
}
62+
return left + 1
63+
}
64+
}
65+
```
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](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)
3+
4+
## 1803\. Count Pairs With XOR in a Range
5+
6+
Hard
7+
8+
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_.
9+
10+
A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [1,4,2,7], low = 2, high = 6
15+
16+
**Output:** 6
17+
18+
**Explanation:** All nice pairs (i, j) are as follows:
19+
20+
- (0, 1): nums[0] XOR nums[1] = 5
21+
22+
- (0, 2): nums[0] XOR nums[2] = 3
23+
24+
- (0, 3): nums[0] XOR nums[3] = 6
25+
26+
- (1, 2): nums[1] XOR nums[2] = 6
27+
28+
- (1, 3): nums[1] XOR nums[3] = 3
29+
30+
- (2, 3): nums[2] XOR nums[3] = 5
31+
32+
**Example 2:**
33+
34+
**Input:** nums = [9,8,4,2,1], low = 5, high = 14
35+
36+
**Output:** 8
37+
38+
**Explanation:** All nice pairs (i, j) are as follows:
39+
40+
- (0, 2): nums[0] XOR nums[2] = 13
41+
42+
- (0, 3): nums[0] XOR nums[3] = 11
43+
44+
- (0, 4): nums[0] XOR nums[4] = 8
45+
46+
- (1, 2): nums[1] XOR nums[2] = 12
47+
48+
- (1, 3): nums[1] XOR nums[3] = 10
49+
50+
- (1, 4): nums[1] XOR nums[4] = 9
51+
52+
- (2, 3): nums[2] XOR nums[3] = 6
53+
54+
- (2, 4): nums[2] XOR nums[4] = 5
55+
56+
**Constraints:**
57+
58+
* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
59+
* <code>1 <= nums[i] <= 2 * 10<sup>4</sup></code>
60+
* <code>1 <= low <= high <= 2 * 10<sup>4</sup></code>
61+
62+
## Solution
63+
64+
```kotlin
65+
class Solution {
66+
fun countPairs(nums: IntArray, low: Int, high: Int): Int {
67+
val root = Trie()
68+
var pairsCount = 0
69+
for (num in nums) {
70+
val pairsCountHigh = countPairsWhoseXorLessThanX(num, root, high + 1)
71+
val pairsCountLow = countPairsWhoseXorLessThanX(num, root, low)
72+
pairsCount += pairsCountHigh - pairsCountLow
73+
root.insertNumber(num)
74+
}
75+
return pairsCount
76+
}
77+
78+
private fun countPairsWhoseXorLessThanX(num: Int, root: Trie, x: Int): Int {
79+
var pairs = 0
80+
var curr: Trie? = root
81+
var i = 14
82+
while (i >= 0 && curr != null) {
83+
val numIthBit = num shr i and 1
84+
val xIthBit = x shr i and 1
85+
if (xIthBit == 1) {
86+
if (curr.child[numIthBit] != null) {
87+
pairs += curr.child[numIthBit]!!.count
88+
}
89+
curr = curr.child[1 - numIthBit]
90+
} else {
91+
curr = curr.child[numIthBit]
92+
}
93+
i--
94+
}
95+
return pairs
96+
}
97+
98+
private class Trie {
99+
var child: Array<Trie?> = arrayOfNulls(2)
100+
var count: Int = 0
101+
102+
fun insertNumber(num: Int) {
103+
var curr = this
104+
for (i in 14 downTo 0) {
105+
val ithBit = num shr i and 1
106+
if (curr.child[ithBit] == null) {
107+
curr.child[ithBit] = Trie()
108+
}
109+
curr.child[ithBit]!!.count++
110+
curr = curr.child[ithBit]!!
111+
}
112+
}
113+
}
114+
}
115+
```
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](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)
3+
4+
## 1805\. Number of Different Integers in a String
5+
6+
Easy
7+
8+
You are given a string `word` that consists of digits and lowercase English letters.
9+
10+
You will replace every non-digit character with a space. For example, `"a123bc34d8ef34"` will become `" 123 34 8 34"`. Notice that you are left with some integers that are separated by at least one space: `"123"`, `"34"`, `"8"`, and `"34"`.
11+
12+
Return _the number of **different** integers after performing the replacement operations on_ `word`.
13+
14+
Two integers are considered different if their decimal representations **without any leading zeros** are different.
15+
16+
**Example 1:**
17+
18+
**Input:** word = "a123bc34d8ef34"
19+
20+
**Output:** 3
21+
22+
**Explanation:** The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
23+
24+
**Example 2:**
25+
26+
**Input:** word = "leet1234code234"
27+
28+
**Output:** 2
29+
30+
**Example 3:**
31+
32+
**Input:** word = "a1b01c001"
33+
34+
**Output:** 1
35+
36+
**Explanation:** The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values.
37+
38+
**Constraints:**
39+
40+
* `1 <= word.length <= 1000`
41+
* `word` consists of digits and lowercase English letters.
42+
43+
## Solution
44+
45+
```kotlin
46+
@Suppress("NAME_SHADOWING")
47+
class Solution {
48+
fun numDifferentIntegers(word: String): Int {
49+
val ints: MutableSet<String> = HashSet()
50+
val chars = word.toCharArray()
51+
var start = -1
52+
var stop = 0
53+
for (i in chars.indices) {
54+
if (chars[i] in '0'..'9') {
55+
if (start == -1) {
56+
start = i
57+
}
58+
stop = i
59+
} else if (start != -1) {
60+
ints.add(extractInt(chars, start, stop))
61+
start = -1
62+
}
63+
}
64+
if (start != -1) {
65+
ints.add(extractInt(chars, start, stop))
66+
}
67+
return ints.size
68+
}
69+
70+
private fun extractInt(chrs: CharArray, start: Int, stop: Int): String {
71+
var start = start
72+
val stb = StringBuilder()
73+
while (start <= stop && chrs[start] == '0') {
74+
start++
75+
}
76+
if (start >= stop) {
77+
stb.append(chrs[stop])
78+
} else {
79+
while (start <= stop) {
80+
stb.append(chrs[start++])
81+
}
82+
}
83+
return stb.toString()
84+
}
85+
}
86+
```

0 commit comments

Comments
 (0)