Sponsored
Sponsored
This approach utilizes hash maps (dictionaries in Python) to achieve optimal time and space complexity for operations such as insertion, deletion, and lookup. By storing elements as keys in a hash map, we benefit from average-case O(1) time complexity for these operations.
Time Complexity: O(1) on average for search, insert, and delete due to the hash map.
Space Complexity: O(n), where n is the number of elements stored.
1class MySet:
2 def __init__(self):
3 self._data = {}
4
5 def insert(self, key):
6 self._data[key] = True
7
8 def search(self, key):
9 return key in self._data
10
11# Example usage
12my_set = MySet()
13my_set.insert(10)
14print(my_set.search(10)) # Output: True
15print(my_set.search(20)) # Output: False
16
Python's dictionaries serve as a direct means to emulate hash maps, where presence in the dictionary indicates inclusion in the set.
This approach leverages sorted arrays to perform efficient binary searches. Operations are optimized for scenarios requiring sorted data, such as when frequent minimum/maximum queries are performed.
Time Complexity: O(n log n) for insertion (due to sorting), O(log n) for search (binary search).
Space Complexity: O(n).
1
In C, we maintain sorted arrays using qsort
after each insertion. Searches are performed with a custom binary search function for efficiency.