GOOGLE | INTERVIEW | PROGRAMMING | RUBY SORT A STRING ACCORDING TO OTHER STRING

By: Saurav

2018-04-12 20:54:00 UTC

Question: Google
Given two lowercase strings, S1 and S2, sort S1 in same order as S2.
If a character in S1 doesn't exist in S2, put them at the end. If S1 is "program" and S2 is "grapo", then return "grrapom".

Here, before moving forward you need to ask the interviewer about what could be the test cases:
1.What if b is empty?
2. What if a is empty?
3. What chars can a and b have?
4. Are the chars all lowercase or mixed
5. What about repetition
6. Can I use library functions like sort provided by ruby and pass a proc to it?

Then we go ahead and write some tests and then implement the method:

def sort_strings(a,b)
  return a if b.length == 0 
  
  return a.split('').sort{|x,y| index_of_char(b,x) <=> index_of_char(b,y)}.join('')
  
end 

def index_of_char(b,char)
  (0..b.length-1).each do |i|
    return i if char == b[i]
  end 
  return Float::INFINITY
end 

p sort_strings('program', 'grapo') == "grrapom"
p sort_strings('program', '') == "program"
p sort_strings('', 'grapo') == ""


Let me know what you think!
twitter: sprakash24oct
linkedin

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 :)