You are on page 1of 15

Write a method to check if the given tree is binary search tree.

private boolean isBST() {


return isBST(root, null, null);
}
private boolean isBST(Node x, Key min, Key max) {
if (x == null) return true;
if (min != null && x.key.compareTo(min) <= 0) return false;
if (max != null && x.key.compareTo(max) >= 0) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}

Write a method to print output of a^b
public double power(double a, int b) {
// Base case with 0 exponent
if (b == 0) return 1;

// Negative exponent
if (b < 0) {
assert a != 0; // Negative exponent for base 0 is not allowed
return 1. / power(a, -b);
}

// General case of positive exponent
double half = power(a, b / 2);
return half * half * ( (b % 2 == 1) ? a : 1 );
}


Replace element of an Array with nearest bigger number at right side of the Array in O(n)
For example if the input Array is
7, 5, 6, 3, 4, 1, 2, 9, 11
output array should be
9, 6, 9, 4, 9, 2, 9, 11, 11
import java.util.Scanner;
import java.util.Stack;

/**
*
* @author
*/
public class NextBigNumber {
private int array[];

private Stack<Integer> stack;
public NextBigNumber()
{
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
array = new int[n];
for(int i = 0;i<n;i++)
array[i] = sc.nextInt();
stack = new Stack<Integer>();
}

public void arrange()
{
stack.push(array[array.length-1]);
for(int i=array.length-2;i>=0;i--)
{
int current = array[i];
if(current<=stack.peek())
{
array[i]=stack.peek();
stack.push(current);
}
else
{
while(!stack.empty() && current > stack.peek())
{
stack.pop();

}
if(!stack.empty())
{
array[i]=stack.peek();

}
stack.push(current);
}
}
}

public void print()
{
for(int i = 0;i<array.length;i++)
{
System.out.print(array[i]+" ");
}
}


}


max sum sub-array problem. Given an array of positive and negative integers, find the maximum
sum possible from the different sub-arrays.
/*
* Returns a maximum sum value in an array of integers
*/
public int maxScan(int[] array)
{
if(array.length == 0) return -1;
else if(array.length == 1)
return array[0];
else
{
int maxSum = array[0];
int current_max = array[0];
for(int i = 1; i < array.length; i++)
{
current_max = Math.max(array[i], current_max +
array[i]);
maxSum = Math.max(maxSum, current_max);
}
return maxSum;
}
}

Implement Smart Pointer?
template <class T>
class shared_ptr
{
public:
shared_ptr(T* p):
ptr(p),
count(new int(1)) {}

//copy constructor must copy the fields AND increment the reference count
shared_ptr(const shared_ptr<T>& other):
ptr(other.ptr),
count(other.count)
{
incrementCount();
}

//destructor must decrement reference count
~shared_ptr()
{
decrementCount();
}

//assignment operator must decrement the reference count of the
//object the pointer no longer points to and increment the count
//of the object it now does point to
shared_ptr<T>& operator=(const shared_ptr<T>& obj)
{
if(this->ptr != obj.ptr)
{
decrementCount();
ptr = obj.ptr;
count = obj.count;
incrementCount();
}
return *this;
}

//not a bad idea to have these, as someone else suggested
T* operator->(){ return ptr; }
T& operator*() { return *ptr;}
T* get() { return ptr;}

private:
inline void incrementCount()
{
(*count)++;
}

//when decrementing, we must free the underlying
//pointer if there are no more copies of it
inline void decrementCount()
{
(*count)--;
if (*count <= 0)
{
delete ptr;
delete count;
}
}

T* ptr;
int* count;
}

in linked list how to find the 1/3rd and 2/3rd nodes efficiently...

ex : 1-->2-->3-->4-->5-->6.

outout :
1/3rd - 2
2/3rd 4
static Node mid;
public static Node FindMid(Node pointer1, Node pointer2)
{
if (pointer1.next != null && pointer1.next.next != null) check it is not null
{
pointer1 = pointer1.next.next;
FindMid(pointer1, pointer2.next);
}
else
mid = pointer2;
return mid;
}

Given a string, reverse the word, but keep the comma, number and space.
int isSeparator(char c)
{
return c == ',' || isdigit(c) || isspace(c);
}
void reverse(char* s, char* e)
{
char c;
for(; s < e; ++s, --e){
c = *s;
*s = *e;
*e = c;
}
}
char* reverseWord(char* s)
{
if(s == NULL || *s == '\0') return s;

char *head = s, *tail = s;
while(1){
//skip continuous separators till next word's front
for(head = tail; *head != '\0' && isSeparator(*head); ++head) ;
if(*head == '\0') break;
//now head points to a word's front, we go on to find out the word's back
for(tail = head + 1; *tail != '\0' && !isSeparator(*tail); ++tail) ;
//now *tail == '\0' or *tail is a separator, so we reverse s[head,tail)
reverse(head, tail - 1);
}
return s;
}

Find Top k most frequent elements
int[] array = new int[] { 1, 2, 1, 1, 3, 4, 5, 3, 3, 3, 3, 3, 5, 6, 7,
2, 9, 7, 5 };

int k = 3;

Integer frequency[] = new Integer[10];
Arrays.fill(frequency, 0);

for (int i = 0; i < frequency.length; i++) {
frequency[array[i]] += 1;
}

Arrays.sort(frequency, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (o1.intValue() < o2.intValue()) {
return 1;
} else if (o1.intValue() > o2.intValue()) {
return -1;
} else {
return 0;
}
};
});

for (int i = 0; i < k; i++) {
System.out.println(array[frequency[i]]);
}

Design LRU Cache

Its only for Java Implementation. However, its very easy to implement it using linkedlist.
/**
* Least Recently Used Cache Implementation.
* Date: 9/19/13
* Time: 8:20 PM
*/

public class LRUCache extends LinkedHashMap {

private int maxSize;

public LRUCache(int maxSize) {
super(maxSize, 0.75F, true);
this.maxSize = maxSize;
}

public boolean removeEldestEntry(Map.Entry map) {
return super.size() > maxSize;
}
}


Given a linked list, determine if it has a cycle in it.
Use fast and low pointer. The advantage about fast/slow pointers is that when a circle is
located, the fast one will catch the slow one for sure.
public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }


public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;

if(head == null)
return false;

if(head.next == null)
return false;

while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;

if(slow == fast)
return true;
}

return false;
}
}

http://www.programcreek.com/2012/11/leetcode-solution-merge-sort-linkedlist-in-java/

The problem:
Given a singly linked list L: L0L1 Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2

//Class definition of ListNode
class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
next = null;
}
}

public class ReorderList {

public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
n1.next = n2;
n2.next = n3;
n3.next = n4;

printList(n1);

reorderList(n1);

printList(n1);
}

public static void reorderList(ListNode head) {

if (head != null && head.next != null) {

ListNode slow = head;
ListNode fast = head;

//use a fast and slow pointer to break the link to two
parts.
while (fast != null && fast.next != null &&
fast.next.next!= null) {
//why need third/second condition?
System.out.println("pre "+slow.val + " " +
fast.val);
slow = slow.next;
fast = fast.next.next;
System.out.println("after " + slow.val + " " +
fast.val);
}

ListNode second = slow.next;
slow.next = null;// need to close first part

// now should have two lists: head and fast

// reverse order for second part
second = reverseOrder(second);

ListNode p1 = head;
ListNode p2 = second;

//merge two lists here
while (p2 != null) {
ListNode temp1 = p1.next;
ListNode temp2 = p2.next;

p1.next = p2;
p2.next = temp1;

p1 = temp1;
p2 = temp2;
}
}
}

public static ListNode reverseOrder(ListNode head) {

if (head == null || head.next == null) {
return head;
}

ListNode pre = head;
ListNode curr = head.next;

while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}

// set head node's next
head.next = null;

return pre;
}

public static void printList(ListNode n) {
System.out.println("------");
while (n != null) {
System.out.print(n.val);
n = n.next;
}
System.out.println();
}
}

Given a sorted linked list, delete all duplicates such that each element appear only
once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;

ListNode prev = head;
ListNode p = head.next;

while(p != null){
if(p.val == prev.val){
prev.next = p.next;
p = p.next;
//no change prev
}else{
prev = p;
p = p.next;
}
}

return head;
}
}

LONGEST COMMON SUBSESQUENCE
public static String lcs(String a, String b){
int aLen = a.length();
int bLen = b.length();
if(aLen == 0 || bLen == 0){
return "";
}else if(a.charAt(aLen-1) == b.charAt(bLen-1)){
return lcs(a.substring(0,aLen-1),b.substring(0,bLen-1))
+ a.charAt(aLen-1);
}else{
String x = lcs(a, b.substring(0,bLen-1));
String y = lcs(a.substring(0,aLen-1), b);
return (x.length() > y.length()) ? x : y;
}
}

All Permutations of String
This is a iterative java version. The idea is to generate all permutation of ch[0], then ch[0]
and ch[1] and so on till ch[0] to ch[n].
public static ArrayList<string> allStringsI(String s) {
ArrayList<string> retVal = new ArrayList<string>();
retVal.add("");
if (s == null || s.length() == 0)
return retVal;
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
ArrayList<string> loop = retVal;
retVal = new ArrayList<string>();
for (String st: loop){
retVal.add(c+st);
for (int j = 1; j <= st.length(); j++)
retVal.add(st.substring(0, j) + c + st.substring(j));
}
}
return retVal;
}



Reverse Words in a String

import java.util.*;
public class Rev {
public static void ReverseWords (char str[])
{
int start = 0, end = 0, length;
length = str.length;
/* Reverse entire string */
ReverseString(str, start, length - 1);
while (end < length) {
if (str[end] != &#039 &#039) { /* Skip non-word characters */
/* Save position of beginning of word */
start = end;
/* Scan to next non-word character */
while (end start) {
/* Exchange characters */
temp = str [start];
str [start] = str [end] ;
str [end] = temp;
/* Move indices towards middle */
start++; end--;
}
return;
}
public static void main(String[] args){
String s = "Hello World";
char[] str = s.toCharArray();
ReverseWords(str);
String output = "";
for(int i = 0; i < str.length; i++)
output+=str[i];
System.out.println(output);
}
}
output: World Hello

BALANCED PARANTHESIS
public static boolean isValid(String s) {
char[] charArray = s.toCharArray();

HashMap<Character, Character> map = new HashMap<Character,
Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');

Stack<Character> stack = new Stack<Character>();

for (Character c : charArray) {
if (map.keySet().contains(c)) {
stack.push(c);
} else if (map.values().contains(c)) {
if (!stack.isEmpty() && map.get(stack.peek()) == c) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}

REVERESE LINKED LIST 0(n)-0(1)
public reverseListIteratively (Node head)
{
if (head == NULL || head.next == NULL)
return; //empty or just one node in list

Node Second = head.next;

//store third node before we change
Node Third = Second.next;

//Second's next pointer
Second.next = head; //second now points to head
head.next = NULL; //change head pointer to NULL

//only two nodes, which we already reversed
if (Third == NULL)
return;

Node CurrentNode = Third;

Node PreviousNode = Second;

while (CurrentNode != NULL)
{
Node NextNode = CurrentNode.next;

CurrentNode.next = PreviousNode;

/* repeat the process, but have to reset
the PreviousNode and CurrentNode
*/

PreviousNode = CurrentNode;
CurrentNode = NextNode;
}

head = PreviousNode; //reset the head node
}

Reverse a linked list recursive Java solution

public void recursiveReverse(Node currentNode )
{
//check for empty list
if(currentNode == NULL)
return;

/* if we are at the TAIL node:
recursive base case:
*/
if(currentNode.next == NULL)
{
//set HEAD to current TAIL since we are reversing list
head = currentNode;
return; //since this is the base case
}

recursiveReverse(currentNode.next);
currentNode.next.next = currentNode;
currentNode.next = null; //set "old" next pointer to NULL
}