Introduction
A Map is a data structure that stores data in the form of key-value pairs.
Each key is associated with a value, allowing us to efficiently find a value using its key.
For example, a student's roll number can be used as a key and the student's name can be stored as its value.
This concept helps in understanding:
- Key-value pairs
- Hashing
- Fast searching
- Insertion and deletion
- Frequency counting
Problem Statement
Given a collection of key-value pairs, store the data and efficiently retrieve the value associated with a given key.
For example, if the keys are student IDs and the values are student names, searching for a student ID should return the corresponding name.
Example
Input:Keys = [101, 102, 103]
Values = ["Alice", "Bob", "Charlie"]
Search Key:
102
Output:
Bob
Explanation:
The key 102 is associated with the value "Bob".
Approach 1: Brute Force
Explanation
The brute force approach stores keys and values in separate arrays.
To find the value associated with a key, we traverse the keys one by one.
When the required key is found, we return the value at the same index.
Steps
- Store keys in one array.
- Store corresponding values in another array.
- Traverse the keys.
- Compare each key with the target key.
- Return the value at the matching index.
Dry Run
Input:Keys = [101, 102, 103]
Values = ["Alice", "Bob", "Charlie"]
Search Key:
102
Check 101 → Not found
Check 102 → Found
Corresponding value:
Bob
Final Result:
Bob
Brute Force Code
Complexity Analysis
Time Complexity: O(n)
In the worst case, all keys may need to be checked.
Space Complexity: O(n)
The keys and values are stored in separate arrays.
Approach 2: Optimized Solution
Explanation
The optimized approach uses a Map.
A Map directly associates each key with its corresponding value.
Hashing allows us to find a value using its key in average O(1) time.
Steps
- Create an empty Map.
- Insert each key-value pair.
- Search for the required key.
- Retrieve its associated value.
- Return the result.
Dry Run
Input:Key-Value pairs:
101 → Alice
102 → Bob
103 → Charlie
Insert:
101 → Alice
102 → Bob
103 → Charlie
Search:
102
Map finds:
102 → Bob
Final Result:
Bob
Optimized Code