Search code examples
javascriptnode.jshashtable

Adding elements on a hash table


I was reading the Grokking Algorithms and it gave me an example of a Hash Map that I couldn't replicate on Javascript... It's very simple, the only thing that I don't know is how to add the value of the ID on the "voted" variable

var canVote = function(id) {
  var voted = {};
  for(let i = 0; i < id.length; i++) {
    if(id in voted) {
      console.log("ID already voted!");
    } else {
      voted[id] = id;
      console.log("Voted successufully!")
    }
  }
}

var id = [10, 20, 20]
canVote(id);


Solution

  • The idea of the Hash table is to find whether a value exists or not in O(1). But, if you iterate over an array of n elements you will obviously end up doing n constant operations which results in O(n).

    Also, the logic which you used has a flaw in the loop iteration. I have modified it in the below code. Please check.

    var canVote = function(id) {
        var voted = {};
        id.forEach(voteId=>{
            if(voted[voteId]){
                console.log("ID already voted!");
            }else{
                voted[voteId] = voteId;
                console.log("Voted successufully!")
            }
        })
    }
    
    var id = [10, 20, 20]
    canVote(id);