Skip to content

Instantly share code, notes, and snippets.

View st0le's full-sized avatar
💭
nohello

Gaurav Kamath st0le

💭
nohello
View GitHub Profile
@st0le
st0le / NonTransitiveComparator
Created June 6, 2014 22:25
Finding Minimum with a Non-Transitive Comparator
using System;
namespace SharpFoo
{
class Program
{
private Random rnd = new Random();
static void Main(string[] args)
{
@st0le
st0le / gist:7376613
Created November 8, 2013 19:51
Coin Change
public static void main(String[] args) {
int K = 4;
int[] coins = new int[]{1,2,3};
int[] ways = new int[K + 1];
ways[0] = 1;
@st0le
st0le / gist:6891663
Last active December 25, 2015 00:59
Binary Search Tree to Double Linked List.
private Node toDBList(Node node) {
if (node.right == null && node.left == null)
return node;
if (node.left != null) {
Node hold = toDBList(node.left);
hold = hold.getRightMost();
hold.right = node;
node.left = hold;
}
if (node.right != null) {
def sort(n):
q = [0]*10
while n > 0:
q[n%10]+=1
n/=10
r = 0
for i in xrange(max(q)+1):
for j in xrange(9,-1,-1):
if q[j] != i: continue
while q[j] > 0:
@st0le
st0le / gist:6656668
Created September 22, 2013 04:20
O(n^2) Find increasing triplet
def find_triple(arr): #O(n^2)/O(1)
N = len(arr)
for i in xrange(N):
left = None
for j in xrange(i - 1, -1, -1):
if arr[i] > arr[j]:
left = j
break
right = None
@st0le
st0le / gist:6656542
Created September 22, 2013 03:59
Naive Triplet
def find_triple(arr): #O(n^3)/O(1)
N = len(arr)
for i in xrange(N):
for j in xrange(i+1,N):
for k in xrange(j+1,N):
if arr[i] < arr[j] < arr[k]:
return arr[i],arr[j],arr[k]
return None
@st0le
st0le / gist:6646977
Created September 21, 2013 03:37
longest_interval_lists
def longest_interval_lists(m):
heap = []
for i,lst in enumerate(m):
heapq.heappush(heap,(lst[0],i,0))
mn,mx = heap[0][0],max(heap)[0]
max_in_heap = mx
while heap:
x,index,i = heapq.heappop(heap)
if i + 1 == len(m[index]): break
@st0le
st0le / gist:6646739
Created September 21, 2013 02:57
O(nlogk) algorithm for k-way merge
def merge2(arr):
heap = [(l[0],i,0) for i,l in enumerate(arr) if len(l) > 0]
heapq.heapify(heap)
lst = []
while heap:
item,lst_index,item_index = heapq.heappop(heap)
lst.append(item)
if item_index + 1 < len(arr[lst_index]):
heapq.heappush(heap,(arr[lst_index][item_index+1],lst_index,item_index+1))
@st0le
st0le / gist:6646622
Created September 21, 2013 02:35
k-way merge
def merge(arr):
k = len(arr)
index = [0] * k
lst = []
while True:
mni = None
for i in xrange(k):
if index[i] < len(arr[i]) and (mni == None or arr[i][index[i]] < arr[mni][index[mni]]):
mni = i
if mni == None: break
@st0le
st0le / gist:6646170
Last active December 23, 2015 13:59
Find Increasing Triplet Subsequence
def find_triple(arr): #O(n)/O(1)
mn = a = arr[0]
b = None
for v in arr[1:]:
if mn >= v: # v is the new minimum
mn = v
elif b == None or b > v: # v > min but less than earlier 'b'
a,b = mn,v
else: # v > b > a
return a,b,v