Map in Data Structure
Map in Data Structure
Learn how Map stores data using key-value pairs, how it works internally, its operations, time complexity, types, examples, and real-world applications.
Introduction
In data structures, a Map is a very important abstract data type used to store data in the form of key-value pairs. A map allows us to associate a unique key with a specific value. Later, we can use that key to quickly access, update, or delete the value.
Map is one of the most commonly used data structures in programming because real-world data is often represented as a relationship between two things. For example, a roll number is related to a student name, a username is related to a user profile, and a product ID is related to product details.
Definition of Map
Each key in a map is unique. A key works like an identifier, and the value is the actual data associated with that key. If we know the key, we can directly find its value without searching every element one by one.
Basic Example
{
"101": "Rumman",
"102": "Amit",
"103": "Priya"
}
In the above example, 101, 102, and 103 are keys. Rumman, Amit, and Priya are their corresponding values.
Real-Life Example of Map
Student ID Card Example
Suppose every student has a unique roll number. If we use roll number as the key and student details as the value, then we can quickly find any student's information using the roll number.
| Key | Value |
|---|---|
| 101 | Rumman Ansari |
| 102 | Amit Kumar |
| 103 | Priya Sharma |
If we want to find the student name for roll number 102, we can directly use the key 102 and get the value Amit Kumar.
Prerequisites to Understand Map
Before learning Map in data structure, students should have basic knowledge of the following topics:
Required Knowledge
- Variables: To understand how individual values are stored.
- Arrays: To compare index-based access with key-based access.
- Functions: To understand operations such as insert, search, update, and delete.
- Objects: Helpful for understanding key-value based data representation.
- Hashing: Useful for understanding how hash-based maps work internally.
- Basic Time Complexity: Helpful for comparing map performance with arrays and lists.
Why Do We Need Map?
Suppose we have a large list of employees and we want to find employee details using employee ID. If we store all employees in a simple array, we may need to search one by one until we find the correct employee. This is slow when the number of records is large.
A map solves this problem by storing employee ID as the key and employee details as the value. So, instead of checking all records one by one, we can directly access the required record using its key.
Without Map
- Data may need to be searched one by one.
- Searching becomes slow for large data.
- Relationships between data items are not clear.
- Code may become longer and harder to maintain.
- Finding a record by name or ID can take more time.
With Map
- Data can be accessed directly using a key.
- Lookup operation is usually very fast.
- Key-value relationship is easy to understand.
- Code becomes more readable and organized.
- Useful for large-scale applications and fast searching.
Structure of Map
A map contains multiple entries. Each entry has two important parts:
Key
A key is a unique identifier used to access a value.
Examples of keys include roll number, employee ID, username, product ID, email ID, account number, and vehicle registration number.
Value
A value is the actual data stored against the key.
Examples of values include student name, employee details, user profile, product information, bank account details, or marks.
Characteristics of Map
Important Features
- Key-Value Pair: Map stores data in the form of key and value.
- Unique Keys: Each key in a map must be unique.
- Fast Lookup: Values can be searched quickly using keys.
- Dynamic Size: A map can grow or shrink as elements are inserted or deleted.
- Flexible Values: Values can be simple data or complex objects.
- Readable Structure: Keys make data easier to understand.
- Useful for Mapping: Best suited for representing relationships between data.
Basic Operations on Map
A map supports several important operations. These operations allow us to add, search, update, remove, and display key-value pairs.
Insert Operation
Insert operation adds a new key-value pair into the map.
If the key does not exist, a new entry is created. If the key already exists, many programming languages update the existing value with the new value.
Search / Lookup Operation
Search operation retrieves the value associated with a given key.
This is the most important use of a map because maps are mainly designed for fast key-based lookup.
Update Operation
Update operation modifies the value of an existing key.
For example, if a product price changes, we can update the price using the product ID as the key.
Delete Operation
Delete operation removes a key-value pair from the map.
When a key is deleted, the value associated with that key is also removed.
Traversal Operation
Traversal means visiting all key-value pairs one by one.
Traversal is useful when we want to display all records stored in a map.
Map Operations Summary
| Operation | Meaning | Example |
|---|---|---|
| Insert | Add a new key-value pair | 101 → "Rumman" |
| Search | Find value using key | Find name using roll number 101 |
| Update | Change value of an existing key | Update salary using employee ID |
| Delete | Remove key-value pair | Delete product using product ID |
| Traversal | Visit all key-value pairs | Display all employee records |
Map Example Using JavaScript
JavaScript provides a built-in Map object. It stores data as key-value pairs and provides methods such as set(), get(), has(), delete(), and clear().
// Creating a Map
let students = new Map();
// Insert key-value pairs
students.set(101, "Rumman");
students.set(102, "Amit");
students.set(103, "Priya");
// Search value using key
console.log(students.get(101));
// Check if key exists
console.log(students.has(102));
// Update value
students.set(102, "Amit Kumar");
// Delete key-value pair
students.delete(103);
// Display complete map
console.log(students);
Output
Rumman
true
Map(2) { 101 => 'Rumman', 102 => 'Amit Kumar' }
Map Example Using Java HashMap
In Java, the Map interface is commonly implemented using classes such as HashMap, LinkedHashMap, and TreeMap. The following example shows how to use HashMap.
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
Map<Integer, String> students = new HashMap<>();
// Insert key-value pairs
students.put(101, "Rumman");
students.put(102, "Amit");
students.put(103, "Priya");
// Search value using key
System.out.println(students.get(101));
// Update value
students.put(102, "Amit Kumar");
// Delete value
students.remove(103);
// Display all key-value pairs
for (Map.Entry<Integer, String> entry : students.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
Output
Rumman
101 -> Rumman
102 -> Amit Kumar
Internal Working of Map
A map can be implemented in different ways. The most common implementations are: Hash Table and Tree. The internal implementation affects performance, order, and use cases.
Hash-Based Map
Uses hashing to calculate the storage location of a key.
In a hash-based map, a hash function converts the key into a numeric index. This index is used to store and retrieve the value quickly.
Tree-Based Map
Uses a tree structure to keep keys in sorted order.
In a tree-based map, keys are arranged according to comparison rules. This type of map is useful when sorted traversal or range-based searching is required.
Hashing in Map
Hashing is a technique used to convert a key into an index. This index helps the map decide where the value should be stored in memory.
Suppose the key is 101 and the table size is 10.
This means the value for key 101 may be stored at index 1. This direct calculation makes map searching very fast in average cases.
Collision in Map
A collision occurs when two different keys generate the same index after applying the hash function. Since both keys want to use the same index, the map must handle this situation.
Collision Example
\( 111 \mod 10 = 1 \)
Here, both 101 and 111 generate the same index 1. This situation is called a collision.
Collision Handling Techniques
Common Techniques
- Chaining: Stores multiple key-value pairs at the same index using a linked structure.
- Linear Probing: Searches the next available empty slot.
- Quadratic Probing: Searches another slot using a quadratic pattern.
- Double Hashing: Uses another hash function to find a new position.
Types of Map
Maps can be classified based on ordering and internal implementation.
Unordered Map
Stores key-value pairs without maintaining sorted order.
Unordered maps are usually implemented using hash tables. They are preferred when fast lookup is more important than maintaining order.
Ordered Map
Maintains keys in sorted order or insertion order depending on implementation.
Ordered maps are useful when we need predictable traversal order, sorted keys, or range-based queries.
Hash Map
Uses hash table internally for fast average-case operations.
Hash maps are commonly used for quick searching, counting frequency, caching, and database indexing.
Tree Map
Uses a tree structure to keep keys sorted.
Tree maps are useful when we need sorted data, range queries, or ordered traversal.
Hash Map vs Tree Map
| Basis | Hash Map | Tree Map |
|---|---|---|
| Internal Structure | Hash table | Tree structure |
| Ordering | No sorted order | Maintains sorted order |
| Search Time | O(1) average | O(log n) |
| Best Use | Fast lookup | Sorted traversal |
| Example | Java HashMap | Java TreeMap |
Time Complexity of Map
Time complexity depends on the internal implementation of the map. A hash-based map usually gives faster average performance, while a tree-based map provides sorted order with logarithmic time.
| Operation | Hash-Based Map Average Case | Hash-Based Map Worst Case | Tree-Based Map |
|---|---|---|---|
| Search | O(1) | O(n) | O(log n) |
| Insert | O(1) | O(n) | O(log n) |
| Delete | O(1) | O(n) | O(log n) |
| Traversal | O(n) | O(n) | O(n) |
Space Complexity of Map
The space complexity of a map is generally O(n), where n is the number of key-value pairs. This is because memory is required to store each key and its associated value.
Hash-based maps may require extra memory for buckets, empty slots, or collision handling structures. Tree-based maps may require extra memory for tree nodes and references.
Map vs Array
Arrays and maps both store data, but they solve different problems. Arrays are best when we want to access data using numeric indexes. Maps are best when we want to access data using meaningful keys.
| Basis | Array | Map |
|---|---|---|
| Access Method | Index-based | Key-based |
| Data Format | Sequential values | Key-value pairs |
| Example | marks[0] | marks.get("Rumman") |
| Best Use | When position matters | When key-based lookup matters |
| Searching | May require linear search | Usually faster using key |
| Readability | Less meaningful for named data | More meaningful because keys describe data |
Map vs Set
Map and Set are both useful data structures, but they are used for different purposes. A map stores key-value pairs, while a set stores only unique values.
| Basis | Map | Set |
|---|---|---|
| Stores | Key-value pairs | Only values |
| Uniqueness | Keys must be unique | Values must be unique |
| Example | Roll No → Student Name | Unique roll numbers |
| Best Use | When value must be found using a key | When duplicate values must be removed |
Map Implementation Methods
| Implementation | Description | Common Performance |
|---|---|---|
| Array-Based Map | Stores key-value pairs in an array and searches linearly. | O(n) |
| Linked List-Based Map | Stores each key-value pair as a node in a linked list. | O(n) |
| Hash Table-Based Map | Uses hashing for fast lookup, insertion, and deletion. | O(1) average |
| Tree-Based Map | Uses a tree structure to keep keys sorted. | O(log n) |
Practical Example: Counting Frequency Using Map
One of the most common uses of a map is frequency counting. In this problem, each item becomes a key and its count becomes the value.
let numbers = [10, 20, 10, 30, 20, 10];
let frequency = new Map();
for (let number of numbers) {
if (frequency.has(number)) {
frequency.set(number, frequency.get(number) + 1);
} else {
frequency.set(number, 1);
}
}
console.log(frequency);
Output
Map(3) { 10 => 3, 20 => 2, 30 => 1 }
In this example, the number is used as the key and the number of occurrences is stored as the value. This technique is commonly used in competitive programming, data analysis, text processing, and search engines.
Advantages of Map
Benefits
- Fast Lookup: Values can be accessed quickly using keys.
- Clear Data Relationship: Key-value structure represents real-world data naturally.
- Dynamic Size: Elements can be added or removed during execution.
- Readable Code: Meaningful keys make code easier to understand.
- Efficient Updates: Existing values can be updated directly using keys.
- Useful in Many Applications: Used in databases, caching, compilers, APIs, and search systems.
Disadvantages of Map
Limitations
- Extra Memory: Some map implementations require additional memory.
- Collision Issues: Hash-based maps may face collisions.
- No Duplicate Keys: Duplicate keys are not allowed in normal maps.
- Worst Case Performance: Hash map operations may become slow in poor collision cases.
- Ordering Depends on Implementation: Not all maps maintain sorted or insertion order.
Applications of Map
Maps are used in many real-world systems because they provide a clean and efficient way to connect keys with values.
Student Management System
- Roll number → Student details
- Fast search of records
- Easy update of marks and attendance
User Profile System
- Username → Profile data
- Quick account lookup
- Useful in login systems
E-Commerce System
- Product ID → Product details
- Fast product search
- Useful for inventory management
Database Indexing
- Primary key → Record location
- Improves search speed
- Useful in large datasets
Caching
- Request URL → Stored response
- Reduces repeated processing
- Improves application performance
Compiler Symbol Table
- Variable name → Memory location
- Tracks identifiers
- Used during compilation
When Should We Use Map?
Common Mistakes Students Make
Avoid These Mistakes
- Thinking that Map and Array are the same.
- Using duplicate keys and expecting both values to remain separately.
- Forgetting that keys must be unique.
- Assuming every map maintains sorted order.
- Ignoring collision handling in hash-based maps.
- Using map where a simple array is enough.
- Not checking whether a key exists before accessing it.
Interview Questions on Map
What is a Map in data structure?
A Map is a data structure that stores data in key-value pairs. Each key is unique and is used to access its associated value.
Why are maps used?
Maps are used when we need fast access to data using meaningful keys, such as finding student details using roll number or user details using username.
What is the difference between Map and Array?
An array accesses data using numeric indexes, while a map accesses data using keys. Arrays are position-based, whereas maps are key-based.
What is the difference between HashMap and TreeMap?
HashMap uses hashing and provides fast average-case operations. TreeMap uses a tree structure and maintains keys in sorted order.
Can two keys have the same value in a map?
Yes, two different keys can have the same value. However, the same key cannot appear twice in a normal map.
What happens if we insert the same key again?
In most map implementations, inserting the same key again updates the old value with the new value.
Quick Revision
| Point | Summary |
|---|---|
| Data Format | Key-value pairs |
| Key Property | Keys must be unique |
| Main Benefit | Fast lookup using key |
| Common Implementations | Hash table and tree |
| Hash Map Average Time | O(1) |
| Tree Map Time | O(log n) |
| Space Complexity | O(n) |
| Best Use Case | Fast key-based data access |
Conclusion
A Map is one of the most useful data structures in computer science. It stores data in the form of key-value pairs, where each key is unique and is used to access its related value. This makes maps extremely useful for fast searching, updating, and deleting data.
Maps are used in many real-world applications such as student management systems, employee records, e-commerce product catalogs, databases, caching systems, search engines, and compilers. Depending on the requirement, maps may be implemented using hash tables for speed or tree structures for sorted order.
Final Takeaway
A Map is best understood as a key-based storage system. If an array answers "What value is stored at this position?", then a map answers "What value belongs to this key?".