Skip to content

Commit ec72949

Browse files
Insert Delete GetRandom O(1) - Duplicates allowed: Accepted
1 parent 25dfc53 commit ec72949

File tree

2 files changed

+116
-0
lines changed

2 files changed

+116
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ My accepted leetcode solutions to some of the common interview problems.
118118
- [Flatten Nested List Iterator](problems/src/design/NestedIterator.java) (Medium)
119119
- [Add and Search Word - Data structure design](problems/src/design/WordDictionary.java) (Medium)
120120
- [Prefix and Suffix Search](problems/src/design/WordFilter.java) (Hard)
121+
- [Insert Delete GetRandom O(1) - Duplicates allowed](problems/src/design/RandomizedCollection.java) (Hard)
121122

122123
#### [Divide and Conquer](problems/src/divide_and_conquer)
123124

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
package design;
2+
import java.util.*;
3+
4+
/**
5+
* Created by gouthamvidyapradhan on 14/04/2018.
6+
* Design a data structure that supports all following operations in average O(1) time.
7+
8+
Note: Duplicate elements are allowed.
9+
insert(val): Inserts an item val to the collection.
10+
remove(val): Removes an item val from the collection if present.
11+
getRandom: Returns a random element from current collection of elements. The probability of each element being
12+
returned is linearly related to the number of same value the collection contains.
13+
Example:
14+
15+
// Init an empty collection.
16+
RandomizedCollection collection = new RandomizedCollection();
17+
18+
// Inserts 1 to the collection. Returns true as the collection did not contain 1.
19+
collection.insert(1);
20+
21+
// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
22+
collection.insert(1);
23+
24+
// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
25+
collection.insert(2);
26+
27+
// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
28+
collection.getRandom();
29+
30+
// Removes 1 from the collection, returns true. Collection now contains [1,2].
31+
collection.remove(1);
32+
33+
// getRandom should return 1 and 2 both equally likely.
34+
collection.getRandom();
35+
36+
Solution O(1) for each operation. Maintain a hashmap of value -> {set of indices}; Set of indices are indices of array
37+
containing the value.
38+
Insert: Insert a element in end of array and add the index of array as the set of values in hashmap.
39+
Remove: If the hashmap contains value remove a random element from the set and replace the element at that index
40+
with the last element from array and remove the last element from the array. Since we are removing the last
41+
element from array this operation requires only O(1) time
42+
getRandom(): Generate a random number between 0 and size of array and return the element at that position.
43+
*/
44+
public class RandomizedCollection {
45+
46+
private Map<Integer, Set<Integer>> map;
47+
private List<Integer> list;
48+
49+
/** Initialize your data structure here. */
50+
public RandomizedCollection() {
51+
map = new HashMap<>();
52+
list = new ArrayList<>();
53+
}
54+
55+
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
56+
public boolean insert(int val) {
57+
boolean status = map.containsKey(val);
58+
Set<Integer> set = map.get(val);
59+
if(set == null){
60+
set = new HashSet<>();
61+
map.put(val, set);
62+
}
63+
list.add(val);
64+
set.add(list.size() - 1);
65+
return !status;
66+
}
67+
68+
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
69+
public boolean remove(int val) {
70+
if(map.containsKey(val)){
71+
Set<Integer> set = map.get(val);
72+
int valIndex = set.iterator().next();
73+
set.remove(valIndex);
74+
if(set.isEmpty()){
75+
map.remove(val);
76+
}
77+
if(valIndex == list.size() - 1){ //if this is the last index then simply remove it
78+
list.remove(list.size() - 1);
79+
} else{
80+
int lastEle = list.get(list.size() - 1);
81+
map.get(lastEle).remove(list.size() - 1);
82+
map.get(lastEle).add(valIndex);
83+
list.set(valIndex, lastEle);
84+
list.remove(list.size() - 1);
85+
}
86+
return true;
87+
} else return false;
88+
}
89+
90+
/** Get a random element from the collection. */
91+
public int getRandom() {
92+
Random random = new Random();
93+
return list.get(random.nextInt(list.size()));
94+
}
95+
96+
/**
97+
* Main method
98+
* @param args
99+
* @throws Exception
100+
*/
101+
public static void main(String[] args) throws Exception{
102+
RandomizedCollection collection = new RandomizedCollection();
103+
System.out.println(collection.insert(1));
104+
System.out.println(collection.insert(1));
105+
System.out.println(collection.insert(2));
106+
System.out.println(collection.getRandom());
107+
System.out.println(collection.remove(2));
108+
System.out.println(collection.getRandom());
109+
System.out.println(collection.remove(1));
110+
System.out.println(collection.getRandom());
111+
System.out.println(collection.remove(1));
112+
}
113+
114+
115+
}

0 commit comments

Comments
 (0)