CRACKING THE CODING INTERVIEW QUESTIONS IN RUBY AND PURE JS

By: Saurav

2018-03-06 21:43:00 UTC

Q1. Given two strings, write a method to decide if one is a permutation of other (anagram)

There are mainly two ways. First is sorting and second is using a data structure to store the counts. Lets see the solutions for sorting:

Ruby

def ispermutation(a,b)
  return true if a.length < 1 and b.length < 1 
  return false if (a.length > 1 and b.length < 1) or (a.length < 1 and b.length > 1)
  
  return false if a.length != b.length
  
  a = a.split("").sort.join("")
  b = b.split("").sort.join("")
  
  (0..a.length-1).each do |i|
    return false unless a[i] == b[i]
  end 
  
  return true

end 

p ispermutation("bac","acb")

JS

function ispermutation(a,b){
  if (a.length < 1 & b.length < 1){
    return true;
  }
  if (a.length != b.length){
    return false;
  }
  if ((a.length < 1 && b.length > 1) || (a.length < 1 && b.length > 1)) {
    return false;
  }
  
  a = a.split("").sort().join("")
  b = b.split("").sort().join("")
  
//  console.log(a)

 for(let i = 0; i<a.length; i++){
   if (a[i] != b[i]){
     return false;
   }
 }
  
  return true;
  
}

ispermutation("afba","afba")
ispermutation("","")

let's use a hash to do the same:

Ruby

def ispermutation(a,b)
  return true if a.length < 1 and b.length < 1 
  return false if (a.length > 1 and b.length < 1) or (a.length < 1 and b.length > 1)
  
  return false if a.length != b.length
  
  a_hash = Hash.new 
  b_hash = Hash.new 
  
  a.split("").each do |i|
    if a_hash.key?(a[i])
      a_hash[a[i]] += 1
    else
      a_hash[a[i]] = 1
    end 
  end
  
  b.split("").each do |i|
    if b_hash.key?(b[i])
      b_hash[b[i]] += 1
    else
      b_hash[b[i]] = 1
    end 
  end
  
  a_hash.each do |key, value|
    return false unless b_hash.key?(key)
    return false unless b_hash[key] == value 
    b_hash.delete(key)
  end
  
  
  b_hash.empty? ? true : false

end 

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)