Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
KodeSeeker / BSTCreate.java
Last active December 14, 2015 22:38
Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height .
public static Node addToTree(int arr[], int start, int end){
if (end < start) {
return null;
}
int mid = (start + end) / 2;
Node n = new TreeNode(arr[mid]);// root
n.left = addToTree(arr, start, mid - 1);//left child
n.right = addToTree(arr, mid + 1, end);//right child
return n;
}
@KodeSeeker
KodeSeeker / LevelOrderLinkedListBST.java
Created March 14, 2013 19:30
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)
ArrayList<LinkedList<TreeNode>> findLevelLinkList(TreeNode root) {
int level = 0;
ArrayList<LinkedList<TreeNode>> result = new ArrayList<LinkedList<TreeNode>>(); // ArrayList to return the final set of lists arranged according to level
LinkedList<TreeNode> list = new LinkedList<TreeNode>();// list to store the individual lists at each level.
list.add(root);//// first place the root., into the array list.
result.add(level, list);// plae the root and level into the final arraylist
while (true) {// create and store lists into the final arraylist for each level.
@KodeSeeker
KodeSeeker / InOrderBSTSuccessor.java
Last active December 14, 2015 23:28
Write an algorithm to find the ‘next’ node (e g , in-order successor) of a given node in a binary search tree where each node has a link to its parent . Parent pointer is provided.
public static TreeNode inorderSucc(Node n) {
if (n != null) {
Node p;
if (n.parent == null || n.right != null) { // if n is the root element, and has a right child.
p = leftMostChild(e.right); // the succesor is the leftmost child of the right child of 'n'
} else
{
// n is not the root.
/*
Get the parent of n, p. If the left child of p ==n, then p is the successor.
@KodeSeeker
KodeSeeker / LowestCommonAncestorBinaryTree.java
Created March 14, 2013 22:31
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree Avoid storing additional nodes in a data structure NOTE: This is not necessarily a binary search tree
/*
Approach similar to approach for Common ancestor for BST. Keep going down on one side(right or left) if both the nodes
are in the same side(right or left), else the current node is the lowest common ancestor*/
public Tree commonAncestor(Node root, Node p, Node q) {
// 1st check if p and q, both belong to the left of the current root node, if yes then recurse on the left side
if (covers(root.left, p) && covers(root.left, q)) // check out the covers subroutine, can be used elsewhere too!
return commonAncestor(root.left, p, q);
// else, check if both p and q are children of right side of the root, if yes, then recurse on the right side
if (covers(root.right, p) && covers(root.right, q))
@KodeSeeker
KodeSeeker / StackWithMinSpaceEfficient.java
Created March 15, 2013 22:39
How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
/*The previous implementation stores the minimum element seen so far at each node. The new approach reduces duplication.
It does not store duplicate minimums, and as we are looking only for the lowest minimum, this approach should suffice. */
public class StackWithMin2 extends Stack<Integer> {
Stack<Integer> min;
public StackWithMin2() {
min = new Stack<Integer>();
}
/* Push function checks if the value being pushed is lower than current min, if yes, then it is pushed to the min stack
@KodeSeeker
KodeSeeker / RotatedPalindrome.java
Last active December 15, 2015 07:39
WAP to check if a string is a rotate palindrome
public static boolean IsRotatePalindrome(String in)
{
for(int i=0; i<in.length();i++)
{
String left = in.substring(0, i);//the first substring method accepts 2 values, 1st is index, 2nd is length
String right = in.substring(i);//the overloaded substring method accepts the starting index as the only argument
//now use our palindrome method to check right+left
if(IsPalindrome(right+left))
return true;//immediate return as a true rotated palindrome when we find one
}
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.0">
<assemblies>
<add assembly="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
@KodeSeeker
KodeSeeker / Djikstra.java
Created April 2, 2013 21:25
Djikstra's algorithm implmentation
mport java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
@KodeSeeker
KodeSeeker / GetRational.java
Last active December 15, 2015 20:58
Obtain the rational number from a decimal number . E.g .125 is expressed as 1/8
public static String GetRational(double a)
{ //.125
boolean isNegative;
if(a<0){// if a is negative then set flag
isNegative=true;
a=-a;
}
int tenPoly=1;
// compute the largest power of 10 that divides 'a' completely
while(a*tenPoly-(int)(a*tenPoly)!=0)
@KodeSeeker
KodeSeeker / PrintAllPairsAdduptoM.java
Created April 7, 2013 04:19
Print all pairs of numbers from an array that adds up to M. Assume input is sorted.
public static void PrintAllPairs(int[] sorted, int M)
{
//as the key is to keep track of two indexes, left and right, we define the indexes
int left = 0;//leftmost
int right = sorted.length-1;//rightmost
//now we start our loop, and only make sure left not meet right will we proceed
while(left<right)
{
int tempSum = sorted[left] + sorted[right];//calculate the temp sum and use it to compare to M
if(tempSum==M)//great we find one pair!