Skip to content

Instantly share code, notes, and snippets.

@petehuang
Last active December 26, 2015 15:09
Show Gist options
  • Save petehuang/7170565 to your computer and use it in GitHub Desktop.
Save petehuang/7170565 to your computer and use it in GitHub Desktop.
First interview
# Reverse polish notation?
#6 + 9 / 3
#6 9 3 / +
#6 9 + 3 /
#2 5 + 9 3 - *
#"10 5 -" => 5
#evaluate_rpn("10 5 -")
#["10", "5", "-"]
#OPERATORS.include?("10")
#numbers << "10".to_i
#numbers = [10]
#numbers << "5".to_i
#numbers = [10, 5]
#OPERATORS.include?("-")
#subtract(numbers.pop, numbers.pop)
#subtract(5, 10)
#numbers << -5
#numbers = [-5]
#-5
def evaluate_rpn(string)
OPERATORS = ["+", "-", "*", "/"]
chars = string.split(" ") #["10", "5", "-"]
numbers = []
chars.each do |char|
if !OPERATORS.include?(char)
numbers << char.to_i
else
second = numbers.pop
first = numbers.pop
if char == "+"
numbers << add(first, second) #numbers[numbers.size-2], numbers[numbers.size-1]
elsif char == "-"
numbers << subtract(first, second)
elsif char == "*"
numbers << multiply(first, second)
elsif char == "/"
numbers << divide(first, second)
end
end
end
numbers.first
end
def add(first, second)
first + second
end
def subtract(first, second)
first - second
end
def multiply(first, second)
first * second
end
def divide(first, second)
first / second
end
# finished with some extra time, let's try another question
# [1,2,3,4,5]
# [3,5,6,7,13]
# first thought is brute force, too inefficient. what's the complexity? O(n^2)
# how about binary search because it's sorted? O(n log n)
# hint: what about merge sort? the merge function runs in linear time
# collabedit crashes here, interview over
bin_search_contains?(element, list) # given
def find_intersection(first_array, second_array)
intersection = []
first_array.each do |n|
if bin_search_contains?(n, second_array)
intersection << n
end
end
intersection
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment