Why is a hash table lookup only O(1) time when searching for a key is O(n)?

前端 未结 4 1895
予麋鹿
予麋鹿 2021-01-12 09:16

Technically speaking, based on posts I\'ve read here, Hash table is indeed O(n) time lookup in the worst case. But I don\'t get how the internal mechanics guarantee it to be

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 09:29

    Great question!

    Assume

    1. We want to map strings to values
    2. hashFunction(string) => hashedIndex : int in O(1)
    3. valueArray : [any] stores values
    4. valueIndex : int is the first empty index in valueArray
    5. lookupArray : [int] stores each valueIndex at hashedIndex
    6. array lookups are O(1).
    // Setting a value
    
    valueArray[valueIndex] = value 
    
    hashedIndex = hashFunction(string)
    
    lookupArray[hashedIndex] = valueIndex
    
    
    // Looking up a value
    
    hashedIndex = hashFunction(string) // O(1)
    
    valueIndex = lookupArray[hashedIndex]; // O(1) array lookup
    
    value = valueArray[valueIndex]; // O(1) array lookup
    

    Lots of details omitted to answer your question clearly.

    Hope that helps!

提交回复
热议问题