Skip to content

Commit fed737a

Browse files
authored
Added tasks 2857-2900
1 parent b8b71e5 commit fed737a

File tree

47 files changed

+3026
-5
lines changed
  • src/main/kotlin/g2801_2900
    • s2815_max_pair_sum_in_an_array
    • s2827_number_of_beautiful_integers_in_the_range
    • s2829_determine_the_minimum_sum_of_a_k_avoiding_array
    • s2835_minimum_operations_to_form_subsequence_with_target_sum
    • s2842_count_k_subsequences_of_a_string_with_maximum_beauty
    • s2846_minimum_edge_weight_equilibrium_queries_in_a_tree
    • s2855_minimum_right_shifts_to_sort_the_array
    • s2857_count_pairs_of_points_with_distance_k
    • s2858_minimum_edge_reversals_so_every_node_is_reachable
    • s2859_sum_of_values_at_indices_with_k_set_bits
    • s2860_happy_students
    • s2861_maximum_number_of_alloys
    • s2862_maximum_element_sum_of_a_complete_subset_of_indices
    • s2864_maximum_odd_binary_number
    • s2865_beautiful_towers_i
    • s2866_beautiful_towers_ii
    • s2867_count_valid_paths_in_a_tree
    • s2869_minimum_operations_to_collect_elements
    • s2870_minimum_number_of_operations_to_make_array_empty
    • s2871_split_array_into_maximum_number_of_subarrays
    • s2872_maximum_number_of_k_divisible_components
    • s2873_maximum_value_of_an_ordered_triplet_i
    • s2874_maximum_value_of_an_ordered_triplet_ii
    • s2875_minimum_size_subarray_in_infinite_array
    • s2876_count_visited_nodes_in_a_directed_graph
    • s2877_create_a_dataframe_from_list
    • s2878_get_the_size_of_a_dataframe
    • s2879_display_the_first_three_rows
    • s2880_select_data
    • s2881_create_a_new_column
    • s2882_drop_duplicate_rows
    • s2883_drop_missing_data
    • s2884_modify_columns
    • s2885_rename_columns
    • s2886_change_data_type
    • s2887_fill_missing_data
    • s2888_reshape_data_concatenate
    • s2889_reshape_data_pivot
    • s2890_reshape_data_melt
    • s2891_method_chaining
    • s2894_divisible_and_non_divisible_sums_difference
    • s2895_minimum_processing_time
    • s2896_apply_operations_to_make_two_strings_equal
    • s2897_apply_operations_on_array_to_maximize_sum_of_squares
    • s2899_last_visited_integers
    • s2900_longest_unequal_adjacent_groups_subsequence_i

Some content is hidden

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

47 files changed

+3026
-5
lines changed

README.md

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,7 +1154,7 @@
11541154
| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 271 | 77.17
11551155
| 0026 |[Remove Duplicates from Sorted Array](src/main/kotlin/g0001_0100/s0026_remove_duplicates_from_sorted_array)| Easy | Top_Interview_Questions, Array, Two_Pointers | 249 | 67.38
11561156
| 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, Big_O_Time_O(n)_Space_O(1) | 189 | 99.37
1157-
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45
1157+
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45
11581158

11591159
#### Udemy Famous Algorithm
11601160

@@ -1406,7 +1406,7 @@
14061406
|-|-|-|-|-|-
14071407
| 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Big_O_Time_O(N)_Space_O(1) | 344 | 83.63
14081408
| 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, Big_O_Time_O(n)_Space_O(1) | 460 | 51.25
1409-
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45
1409+
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45
14101410

14111411
#### Day 2 Array
14121412

@@ -1680,7 +1680,7 @@
16801680
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- -->
16811681
|-|-|-|-|-|-
16821682
| 0082 |[Remove Duplicates from Sorted List II](src/main/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii)| Medium | Two_Pointers, Linked_List | 166 | 89.47
1683-
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45
1683+
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45
16841684

16851685
#### Day 4 Two Pointers
16861686

@@ -1816,6 +1816,45 @@
18161816

18171817
| # | Title | Difficulty | Tag | Time, ms | Time, %
18181818
|------|----------------|-------------|-------------|----------|--------
1819+
| 2900 |[Longest Unequal Adjacent Groups Subsequence I](src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i)| Medium | Array, String, Dynamic_Programming, Greedy | 294 | 100.00
1820+
| 2899 |[Last Visited Integers](src/main/kotlin/g2801_2900/s2899_last_visited_integers)| Easy | Array, String, Simulation | 209 | 72.73
1821+
| 2897 |[Apply Operations on Array to Maximize Sum of Squares](src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares)| Hard | Array, Hash_Table, Greedy, Bit_Manipulation | 572 | 100.00
1822+
| 2896 |[Apply Operations to Make Two Strings Equal](src/main/kotlin/g2801_2900/s2896_apply_operations_to_make_two_strings_equal)| Medium | String, Dynamic_Programming | 181 | 66.67
1823+
| 2895 |[Minimum Processing Time](src/main/kotlin/g2801_2900/s2895_minimum_processing_time)| Medium | Array, Sorting, Greedy | 662 | 80.00
1824+
| 2894 |[Divisible and Non-divisible Sums Difference](src/main/kotlin/g2801_2900/s2894_divisible_and_non_divisible_sums_difference)| Easy | Math | 135 | 76.92
1825+
| 2891 |[Method Chaining](src/main/kotlin/g2801_2900/s2891_method_chaining)| Easy || 412 | 99.23
1826+
| 2890 |[Reshape Data: Melt](src/main/kotlin/g2801_2900/s2890_reshape_data_melt)| Easy || 446 | 97.89
1827+
| 2889 |[Reshape Data: Pivot](src/main/kotlin/g2801_2900/s2889_reshape_data_pivot)| Easy || 416 | 99.87
1828+
| 2888 |[Reshape Data: Concatenate](src/main/kotlin/g2801_2900/s2888_reshape_data_concatenate)| Easy || 441 | 96.26
1829+
| 2887 |[Fill Missing Data](src/main/kotlin/g2801_2900/s2887_fill_missing_data)| Easy || 404 | 97.11
1830+
| 2886 |[Change Data Type](src/main/kotlin/g2801_2900/s2886_change_data_type)| Easy || 421 | 94.57
1831+
| 2885 |[Rename Columns](src/main/kotlin/g2801_2900/s2885_rename_columns)| Easy || 467 | 68.13
1832+
| 2884 |[Modify Columns](src/main/kotlin/g2801_2900/s2884_modify_columns)| Easy || 401 | 96.35
1833+
| 2883 |[Drop Missing Data](src/main/kotlin/g2801_2900/s2883_drop_missing_data)| Easy || 429 | 94.97
1834+
| 2882 |[Drop Duplicate Rows](src/main/kotlin/g2801_2900/s2882_drop_duplicate_rows)| Easy || 405 | 97.36
1835+
| 2881 |[Create a New Column](src/main/kotlin/g2801_2900/s2881_create_a_new_column)| Easy || 437 | 81.98
1836+
| 2880 |[Select Data](src/main/kotlin/g2801_2900/s2880_select_data)| Easy || 428 | 94.99
1837+
| 2879 |[Display the First Three Rows](src/main/kotlin/g2801_2900/s2879_display_the_first_three_rows)| Easy || 406 | 96.44
1838+
| 2878 |[Get the Size of a DataFrame](src/main/kotlin/g2801_2900/s2878_get_the_size_of_a_dataframe)| Easy || 413 | 94.68
1839+
| 2877 |[Create a DataFrame from List](src/main/kotlin/g2801_2900/s2877_create_a_dataframe_from_list)| Easy || 406 | 82.57
1840+
| 2876 |[Count Visited Nodes in a Directed Graph](src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph)| Hard | Dynamic_Programming, Graph, Memoization | 922 | 100.00
1841+
| 2875 |[Minimum Size Subarray in Infinite Array](src/main/kotlin/g2801_2900/s2875_minimum_size_subarray_in_infinite_array)| Medium | Array, Hash_Table, Prefix_Sum, Sliding_Window | 372 | 100.00
1842+
| 2874 |[Maximum Value of an Ordered Triplet II](src/main/kotlin/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii)| Medium | Array | 508 | 100.00
1843+
| 2873 |[Maximum Value of an Ordered Triplet I](src/main/kotlin/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i)| Easy | Array | 157 | 94.12
1844+
| 2872 |[Maximum Number of K-Divisible Components](src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components)| Hard | Dynamic_Programming, Depth_First_Search, Tree | 780 | 100.00
1845+
| 2871 |[Split Array Into Maximum Number of Subarrays](src/main/kotlin/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays)| Medium | Array, Greedy, Bit_Manipulation | 490 | 100.00
1846+
| 2870 |[Minimum Number of Operations to Make Array Empty](src/main/kotlin/g2801_2900/s2870_minimum_number_of_operations_to_make_array_empty)| Medium | Array, Hash_Table, Greedy, Counting | 503 | 80.00
1847+
| 2869 |[Minimum Operations to Collect Elements](src/main/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements)| Easy | Array, Hash_Table | 156 | 100.00
1848+
| 2867 |[Count Valid Paths in a Tree](src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree)| Hard | Dynamic_Programming, Math, Depth_First_Search, Tree, Number_Theory | 793 | 100.00
1849+
| 2866 |[Beautiful Towers II](src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii)| Medium | Array, Stack, Monotonic_Stack | 676 | 85.71
1850+
| 2865 |[Beautiful Towers I](src/main/kotlin/g2801_2900/s2865_beautiful_towers_i)| Medium | Array, Stack, Monotonic_Stack | 232 | 75.00
1851+
| 2864 |[Maximum Odd Binary Number](src/main/kotlin/g2801_2900/s2864_maximum_odd_binary_number)| Easy | String, Math, Greedy | 176 | 90.91
1852+
| 2862 |[Maximum Element-Sum of a Complete Subset of Indices](src/main/kotlin/g2801_2900/s2862_maximum_element_sum_of_a_complete_subset_of_indices)| Hard | Array, Math, Number_Theory | 259 | 100.00
1853+
| 2861 |[Maximum Number of Alloys](src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys)| Medium | Array, Binary_Search | 289 | 100.00
1854+
| 2860 |[Happy Students](src/main/kotlin/g2801_2900/s2860_happy_students)| Medium | Array, Sorting, Enumeration | 512 | 100.00
1855+
| 2859 |[Sum of Values at Indices With K Set Bits](src/main/kotlin/g2801_2900/s2859_sum_of_values_at_indices_with_k_set_bits)| Easy | Array, Bit_Manipulation | 177 | 100.00
1856+
| 2858 |[Minimum Edge Reversals So Every Node Is Reachable](src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable)| Hard | Dynamic_Programming, Depth_First_Search, Breadth_First_Search, Graph | 1161 | 100.00
1857+
| 2857 |[Count Pairs of Points With Distance k](src/main/kotlin/g2801_2900/s2857_count_pairs_of_points_with_distance_k)| Medium | Array, Hash_Table, Bit_Manipulation | 1212 | 100.00
18191858
| 2856 |[Minimum Array Length After Pair Removals](src/main/kotlin/g2801_2900/s2856_minimum_array_length_after_pair_removals)| Medium | Array, Hash_Table, Greedy, Binary_Search, Two_Pointers, Counting | 647 | 100.00
18201859
| 2855 |[Minimum Right Shifts to Sort the Array](src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array)| Easy | Array | 169 | 75.00
18211860
| 2851 |[String Transformation](src/main/kotlin/g2801_2900/s2851_string_transformation)| Hard | String, Dynamic_Programming, Math, String_Matching | 377 | 100.00
@@ -4085,7 +4124,7 @@
40854124
| 0018 |[4Sum](src/main/kotlin/g0001_0100/s0018_4sum)| Medium | Array, Sorting, Two_Pointers | 229 | 98.59
40864125
| 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, Algorithm_II_Day_11_Recursion_Backtracking, Udemy_Backtracking/Recursion, Big_O_Time_O(4^n)_Space_O(n) | 155 | 95.24
40874126
| 0016 |[3Sum Closest](src/main/kotlin/g0001_0100/s0016_3sum_closest)| Medium | Array, Sorting, Two_Pointers, Level_2_Day_14_Sliding_Window/Two_Pointer | 163 | 100.00
4088-
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Data_Structure_II_Day_1_Array, Algorithm_II_Day_3_Two_Pointers, Udemy_Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45
4127+
| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Data_Structure_II_Day_1_Array, Algorithm_II_Day_3_Two_Pointers, Udemy_Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45
40894128
| 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String, Level_2_Day_2_String, Udemy_Strings | 154 | 89.70
40904129
| 0013 |[Roman to Integer](src/main/kotlin/g0001_0100/s0013_roman_to_integer)| Easy | Top_Interview_Questions, String, Hash_Table, Math | 211 | 83.47
40914130
| 0012 |[Integer to Roman](src/main/kotlin/g0001_0100/s0012_integer_to_roman)| Medium | String, Hash_Table, Math | 180 | 98.25

src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import java.util.PriorityQueue
4343
import kotlin.collections.HashMap
4444
import kotlin.math.max
4545

46+
@Suppress("NAME_SHADOWING")
4647
class Solution {
4748
fun maxSum(nums: IntArray): Int {
4849
// what we'll return

src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ Return _the number of beautiful integers in the range_ `[low, high]`.
5454
```kotlin
5555
import kotlin.math.max
5656

57+
@Suppress("kotlin:S107")
5758
class Solution {
5859
private lateinit var dp: Array<Array<Array<Array<IntArray>>>>
5960
private var maxLength = 0

src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Return _the **minimum** possible sum of a k-avoiding array of length_ `n`.
3434
## Solution
3535

3636
```kotlin
37+
@Suppress("NAME_SHADOWING")
3738
class Solution {
3839
fun minimumSum(n: Int, k: Int): Int {
3940
var k = k

src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ class Solution {
7777
if (sum < target) {
7878
return -1
7979
}
80-
while (!pq.isEmpty()) {
80+
while (pq.isNotEmpty()) {
8181
val `val` = pq.poll()
8282
sum -= `val`.toLong()
8383
if (`val` <= target) {

src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is
7373
## Solution
7474

7575
```kotlin
76+
@Suppress("NAME_SHADOWING")
7677
class Solution {
7778
fun countKSubsequencesWithMaxBeauty(s: String, k: Int): Int {
7879
var k = k

src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6.
6464
import kotlin.math.ln
6565
import kotlin.math.max
6666

67+
@Suppress("kotlin:S107")
6768
class Solution {
6869
private class Node(var v: Int, var w: Int)
6970

src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ Now nums is sorted; therefore the answer is 2.
4848
## Solution
4949

5050
```kotlin
51+
@Suppress("kotlin:S6510")
5152
class Solution {
5253
fun minimumRightShifts(nums: List<Int>): Int {
5354
var i = 1
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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+
## 2857\. Count Pairs of Points With Distance k
5+
6+
Medium
7+
8+
You are given a **2D** integer array `coordinates` and an integer `k`, where <code>coordinates[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> are the coordinates of the <code>i<sup>th</sup></code> point in a 2D plane.
9+
10+
We define the **distance** between two points <code>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>(x<sub>2</sub>, y<sub>2</sub>)</code> as `(x1 XOR x2) + (y1 XOR y2)` where `XOR` is the bitwise `XOR` operation.
11+
12+
Return _the number of pairs_ `(i, j)` _such that_ `i < j` _and the distance between points_ `i` _and_ `j` _is equal to_ `k`.
13+
14+
**Example 1:**
15+
16+
**Input:** coordinates = \[\[1,2],[4,2],[1,3],[5,2]], k = 5
17+
18+
**Output:** 2
19+
20+
**Explanation:** We can choose the following pairs:
21+
- (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5.
22+
- (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5.
23+
24+
**Example 2:**
25+
26+
**Input:** coordinates = \[\[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0
27+
28+
**Output:** 10
29+
30+
**Explanation:** Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs.
31+
32+
**Constraints:**
33+
34+
* `2 <= coordinates.length <= 50000`
35+
* <code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>6</sup></code>
36+
* `0 <= k <= 100`
37+
38+
## Solution
39+
40+
```kotlin
41+
class Solution {
42+
fun countPairs(coordinates: List<List<Int>>, k: Int): Int {
43+
var ans = 0
44+
val map: MutableMap<Long, Int> = HashMap()
45+
for (p in coordinates) {
46+
val p0 = p[0]
47+
val p1 = p[1]
48+
for (i in 0..k) {
49+
val x1 = i xor p0
50+
val y1 = (k - i) xor p1
51+
val key2 = hash(x1, y1)
52+
if (map.containsKey(key2)) {
53+
ans += map[key2]!!
54+
}
55+
}
56+
val key = hash(p0, p1)
57+
map[key] = map.getOrDefault(key, 0) + 1
58+
}
59+
return ans
60+
}
61+
62+
private fun hash(x1: Int, y1: Int): Long {
63+
val r = 1e8.toLong()
64+
return x1 * r + y1
65+
}
66+
}
67+
```
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
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+
## 2858\. Minimum Edge Reversals So Every Node Is Reachable
5+
6+
Hard
7+
8+
There is a **simple directed graph** with `n` nodes labeled from `0` to `n - 1`. The graph would form a **tree** if its edges were bi-directional.
9+
10+
You are given an integer `n` and a **2D** integer array `edges`, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents a **directed edge** going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.
11+
12+
An **edge reversal** changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.
13+
14+
For every node `i` in the range `[0, n - 1]`, your task is to **independently** calculate the **minimum** number of **edge reversals** required so it is possible to reach any other node starting from node `i` through a **sequence** of **directed edges**.
15+
16+
Return _an integer array_ `answer`_, where_ `answer[i]` _is the_ _**minimum** number of **edge reversals** required so it is possible to reach any other node starting from node_ `i` _through a **sequence** of **directed edges**._
17+
18+
**Example 1:**
19+
20+
![](https://assets.leetcode.com/uploads/2023/08/26/image-20230826221104-3.png)
21+
22+
**Input:** n = 4, edges = \[\[2,0],[2,1],[1,3]]
23+
24+
**Output:** [1,1,0,2]
25+
26+
**Explanation:** The image above shows the graph formed by the edges.
27+
28+
For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0.
29+
30+
So, answer[0] = 1.
31+
32+
For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1.
33+
34+
So, answer[1] = 1.
35+
36+
For node 2: it is already possible to reach any other node starting from node 2.
37+
38+
So, answer[2] = 0.
39+
40+
For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3.
41+
42+
So, answer[3] = 2.
43+
44+
**Example 2:**
45+
46+
![](https://assets.leetcode.com/uploads/2023/08/26/image-20230826225541-2.png)
47+
48+
**Input:** n = 3, edges = \[\[1,2],[2,0]]
49+
50+
**Output:** [2,0,1]
51+
52+
**Explanation:** The image above shows the graph formed by the edges.
53+
54+
For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0.
55+
56+
So, answer[0] = 2.
57+
58+
For node 1: it is already possible to reach any other node starting from node 1.
59+
60+
So, answer[1] = 0.
61+
62+
For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2.
63+
64+
So, answer[2] = 1.
65+
66+
**Constraints:**
67+
68+
* <code>2 <= n <= 10<sup>5</sup></code>
69+
* `edges.length == n - 1`
70+
* `edges[i].length == 2`
71+
* <code>0 <= u<sub>i</sub> == edges[i][0] < n</code>
72+
* <code>0 <= v<sub>i</sub> == edges[i][1] < n</code>
73+
* <code>u<sub>i</sub> != v<sub>i</sub></code>
74+
* The input is generated such that if the edges were bi-directional, the graph would be a tree.
75+
76+
## Solution
77+
78+
```kotlin
79+
import java.util.LinkedList
80+
import java.util.Queue
81+
82+
class Solution {
83+
fun minEdgeReversals(n: Int, edges: Array<IntArray>): IntArray {
84+
val nexts: Array<MutableList<IntArray>> = Array(n) { ArrayList() }
85+
for (edge in edges) {
86+
val u = edge[0]
87+
val v = edge[1]
88+
nexts[u].add(intArrayOf(1, v))
89+
nexts[v].add(intArrayOf(-1, u))
90+
}
91+
val res = IntArray(n)
92+
for (i in 0 until n) {
93+
res[i] = -1
94+
}
95+
res[0] = dfs(nexts, 0, -1)
96+
val queue: Queue<Int> = LinkedList()
97+
queue.add(0)
98+
while (queue.isNotEmpty()) {
99+
val index = queue.remove()
100+
val `val` = res[index]
101+
val next: List<IntArray> = nexts[index]
102+
for (node in next) {
103+
if (res[node[1]] == -1) {
104+
if (node[0] == 1) {
105+
res[node[1]] = `val` + 1
106+
} else {
107+
res[node[1]] = `val` - 1
108+
}
109+
queue.add(node[1])
110+
}
111+
}
112+
}
113+
return res
114+
}
115+
116+
private fun dfs(nexts: Array<MutableList<IntArray>>, index: Int, pre: Int): Int {
117+
var res = 0
118+
val next: List<IntArray> = nexts[index]
119+
for (node in next) {
120+
if (node[1] != pre) {
121+
if (node[0] == -1) {
122+
res++
123+
}
124+
res += dfs(nexts, node[1], index)
125+
}
126+
}
127+
return res
128+
}
129+
}
130+
```

0 commit comments

Comments
 (0)