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.
1#include <stdio.h>
2#include <stdlib.h>
3
4#define TABLE_SIZE 1000
5
6struct Node {
7 int key;
8 struct Node* next;
9};
10
11struct Node* hashTable[TABLE_SIZE];
12
13int hashFunction(int key) {
14 return key % TABLE_SIZE;
15}
16
17void insert(int key) {
18 int index = hashFunction(key);
19 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
20 newNode->key = key;
21 newNode->next = hashTable[index];
22 hashTable[index] = newNode;
23}
24
25int search(int key) {
26 int index = hashFunction(key);
27 struct Node* head = hashTable[index];
28 while (head != NULL) {
29 if (head->key == key) return 1;
30 head = head->next;
31 }
32 return 0;
33}
34
35int main() {
36 insert(10);
37 printf("Search for 10: %d\n", search(10)); // Output: 1
38 printf("Search for 20: %d\n", search(20)); // Output: 0
39 return 0;
40}
41
In C, hash maps aren't natively supported, so we implement it using separate chaining. We map keys to a list at each index using a simple modulo-based hash function.
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.