Skip to content

Commit 2e5bb80

Browse files
authored
Added tasks 381, 382, 383, 384.
1 parent 39c628e commit 2e5bb80

File tree

13 files changed

+428
-0
lines changed

13 files changed

+428
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,7 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.6'
10811081

10821082
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- -->
10831083
|-|-|-|-|-|-
1084+
| 0383 |[Ransom Note](src/main/kotlin/g0301_0400/s0383_ransom_note/Solution.kt)| Easy | String, Hash_Table, Counting | 333 | 79.58
10841085
| 0242 |[Valid Anagram](src.save/main/kotlin/g0201_0300/s0242_valid_anagram/Solution.kt)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65
10851086

10861087
#### Day 7 Linked List
@@ -1512,6 +1513,7 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.6'
15121513

15131514
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- -->
15141515
|-|-|-|-|-|-
1516+
| 0384 |[Shuffle an Array](src/main/kotlin/g0301_0400/s0384_shuffle_an_array/Solution.kt)| Medium | Top_Interview_Questions, Array, Math, Randomized | 940 | 72.09
15151517

15161518
#### Day 21 Others
15171519

@@ -1610,6 +1612,10 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.6'
16101612
| 0437 |[Path Sum III](src/main/kotlin/g0401_0500/s0437_path_sum_iii/Solution.kt)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Level_2_Day_7_Tree | 403 | 54.12
16111613
| 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum/Solution.kt)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Level_2_Day_13_Dynamic_Programming | 509 | 57.56
16121614
| 0394 |[Decode String](src/main/kotlin/g0301_0400/s0394_decode_string/Solution.kt)| Medium | Top_100_Liked_Questions, String, Stack, Recursion, Level_1_Day_14_Stack, Udemy_Strings | 224 | 64.86
1615+
| 0384 |[Shuffle an Array](src/main/kotlin/g0301_0400/s0384_shuffle_an_array/Solution.kt)| Medium | Top_Interview_Questions, Array, Math, Randomized, Algorithm_II_Day_20_Others | 940 | 72.09
1616+
| 0383 |[Ransom Note](src/main/kotlin/g0301_0400/s0383_ransom_note/Solution.kt)| Easy | String, Hash_Table, Counting, Data_Structure_I_Day_6_String | 333 | 79.58
1617+
| 0382 |[Linked List Random Node](src/main/kotlin/g0301_0400/s0382_linked_list_random_node/Solution.kt)| Medium | Math, Linked_List, Randomized, Reservoir_Sampling | 283 | 100.00
1618+
| 0381 |[Insert Delete GetRandom O(1) - Duplicates allowed](src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed/RandomizedCollection.kt)| Hard | Array, Hash_Table, Math, Design, Randomized | 1313 | 50.00
16131619
| 0380 |[Insert Delete GetRandom O(1)](src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1/RandomizedSet.kt)| Medium | Top_Interview_Questions, Array, Hash_Table, Math, Design, Randomized, Programming_Skills_II_Day_20 | 1326 | 68.23
16141620
| 0378 |[Kth Smallest Element in a Sorted Matrix](src/main/kotlin/g0301_0400/s0378_kth_smallest_element_in_a_sorted_matrix/Solution.kt)| Medium | Top_Interview_Questions, Array, Sorting, Binary_Search, Matrix, Heap_Priority_Queue | 522 | 59.78
16151621
| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv/Solution.kt)| Medium | Array, Dynamic_Programming, Dynamic_Programming_I_Day_21 | 217 | 72.41
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package g0301_0400.s0381_insert_delete_getrandom_o1_duplicates_allowed
2+
3+
// #Hard #Array #Hash_Table #Math #Design #Randomized
4+
// #2022_11_24_Time_1313_ms_(50.00%)_Space_148_MB_(25.00%)
5+
6+
@Suppress("kotlin:S2245")
7+
class RandomizedCollection() {
8+
val m2a = HashMap<Int, HashSet<Int>>()
9+
val a2m = ArrayList<Int>()
10+
/** Initialize your data structure here. */
11+
12+
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
13+
fun insert(x: Int): Boolean {
14+
a2m.add(x)
15+
val pos = a2m.size - 1
16+
if (x in m2a) {
17+
m2a[x]!!.add(pos)
18+
return false
19+
} else {
20+
m2a[x] = HashSet<Int>()
21+
m2a[x]!!.add(pos)
22+
return true
23+
}
24+
}
25+
26+
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
27+
fun remove(x: Int): Boolean {
28+
if (x !in m2a)
29+
return false
30+
val pos = m2a[x]!!.iterator().next()
31+
if (m2a[x]!!.size == 1)
32+
m2a.remove(x)
33+
else
34+
m2a[x]!!.remove(pos)
35+
if (pos != a2m.size - 1) {
36+
m2a[a2m[a2m.size - 1]]!!.remove(a2m.size - 1)
37+
m2a[a2m[a2m.size - 1]]!!.add(pos)
38+
a2m[pos] = a2m[a2m.size - 1]
39+
}
40+
a2m.removeAt(a2m.size - 1)
41+
return true
42+
}
43+
44+
/** Get a random element from the collection. */
45+
fun getRandom(): Int {
46+
val pos = Math.floor(Math.random() * a2m.size).toInt()
47+
return a2m[pos]
48+
}
49+
}
50+
51+
/*
52+
* Your RandomizedCollection object will be instantiated and called as such:
53+
* var obj = RandomizedCollection()
54+
* var param_1 = obj.insert(`val`)
55+
* var param_2 = obj.remove(`val`)
56+
* var param_3 = obj.getRandom()
57+
*/
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
381\. Insert Delete GetRandom O(1) - Duplicates allowed
2+
3+
Hard
4+
5+
`RandomizedCollection` is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element.
6+
7+
Implement the `RandomizedCollection` class:
8+
9+
* `RandomizedCollection()` Initializes the empty `RandomizedCollection` object.
10+
* `bool insert(int val)` Inserts an item `val` into the multiset, even if the item is already present. Returns `true` if the item is not present, `false` otherwise.
11+
* `bool remove(int val)` Removes an item `val` from the multiset if present. Returns `true` if the item is present, `false` otherwise. Note that if `val` has multiple occurrences in the multiset, we only remove one of them.
12+
* `int getRandom()` Returns a random element from the current multiset of elements. The probability of each element being returned is **linearly related** to the number of same values the multiset contains.
13+
14+
You must implement the functions of the class such that each function works on **average** `O(1)` time complexity.
15+
16+
**Note:** The test cases are generated such that `getRandom` will only be called if there is **at least one** item in the `RandomizedCollection`.
17+
18+
**Example 1:**
19+
20+
**Input**
21+
22+
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
23+
[[], [1], [1], [2], [], [1], []]
24+
25+
**Output:** [null, true, false, true, 2, true, 1]
26+
27+
**Explanation:**
28+
29+
RandomizedCollection randomizedCollection = new RandomizedCollection();
30+
randomizedCollection.insert(1); // return true since the collection does not contain 1.
31+
// Inserts 1 into the collection.
32+
randomizedCollection.insert(1); // return false since the collection contains 1.
33+
// Inserts another 1 into the collection. Collection now contains [1,1].
34+
randomizedCollection.insert(2); // return true since the collection does not contain 2.
35+
// Inserts 2 into the collection. Collection now contains [1,1,2].
36+
randomizedCollection.getRandom(); // getRandom should:
37+
// - return 1 with probability 2/3, or
38+
// - return 2 with probability 1/3.
39+
randomizedCollection.remove(1); // return true since the collection contains 1.
40+
// Removes 1 from the collection. Collection now contains [1,2].
41+
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
42+
43+
**Constraints:**
44+
45+
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code>
46+
* At most <code>2 * 10<sup>5</sup></code> calls **in total** will be made to `insert`, `remove`, and `getRandom`.
47+
* There will be **at least one** element in the data structure when `getRandom` is called.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package g0301_0400.s0382_linked_list_random_node
2+
3+
// #Medium #Math #Linked_List #Randomized #Reservoir_Sampling
4+
// #2022_11_24_Time_283_ms_(100.00%)_Space_38.6_MB_(100.00%)
5+
6+
import com_github_leetcode.ListNode
7+
import java.util.Random
8+
9+
/*
10+
* Example:
11+
* var li = ListNode(5)
12+
* var v = li.`val`
13+
* Definition for singly-linked list.
14+
* class ListNode(var `val`: Int) {
15+
* var next: ListNode? = null
16+
* }
17+
*/
18+
@Suppress("kotlin:S2245")
19+
class Solution(head: ListNode?) {
20+
private val al: MutableList<Int>
21+
private val rand: Random
22+
23+
init {
24+
var head = head
25+
al = ArrayList()
26+
rand = Random()
27+
while (head != null) {
28+
al.add(head.`val`)
29+
head = head.next
30+
}
31+
}
32+
33+
fun getRandom(): Int {
34+
/*
35+
Math.random() will generate a random number b/w 0 & 1.
36+
then multiply it with the array size.
37+
take only the integer part which is a random index.
38+
return the element at that random index.
39+
*/
40+
val ind = rand.nextInt(al.size)
41+
return al[ind]
42+
}
43+
}
44+
45+
/*
46+
* Your Solution object will be instantiated and called as such:
47+
* var obj = Solution(head)
48+
* var param_1 = obj.getRandom()
49+
*/
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
382\. Linked List Random Node
2+
3+
Medium
4+
5+
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
6+
7+
Implement the `Solution` class:
8+
9+
* `Solution(ListNode head)` Initializes the object with the integer array nums.
10+
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen.
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg)
15+
16+
**Input**
17+
18+
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
19+
[[[1, 2, 3]], [], [], [], [], []]
20+
21+
**Output:**
22+
23+
[null, 1, 3, 2, 2, 3]
24+
25+
**Explanation:**
26+
27+
Solution solution = new Solution([1, 2, 3]);
28+
solution.getRandom(); // return 1
29+
solution.getRandom(); // return 3
30+
solution.getRandom(); // return 2
31+
solution.getRandom(); // return 2
32+
solution.getRandom(); // return 3
33+
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
34+
35+
**Constraints:**
36+
37+
* The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.
38+
* <code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code>
39+
* At most <code>10<sup>4</sup></code> calls will be made to `getRandom`.
40+
41+
**Follow up:**
42+
43+
* What if the linked list is extremely large and its length is unknown to you?
44+
* Could you solve this efficiently without using extra space?
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g0301_0400.s0383_ransom_note
2+
3+
// #Easy #String #Hash_Table #Counting #Data_Structure_I_Day_6_String
4+
// #2022_11_24_Time_333_ms_(79.58%)_Space_45.2_MB_(75.39%)
5+
6+
class Solution {
7+
fun canConstruct(ransomNote: String, magazine: String): Boolean {
8+
val a = IntArray(26)
9+
var n = ransomNote.length
10+
for (i in 0 until n) {
11+
a[ransomNote[i].code - 97]++
12+
}
13+
var i = 0
14+
while (i < magazine.length && n != 0) {
15+
if (a[magazine[i].code - 97] > 0) {
16+
n--
17+
a[magazine[i].code - 97]--
18+
}
19+
i++
20+
}
21+
return n == 0
22+
}
23+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
383\. Ransom Note
2+
3+
Easy
4+
5+
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
6+
7+
Each letter in `magazine` can only be used once in `ransomNote`.
8+
9+
**Example 1:**
10+
11+
**Input:** ransomNote = "a", magazine = "b"
12+
13+
**Output:** false
14+
15+
**Example 2:**
16+
17+
**Input:** ransomNote = "aa", magazine = "ab"
18+
19+
**Output:** false
20+
21+
**Example 3:**
22+
23+
**Input:** ransomNote = "aa", magazine = "aab"
24+
25+
**Output:** true
26+
27+
**Constraints:**
28+
29+
* <code>1 <= ransomNote.length, magazine.length <= 10<sup>5</sup></code>
30+
* `ransomNote` and `magazine` consist of lowercase English letters.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package g0301_0400.s0384_shuffle_an_array
2+
3+
// #Medium #Top_Interview_Questions #Array #Math #Randomized #Algorithm_II_Day_20_Others
4+
// #2022_11_24_Time_940_ms_(72.09%)_Space_81.5_MB_(51.16%)
5+
6+
import java.util.Random
7+
8+
@Suppress("kotlin:S2245")
9+
class Solution(private val nums: IntArray) {
10+
private val random: Random = Random()
11+
12+
// Resets the array to its original configuration and return it.
13+
fun reset(): IntArray {
14+
return nums
15+
}
16+
17+
// Returns a random shuffling of the array.
18+
fun shuffle(): IntArray {
19+
val shuffled = nums.clone()
20+
for (i in nums.size - 1 downTo 1) {
21+
val j: Int = random.nextInt(i + 1)
22+
swap(shuffled, i, j)
23+
}
24+
return shuffled
25+
}
26+
27+
private fun swap(shuffled: IntArray, i: Int, j: Int) {
28+
val tmp = shuffled[i]
29+
shuffled[i] = shuffled[j]
30+
shuffled[j] = tmp
31+
}
32+
}
33+
34+
/*
35+
* Your Solution object will be instantiated and called as such:
36+
* var obj = Solution(nums)
37+
* var param_1 = obj.reset()
38+
* var param_2 = obj.shuffle()
39+
*/
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
384\. Shuffle an Array
2+
3+
Medium
4+
5+
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling.
6+
7+
Implement the `Solution` class:
8+
9+
* `Solution(int[] nums)` Initializes the object with the integer array `nums`.
10+
* `int[] reset()` Resets the array to its original configuration and returns it.
11+
* `int[] shuffle()` Returns a random shuffling of the array.
12+
13+
**Example 1:**
14+
15+
**Input** ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []]
16+
17+
**Output:** [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
18+
19+
**Explanation:** Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
20+
21+
**Constraints:**
22+
23+
* `1 <= nums.length <= 50`
24+
* <code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code>
25+
* All the elements of `nums` are **unique**.
26+
* At most <code>10<sup>4</sup></code> calls **in total** will be made to `reset` and `shuffle`.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package g0301_0400.s0381_insert_delete_getrandom_o1_duplicates_allowed
2+
3+
import org.hamcrest.CoreMatchers.equalTo
4+
import org.hamcrest.MatcherAssert.assertThat
5+
import org.junit.jupiter.api.Test
6+
import java.util.Arrays
7+
8+
internal class RandomizedCollectionTest {
9+
@Test
10+
fun randomizedCollectionTest() {
11+
val result: MutableList<String> = ArrayList()
12+
var randomizedCollection: RandomizedCollection? = null
13+
result.add(randomizedCollection.toString() + "")
14+
randomizedCollection = RandomizedCollection()
15+
result.add(randomizedCollection.insert(1).toString() + "")
16+
result.add(randomizedCollection.insert(1).toString() + "")
17+
result.add(randomizedCollection.insert(2).toString() + "")
18+
val random = randomizedCollection.getRandom()
19+
result.add(random.toString() + "")
20+
result.add(randomizedCollection.remove(1).toString() + "")
21+
val random2 = randomizedCollection.getRandom()
22+
result.add(random2.toString() + "")
23+
val expected: List<String> = ArrayList(
24+
Arrays.asList(
25+
"null",
26+
"true",
27+
"false",
28+
"true",
29+
random.toString() + "",
30+
"true",
31+
random2.toString() + ""
32+
)
33+
)
34+
assertThat(result, equalTo(expected))
35+
}
36+
}

0 commit comments

Comments
 (0)