Affirm | phone interview | Insert Delete GetRandom O(1)
Anonymous User
3985

It is almost the same question as https://leetcode.com/problems/insert-delete-getrandom-o1/

But they wanted to be a hashmap ex

myObject.putItem('a', 5);
myObject.putItem('b', 6);
myObject.putItem('c', 5);

'a' : 5
'b': 6
'c' : 5

putItem() function should be O(1) and take a char and a int as the input
Delete() could be O(n)
getRandom() should have 2/3 chance return 5 and 1/3 chance return 6

The problem is that putItem function can replace the value if the char is already in the map

// current in map
'a' : 5
'b': 6
'c' : 5

myObject.putItem('c', 6);

// update map
'a' : 5
'b': 6
'c' : 6

So getRandom should now have a have 2/3 chance return 6 and 1/3 chance return 5

So I was able to come out with the same solution as the top answer in that similar question but I did not know how to update the arraylist and keep the function putItem O(1)

Comments (5)