![]() |
VOOZH | about |
Consider a problem where same elements are likely to be searched again and again. Implement search operation efficiently.
Examples :
Input : arr[] = {12 25 36 85 98 75 89 15 63 66
64 74 27 83 97}
q[] = {63, 63, 86, 63, 78}
Output : Yes Yes No Yes No
We need one by one search items of q[] in arr[].
The element 63 is present, 78 and 86 are not present.
Implementation: The idea is simple, we move the searched element to front of the array so that it can be searched quickly next time.
Yes Yes No Yes No
Complexity Analysis:
Further Thoughts : We can do better by using a linked list. In linked list, moving an item to front can be done in O(1) time.
The best solution would be to use Splay Tree (a data structure designed for this purpose). Splay tree supports insert, search and delete operations in O(Log n) time on average. Also, splay tree is a BST, so we can quickly print elements in sorted order.