# Cracking the Coding Interview — 1.2 Check Permutation JavaScript Solution

Write a function to check whether two given strings are Permutation of each other. A permutation of a string is another string that contains same characters, only the order of characters can be different.

For example, “abcd” and “dabc” are permutation of each other.

First, we will create a hash map for storage purposes, NEVER mutate the original string or data, ALWAYS create a copy!

Second step is to check if the length of given two strings is the same. We will then need to loop through each string and count the number of characters in them. If a character already exists in the hash map, increment the count. Otherwise, set it to 1.

Inside the second for loop check if myHash doesn’t have the character and return false right away in case it is not a permutation. For example

Str1: abcd

str2: dcbt

when you get to “t” you are trying to reduce the value of undefined since myHash won’t have “t” inside

Our last requirement is to loop through the hash map and ensure that our object does not have any characters with a count 0 in them. If it does, return false.

And that’s it! These simple 3 steps are common in tech interviews. The time complexity of this solution in JavaScript is O(n).

`const checkPermutation = (str1, str2) => {  if (str1.length !== str2.length) {  return false;  } let myHash = {}; for (let i = 0; i < str1.length; i++) {   if (myHash[str1[i]]) {   myHash[str1.charAt(i)]++;   } else {   myHash[str1.charAt(i)] = 1;   } } for (let i = 0; i < str2.length; i++) { myHash[str2.charAt(i)]--; } for (i in myHash) {   if (myHash[i] !== 0) {   return false;   } } return true;}`