Skip to main content

Update in Hash Table

Ayesha
EditReport

Update in Hash Table

The update operation involves modifying the value associated with an existing key in a hash table. If the key is not present, it may require an insertion.

Video Explanation

Steps for Update

  1. Hash the Key: Use a hash function to find the index.
  2. Update the Value: Modify the value associated with the key if it exists.
  3. Handle Key Absence: If the key does not exist, you can choose to insert it instead.

Time Complexity

  • Average Case: O(1)O(1)
  • Worst Case: O(n)O(n)

Example Code (Python)

class HashTable:
def __init__(self):
self.table = {}

def update(self, key, value):
self.table[key] = value

# Example usage
hash_table = HashTable()
hash_table.table = {'apple': 10, 'banana': 20}
hash_table.update('apple', 30) # Updates value

Example Code (Javascript)

class HashTable {
constructor() {
this.table = {};
}

update(key, value) {
this.table[key] = value;
}
}

// Example usage
const hashTable = new HashTable();
hashTable.table = { 'apple': 10, 'banana': 20 };
hashTable.update('apple', 30); // Updates the value for 'apple'
console.log(hashTable.table); // Output: { 'apple': 30, 'banana': 20 }

Conclusion

Update is critical for modifying data in hash tables, making them adaptable and suitable for dynamic applications.

Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Update in Hash Table"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.