Skip to content

Instantly share code, notes, and snippets.

View alexspark's full-sized avatar

Alex Park alexspark

  • Los Angeles, CA
View GitHub Profile
@alexspark
alexspark / in_order_traversal.rb
Last active January 16, 2018 08:37
In-order traversal of a binary tree
class Node
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
end
def in_order_traversal(node)
in_order_traversal node.left if node.left
puts node.value
@alexspark
alexspark / level_order_traversal.rb
Created January 16, 2018 08:48
Level-order traversal of a binary tree
class Node
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
end
def level_order_traversal(node)
queue = [node]
@alexspark
alexspark / reverse_interleave.rb
Last active January 20, 2018 23:02
Daily Coding Problem 1
# This problem was asked by Google.
#
# Given a stack of N elements, interleave the first half of the stack
# with the second half reversed using only one other queue. This should be done in-place.
#
# Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue.
def reverse_interleave(stack)
return stack if stack.length < 3
@alexspark
alexspark / product_of_others.rb
Last active January 22, 2018 05:37
Product of others
# This problem was asked by Uber.
# Given an array of integers, return a new array such that each element
# at index i of the new array is the product of all the numbers in the original
# array except the one at i. Solve it without using division and in O(n) time.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].
# If our input was [3, 2, 1], the expected output would be [2, 3, 6].
def products_of_others(list)
right_products = Array.new(list.length)
left_products = Array.new(list.length)
require 'benchmark'
module BenchmarkTest
def self.find_pair_naive(list, sum)
list.each_with_index do |first, index_1|
list.each_with_index do |second, index_2|
next if index_1.eql? index_2
if first + second == sum
return [index_1, index_2]