Skip to content

Commit be05987

Browse files
authored
Added tasks 1094-1450
1 parent 977ebdd commit be05987

File tree

132 files changed

+11376
-684
lines changed
  • src/main/kotlin
    • g1001_1100
    • g1101_1200
    • g1301_1400
      • s1301_number_of_paths_with_max_score
      • s1302_deepest_leaves_sum
      • s1304_find_n_unique_integers_sum_up_to_zero
      • s1305_all_elements_in_two_binary_search_trees
      • s1306_jump_game_iii
      • s1307_verbal_arithmetic_puzzle
      • s1309_decrypt_string_from_alphabet_to_integer_mapping
      • s1310_xor_queries_of_a_subarray
      • s1311_get_watched_videos_by_your_friends
      • s1312_minimum_insertion_steps_to_make_a_string_palindrome
      • s1313_decompress_run_length_encoded_list
      • s1314_matrix_block_sum
      • s1315_sum_of_nodes_with_even_valued_grandparent
      • s1316_distinct_echo_substrings
      • s1317_convert_integer_to_the_sum_of_two_no_zero_integers
      • s1318_minimum_flips_to_make_a_or_b_equal_to_c
      • s1319_number_of_operations_to_make_network_connected
      • s1320_minimum_distance_to_type_a_word_using_two_fingers
      • s1323_maximum_69_number
      • s1324_print_words_vertically
      • s1325_delete_leaves_with_a_given_value
      • s1326_minimum_number_of_taps_to_open_to_water_a_garden
      • s1328_break_a_palindrome
      • s1329_sort_the_matrix_diagonally
      • s1330_reverse_subarray_to_maximize_array_value
      • s1331_rank_transform_of_an_array
      • s1332_remove_palindromic_subsequences
      • s1333_filter_restaurants_by_vegan_friendly_price_and_distance
      • s1334_find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance
      • s1335_minimum_difficulty_of_a_job_schedule
      • s1337_the_k_weakest_rows_in_a_matrix
      • s1338_reduce_array_size_to_the_half
      • s1339_maximum_product_of_splitted_binary_tree
      • s1340_jump_game_v
      • s1342_number_of_steps_to_reduce_a_number_to_zero
      • s1343_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold
      • s1344_angle_between_hands_of_a_clock
      • s1345_jump_game_iv
      • s1346_check_if_n_and_its_double_exist
      • s1347_minimum_number_of_steps_to_make_two_strings_anagram
      • s1348_tweet_counts_per_frequency
      • s1349_maximum_students_taking_exam
      • s1351_count_negative_numbers_in_a_sorted_matrix
      • s1352_product_of_the_last_k_numbers
      • s1353_maximum_number_of_events_that_can_be_attended
      • s1354_construct_target_array_with_multiple_sums
      • s1356_sort_integers_by_the_number_of_1_bits
      • s1357_apply_discount_every_n_orders
      • s1358_number_of_substrings_containing_all_three_characters
      • s1359_count_all_valid_pickup_and_delivery_options
      • s1360_number_of_days_between_two_dates
      • s1361_validate_binary_tree_nodes
      • s1362_closest_divisors
      • s1363_largest_multiple_of_three
      • s1365_how_many_numbers_are_smaller_than_the_current_number
      • s1366_rank_teams_by_votes
      • s1367_linked_list_in_binary_tree
      • s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid
      • s1370_increasing_decreasing_string
      • s1371_find_the_longest_substring_containing_vowels_in_even_counts
      • s1372_longest_zigzag_path_in_a_binary_tree
      • s1373_maximum_sum_bst_in_binary_tree
      • s1374_generate_a_string_with_characters_that_have_odd_counts
      • s1375_number_of_times_binary_string_is_prefix_aligned
      • s1376_time_needed_to_inform_all_employees
      • s1377_frog_position_after_t_seconds
      • s1379_find_a_corresponding_node_of_a_binary_tree_in_a_clone_of_that_tree
      • s1380_lucky_numbers_in_a_matrix
      • s1381_design_a_stack_with_increment_operation
      • s1382_balance_a_binary_search_tree
      • s1383_maximum_performance_of_a_team
      • s1385_find_the_distance_value_between_two_arrays
      • s1386_cinema_seat_allocation
      • s1387_sort_integers_by_the_power_value
      • s1388_pizza_with_3n_slices
      • s1389_create_target_array_in_the_given_order
      • s1390_four_divisors
      • s1391_check_if_there_is_a_valid_path_in_a_grid
      • s1392_longest_happy_prefix
      • s1393_capital_gainloss
      • s1394_find_lucky_integer_in_an_array
      • s1395_count_number_of_teams
      • s1396_design_underground_system
      • s1397_find_all_good_strings
      • s1399_count_largest_group
      • s1400_construct_k_palindrome_strings
    • g1401_1500
      • s1401_circle_and_rectangle_overlapping
      • s1402_reducing_dishes
      • s1403_minimum_subsequence_in_non_increasing_order
      • s1404_number_of_steps_to_reduce_a_number_in_binary_representation_to_one
      • s1405_longest_happy_string
      • s1406_stone_game_iii
      • s1407_top_travellers
      • s1408_string_matching_in_an_array
      • s1409_queries_on_a_permutation_with_key
      • s1410_html_entity_parser
      • s1411_number_of_ways_to_paint_n_3_grid
      • s1413_minimum_value_to_get_positive_step_by_step_sum
      • s1414_find_the_minimum_number_of_fibonacci_numbers_whose_sum_is_k
      • s1415_the_k_th_lexicographical_string_of_all_happy_strings_of_length_n
      • s1416_restore_the_array
      • s1417_reformat_the_string
      • s1418_display_table_of_food_orders_in_a_restaurant
      • s1419_minimum_number_of_frogs_croaking
      • s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons
      • s1422_maximum_score_after_splitting_a_string
      • s1423_maximum_points_you_can_obtain_from_cards
      • s1424_diagonal_traverse_ii
      • s1425_constrained_subsequence_sum
      • s1431_kids_with_the_greatest_number_of_candies
      • s1432_max_difference_you_can_get_from_changing_an_integer
      • s1433_check_if_a_string_can_break_another_string
      • s1434_number_of_ways_to_wear_different_hats_to_each_other
      • s1436_destination_city
      • s1437_check_if_all_1s_are_at_least_length_k_places_away
      • s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit
      • s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows
      • s1441_build_an_array_with_stack_operations
      • s1442_count_triplets_that_can_form_two_arrays_of_equal_xor
      • s1443_minimum_time_to_collect_all_apples_in_a_tree
      • s1444_number_of_ways_of_cutting_a_pizza
      • s1446_consecutive_characters
      • s1447_simplified_fractions
      • s1448_count_good_nodes_in_binary_tree
      • s1449_form_largest_integer_with_digits_that_add_up_to_target
      • s1450_number_of_students_doing_homework_at_a_given_time

Some content is hidden

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

132 files changed

+11376
-684
lines changed

README.md

Lines changed: 827 additions & 682 deletions
Large diffs are not rendered by default.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
## 1094\. Car Pooling
5+
6+
Medium
7+
8+
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
9+
10+
You are given the integer `capacity` and an array `trips` where <code>trips[i] = [numPassengers<sub>i</sub>, from<sub>i</sub>, to<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> trip has <code>numPassengers<sub>i</sub></code> passengers and the locations to pick them up and drop them off are <code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> respectively. The locations are given as the number of kilometers due east from the car's initial location.
11+
12+
Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_.
13+
14+
**Example 1:**
15+
16+
**Input:** trips = \[\[2,1,5],[3,3,7]], capacity = 4
17+
18+
**Output:** false
19+
20+
**Example 2:**
21+
22+
**Input:** trips = \[\[2,1,5],[3,3,7]], capacity = 5
23+
24+
**Output:** true
25+
26+
**Constraints:**
27+
28+
* `1 <= trips.length <= 1000`
29+
* `trips[i].length == 3`
30+
* <code>1 <= numPassengers<sub>i</sub> <= 100</code>
31+
* <code>0 <= from<sub>i</sub> < to<sub>i</sub> <= 1000</code>
32+
* <code>1 <= capacity <= 10<sup>5</sup></code>
33+
34+
## Solution
35+
36+
```kotlin
37+
@Suppress("NAME_SHADOWING")
38+
class Solution {
39+
fun carPooling(trips: Array<IntArray>, capacity: Int): Boolean {
40+
var capacity = capacity
41+
val stops = IntArray(1001)
42+
for (t in trips) {
43+
stops[t[1]] += t[0]
44+
stops[t[2]] -= t[0]
45+
}
46+
var i = 0
47+
while (capacity >= 0 && i < 1001) {
48+
capacity -= stops[i]
49+
++i
50+
}
51+
return capacity >= 0
52+
}
53+
}
54+
```
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+
## 1095\. Find in Mountain Array
5+
6+
Hard
7+
8+
_(This problem is an **interactive problem**.)_
9+
10+
You may recall that an array `arr` is a **mountain array** if and only if:
11+
12+
* `arr.length >= 3`
13+
* There exists some `i` with `0 < i < arr.length - 1` such that:
14+
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
15+
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
16+
17+
Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`.
18+
19+
**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface:
20+
21+
* `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed).
22+
* `MountainArray.length()` returns the length of the array.
23+
24+
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.
25+
26+
**Example 1:**
27+
28+
**Input:** array = [1,2,3,4,5,3,1], target = 3
29+
30+
**Output:** 2
31+
32+
**Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
33+
34+
**Example 2:**
35+
36+
**Input:** array = [0,1,2,4,2,1], target = 3
37+
38+
**Output:** -1
39+
40+
**Explanation:** 3 does not exist in `the array,` so we return -1.
41+
42+
**Constraints:**
43+
44+
* <code>3 <= mountain_arr.length() <= 10<sup>4</sup></code>
45+
* <code>0 <= target <= 10<sup>9</sup></code>
46+
* <code>0 <= mountain_arr.get(index) <= 10<sup>9</sup></code>
47+
48+
## Solution
49+
50+
```kotlin
51+
/*
52+
* // This is MountainArray's API interface.
53+
* // You should not implement it, or speculate about its implementation
54+
* class MountainArray {
55+
* fun get(index: Int): Int {}
56+
* fun length(): Int {}
57+
* }
58+
*/
59+
60+
class Solution {
61+
fun findInMountainArray(target: Int, mountainArr: MountainArray): Int {
62+
val peakIndex = findPeak(mountainArr)
63+
if (target == mountainArr.get(peakIndex)) {
64+
return peakIndex
65+
}
66+
val leftResult = findInPeakLeft(target, peakIndex, mountainArr)
67+
return if (leftResult != -1) {
68+
leftResult
69+
} else findInPeakRight(target, peakIndex, mountainArr)
70+
}
71+
72+
private fun findPeak(mountainArray: MountainArray): Int {
73+
val len: Int = mountainArray.length()
74+
var left = 0
75+
var right = len - 1
76+
while (left < right) {
77+
val mid = left + (right - left) / 2
78+
if (mountainArray.get(mid) < mountainArray.get(mid + 1)) {
79+
left = mid + 1
80+
} else {
81+
right = mid
82+
}
83+
}
84+
return left
85+
}
86+
87+
private fun findInPeakLeft(target: Int, peakIndex: Int, mountainArray: MountainArray): Int {
88+
var leftIndex = 0
89+
var rightIndex = peakIndex - 1
90+
while (leftIndex < rightIndex) {
91+
val midIndex = leftIndex + (rightIndex - leftIndex) / 2
92+
if (target > mountainArray.get(midIndex)) {
93+
leftIndex = midIndex + 1
94+
} else {
95+
rightIndex = midIndex
96+
}
97+
}
98+
return if (target == mountainArray.get(leftIndex)) leftIndex else -1
99+
}
100+
101+
private fun findInPeakRight(target: Int, peakIndex: Int, mountainArray: MountainArray): Int {
102+
var leftIndex = peakIndex + 1
103+
var rightIndex: Int = mountainArray.length() - 1
104+
while (leftIndex < rightIndex) {
105+
val midIndex = leftIndex + (rightIndex - leftIndex) / 2
106+
if (target < mountainArray.get(midIndex)) {
107+
leftIndex = midIndex + 1
108+
} else {
109+
rightIndex = midIndex
110+
}
111+
}
112+
return if (target == mountainArray.get(leftIndex)) leftIndex else -1
113+
}
114+
}
115+
```
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
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+
## 1096\. Brace Expansion II
5+
6+
Hard
7+
8+
Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
9+
10+
The grammar can best be understood through simple examples:
11+
12+
* Single letters represent a singleton set containing that word.
13+
* `R("a") = {"a"}`
14+
* `R("w") = {"w"}`
15+
* When we take a comma-delimited list of two or more expressions, we take the union of possibilities.
16+
* `R("{a,b,c}") = {"a","b","c"}`
17+
* `R("{ {a,b},{b,c}}") = {"a","b","c"}` (notice the final set only contains each word at most once)
18+
* 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.
19+
* `R("{a,b}{c,d}") = {"ac","ad","bc","bd"}`
20+
* `R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}`
21+
22+
Formally, the three rules for our grammar:
23+
24+
* For every lowercase letter `x`, we have `R(x) = {x}`.
25+
* For expressions <code>e<sub>1</sub>, e<sub>2</sub>, ... , e<sub>k</sub></code> with `k >= 2`, we have <code>R({e<sub>1</sub>, e<sub>2</sub>, ...}) = R(e<sub>1</sub>) ∪ R(e<sub>2</sub>) ∪ ...</code>
26+
* For expressions <code>e<sub>1</sub></code> and <code>e<sub>2</sub></code>, we have <code>R(e<sub>1</sub> + e<sub>2</sub>) = {a + b for (a, b) in R(e<sub>1</sub>) × R(e<sub>2</sub>)}</code>, where `+` denotes concatenation, and `×` denotes the cartesian product.
27+
28+
Given an expression representing a set of words under the given grammar, return _the sorted list of words that the expression represents_.
29+
30+
**Example 1:**
31+
32+
**Input:** expression = "{a,b}{c,{d,e}}"
33+
34+
**Output:** ["ac","ad","ae","bc","bd","be"]
35+
36+
**Example 2:**
37+
38+
**Input:** expression = "{ {a,z},a{b,c},{ab,z}}"
39+
40+
**Output:** ["a","ab","ac","z"]
41+
42+
**Explanation:** Each distinct word is written only once in the final answer.
43+
44+
**Constraints:**
45+
46+
* `1 <= expression.length <= 60`
47+
* `expression[i]` consists of `'{'`, `'}'`, `','`or lowercase English letters.
48+
* The given `expression` represents a set of words based on the grammar given in the description.
49+
50+
## Solution
51+
52+
```kotlin
53+
class Solution {
54+
fun braceExpansionII(expression: String): List<String> {
55+
val res = flatten(expression)
56+
val sorted: MutableList<String> = ArrayList(res)
57+
sorted.sort()
58+
return sorted
59+
}
60+
61+
private fun flatten(expression: String): Set<String> {
62+
val res: MutableSet<String> = HashSet()
63+
// A temp set to store cartesian product results.
64+
var curSet: MutableSet<String> = HashSet()
65+
var idx = 0
66+
while (idx < expression.length) {
67+
if (expression[idx] == '{') {
68+
// end will be the index of matching "}"
69+
val end = findClosingBrace(expression, idx)
70+
val set = flatten(expression.substring(idx + 1, end))
71+
curSet = concatenateSet(curSet, set)
72+
idx = end + 1
73+
} else if (Character.isLowerCase(expression[idx])) {
74+
// Create set with single element
75+
val set: Set<String> = HashSet(
76+
listOf(
77+
expression[idx].toString()
78+
)
79+
)
80+
curSet = concatenateSet(curSet, set)
81+
idx++
82+
} else if (expression[idx] == ',') {
83+
res.addAll(curSet)
84+
curSet.clear()
85+
idx++
86+
}
87+
}
88+
// Don't forget!
89+
res.addAll(curSet)
90+
return res
91+
}
92+
93+
private fun concatenateSet(set1: Set<String>, set2: Set<String>): MutableSet<String> {
94+
if (set1.isEmpty() || set2.isEmpty()) {
95+
return if (set2.isNotEmpty()) HashSet(set2) else HashSet(set1)
96+
}
97+
val res: MutableSet<String> = HashSet()
98+
for (s1 in set1) {
99+
for (s2 in set2) {
100+
res.add(s1 + s2)
101+
}
102+
}
103+
return res
104+
}
105+
106+
private fun findClosingBrace(expression: String, start: Int): Int {
107+
var count = 0
108+
var idx = start
109+
while (idx < expression.length) {
110+
if (expression[idx] == '{') {
111+
count++
112+
} else if (expression[idx] == '}') {
113+
count--
114+
}
115+
if (count == 0) {
116+
break
117+
}
118+
idx++
119+
}
120+
return idx
121+
}
122+
}
123+
```

src/main/kotlin/g1101_1200/s1106_parsing_a_boolean_expression/readme.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ class Solution {
6666
return res
6767
}
6868

69-
private operator fun not(): Boolean {
69+
private fun not(): Boolean {
7070
consume('!')
7171
return !group()[0]
7272
}
@@ -109,7 +109,7 @@ class Solution {
109109
}
110110

111111
private val isAtEnd: Boolean
112-
private get() = index >= source!!.length
112+
get() = index >= source!!.length
113113

114114
private fun advance() {
115115
if (isAtEnd) {

0 commit comments

Comments
 (0)