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.
1using System;
2using System.Collections.Generic;
3
4class MySet {
5 private Dictionary<int, bool> hashMap;
6
7 public MySet() {
8 hashMap = new Dictionary<int, bool>();
9 }
10
11 public void Insert(int key) {
12 hashMap[key] = true;
13 }
14
15 public bool Search(int key) {
16 return hashMap.ContainsKey(key);
17 }
18
19 static void Main() {
20 MySet mySet = new MySet();
21 mySet.Insert(10);
22 Console.WriteLine("Search for 10: " + mySet.Search(10)); // Output: True
23 Console.WriteLine("Search for 20: " + mySet.Search(20)); // Output: False
24 }
25}
26
C# provides the Dictionary
class, similar to Java's HashMap
, allowing us to manage our key-value pairs efficiently.
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.