Learning Hashmaps: Bijective


Hashmaps

Studying a bit on hashmaps, it occurred to me with Leetcode 205 that a basic hashmap is unidirectional. Meaning, it can map items from one set onto another, but it doesn’t inherently give us a mechanism to go backwards. Your basic hashmap is injective, as shown in this picture:

A visual guide to what is an injective function and what is not an injective function borrowed from here: url

I figured the best way to do this was simply two hashmaps, each that pointed from one set to the other, and then check them at the same time. Example below:

function isIsomorphic(s: string, t: string): boolean {
  let answer: boolean = true;
  const sArray = s.split("");
  const tArray = t.split("");
  let mapSontoT = {};
  let mapTontoS = {};

  for (let i = 0; i < s.length; i++) {
    if (
      !mapSontoT.hasOwnProperty(sArray[i]) &&
      !mapTontoS.hasOwnProperty(tArray[i])
    ) {
      mapSontoT[sArray[i]] = tArray[i];
      mapTontoS[tArray[i]] = sArray[i];
      continue;
    } else if (mapSontoT[sArray[i]] !== tArray[i]) {
      answer = false;
      break;
    } else if (mapTontoS[tArray[i]] !== sArray[i]) {
      answer = false;
      break;
    }
  }

  return answer;
}

Also here are some of the other random resources I used, specifically how to actually implement a hashmap in JS. Please, future me, do NOT forget that hasOwnProperty exists as a method on objects.