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.
1import java.util.HashMap;
2
3public class MySet {
4 private HashMap<Integer, Boolean> hashMap;
5
6 public MySet() {
7 hashMap = new HashMap<>();
8 }
9
10 public void insert(int key) {
11 hashMap.put(key, true);
12 }
13
14 public boolean search(int key) {
15 return hashMap.containsKey(key);
16 }
17
18 public static void main(String[] args) {
19 MySet mySet = new MySet();
20 mySet.insert(10);
21 System.out.println("Search for 10: " + mySet.search(10)); // Output: true
22 System.out.println("Search for 20: " + mySet.search(20)); // Output: false
23 }
24}
25
In Java, the HashMap
is used to efficiently manage insertion and lookup operations. We use the presence of a key to indicate its inclusion.
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.