Amazon Interview Question
SDE-2sCountry: India
Interview Type: In-Person
Store hash map from items to index in array. For insertion just push back item to the array and add corresponding record to hash map. For deletion determine position of deleted item in array and in array perform swap this item with last item. Decrement size of array and reflect swap changes in hash map.
All of the operations being O(1) looks like the interviewer is asking for a hashmap implementation.
Simplest way of implementing a hashtable/map requires two things:
1. Data structure to store key value pairs, we take array named A of size = sz
2. A hash function F.
So, our Hashtable will store key value pairs and allow Insert, Delete, Search and getRandom in O(1) time.
getRandom:
- puneet.sohi November 25, 2015Bascially return any random entry from the array. Pick a random number using random number generator and use
the modulus operator to convert it into a suitable index i.e. idx = random_number % size
Now, return the key-val pair at this size.