Skip to content

Instantly share code, notes, and snippets.

@tigarcia
Created June 10, 2014 17:58
Show Gist options
  • Select an option

  • Save tigarcia/9e15b3e2903ea8417714 to your computer and use it in GitHub Desktop.

Select an option

Save tigarcia/9e15b3e2903ea8417714 to your computer and use it in GitHub Desktop.
Common Letters in 2 Strings

Common Characters Interview Questions

Write a function that takes two strings as arguments and returns a string containing only the characters found in both strings. Write 2 versions – one that is O(n) and one that is O(n^2).

O(n^2) Solution

def common_characters_O_of_N2(string1, string2)
  common = {}
  string1.each_char do |c|
    string2.each_char do |c_inner|
      if c == c_inner and !common.has_key? c
        common[c] = true
      end
    end
  end
  
  result = common.keys
end

O(n) Solution

def common_characters_O_of_N(string1, string2)
  common = {}
  string1.each_char do |c|
    unless common.has_key? c
      common[c] = false
    end 
  end

  string2.each_char do |c|
    if common.has_key? c
      common[c] = true
    end
  end

  result = common.select {|key, value| value }.keys
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment