Microsoft Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
<Programming Pearls> has the answer:
two array: from[], to[] (from[to[i]] == i).
initial:
top = 0;
push one element:
to[top] = data; from[data]=top++;
check data:
to[from[data]] == data
If we can do this, this i will give you one advice store data into from inself ,not in top, and enqueue operation is from[data] = data;
and similarly dequeue operation can be written, and this require less amount of memory, so what is this,
i don't know what sonesh is saying.
I have another doubt.
Take the case:
While searching, data = 5
5 has not been inserted in the hashmap
Garbage values are as follows:
from[5] = 3234
to[3234] = 5
Then this will return that 5 exists but if we have the check from[data]<top, then it will function correctly
So I think the check
from[data]<top
should also be there.
You could use an array of linked lists of size M. The hashing function could be (val % M). Every time you have to insert a no., you pass it through the hashing function to get the index where the no. would be inserted.
If there isn't any linked list at that index, you will have to create a node. And then that index would have to point to that node. Thus in this you don't need any initialization in the beginning.
Use two data structures
- deadman September 01, 20121. An array of size N, with index nextEmpty, which indicates where the next element should be added.
2. A hashmap with key as the number itself and value as the index of that number in the array.
For add operation - Just add the number at nextEmpty location, update hashmap and do nextEmpty++.
For remove operation - Get the index of the number from hashmap, remove it from hashmap. Then swap last element in the array(nextEmpty-1) with that element. Update the hashmap and do nextEmpty--
Both operations will be O(1)