Skip to content

Instantly share code, notes, and snippets.

View bparanj's full-sized avatar

Bala Paranj bparanj

View GitHub Profile
Interval Operations
There are a few operations that can be performed on intervals:
1. Merge interval[] s.t. the all intervals are disjoint.
[0,5],[5,7] ==> [0,7]
2. Insert interval into interval[] s.t. all intervals are disjoint.
3. Find intersection between two interval[].
[0,5],[5,7] => [5,5]
In order to perform these operations, it is important to understand the 6
def smaller_numbers_than_current(nums)
indices = {}
list = nums.sort
for i in (0..list.size-1)
unless indices.has_key?(list[i])
indices[list[i]] = i
end
end
result = []
def two_sum(nums, target)
hash = {}
nums.each_with_index do |element, index|
if hash.include?(target - element)
return [index, hash[target - element]]
else
hash[element] = index
end
end
def xor_operation(n, start)
number = 0
for i in (0..n-1) do
number ^= start + 2*i
end
number
end
def num_jewels_in_stones(j, s)
jewels = j.chars
count = 0
s.chars.each do |c|
if jewels.include?(c)
count += 1
end
end
count
def number_of_steps(num)
count = 0
while num != 0
if num.even?
num = num/2
else
num -= 1
end
count += 1
end
def defang(address)
chars = address.chars
result = ''
chars.each do |c|
if c == '.'
c = '[.]'
end
result += c
end
def candies(candies, extra_candies)
max = candies.max
result = []
for i in (0..candies.size-1)
if candies[i] + extra_candies >= max
result << true
else
result << false
def shuffle(nums, n)
result = []
for i in (0..nums.size-n-1)
result << nums[i]
result << nums[i+n]
end
result
end
def pairs(nums)
total = 0
for i in (0..nums.size-2)
for j in (i+1..nums.size-1)
if nums[i] == nums[j]
total += 1
end
end
end