Monday, November 30, 2015
Count the number of occurrence of an element in an array using Binary Search
public int FindNumberOfOccurancesInArray(int element, int[] input) {
int first=BinarySearchFindIndex(element, input, true);
if(first==-1)//Doesn't have the element
return 0;
else {
int second=BinarySearchFindIndex(element, input, false);
System.out.println(first+" "+second);
return second-first+1;
}
}
This is a module to perform Binary Search
if firstElement = true -> Binary Search returns first occurrence of an element
if firstElement = false -> Binary Search returns last occurrence of an element
public int BinarySearchFindIndex(int element, int[] input, boolean firstElement) {
int high = input.length;
int low = 0;
int result =-1;
while(low<=high) {
int mid = low + ((high-low)/2);
if(element==input[mid]) {
result = mid;
if(firstElement)
high=mid-1;
else
low=mid+1;
} else if(element<input[mid]) {
high=mid-1;
} else if(element>input[mid]) {
low=mid+1;
}
}
return result;
}
Labels:
Algorithm,
Binary Search,
Java,
Jeevan,
Jeevan Rex,
Jeevanus
Check if Parentheses are Balanced
import java.util.Stack;
class Parenthesis {
public boolean isParenthesisCorrect(String s) {
char[] c = s.toCharArray();
int size=c.length;
Stack S = new Stack<Character>();
boolean flag = true;
for(int i=0; i<size; i++) {
if(c[i]=='(')
S.push(c[i]);
else if(c[i]==')') {
if(!((Character)S.pop()=='(')) {
flag=false;
break;
}
}
}
if(!S.isEmpty())
flag=false;
return flag;
}
}
public class Main {
public static void main(String[] args) {
Parenthesis P = new Parenthesis();
String s = "((a+b)*(a-b))/c";
System.out.println(P.isParenthesisCorrect(s));
}
}
Saturday, November 28, 2015
Implementing 3 fixed size Stacks using same Array
public class ThreeStacks {
int ArraySize;
int[] Array;
int[] topPointers = {-1,-1,-1};
public ThreeStacks(int size) {
this.ArraySize = size;
this.Array = new int[size * 3];
}
public int peek(int StackNumber) {
if(topPointers[StackNumber-1]>-1) {
return Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
} else {
System.out.println("Error: "+StackNumber+" is empty");
return ErrorCode;
}
}
public static final int ErrorCode = -999;
public int pop(int StackNumber) {
StackNumber--;
if(topPointers[StackNumber]>-1) {
int ret = Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
topPointers[StackNumber]--;
return ret;
} else {
System.out.println("Error: "+StackNumber+" is empty");
return ErrorCode;
}
}
public void push(int data, int StackNumber) {
int maxSize = (ArraySize*StackNumber)-1;
if(topPointers[StackNumber-1]<maxSize) {
topPointers[StackNumber-1]++;
int nextLoc = (ArraySize*(StackNumber-1))+topPointers[StackNumber-1];
Array[nextLoc]=data;
} else {
System.out.println("Stack "+StackNumber+" is full");
}
}
public void print3Stacks() {
StringBuffer sb =new StringBuffer();
for(int i=0; i<=topPointers[0]; i++) {
sb.append(Array[i]);
}
System.out.println(sb.toString());
sb =new StringBuffer();
for(int i=ArraySize; i<=ArraySize+topPointers[1]; i++) {
sb.append(Array[i]);
}
System.out.println(sb.toString());
sb =new StringBuffer();
for(int i=(ArraySize*2); i<=(ArraySize*2)+topPointers[2]; i++) {
sb.append(Array[i]);
}
System.out.println(sb.toString());
}
}
int ArraySize;
int[] Array;
int[] topPointers = {-1,-1,-1};
public ThreeStacks(int size) {
this.ArraySize = size;
this.Array = new int[size * 3];
}
public int peek(int StackNumber) {
if(topPointers[StackNumber-1]>-1) {
return Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
} else {
System.out.println("Error: "+StackNumber+" is empty");
return ErrorCode;
}
}
public static final int ErrorCode = -999;
public int pop(int StackNumber) {
StackNumber--;
if(topPointers[StackNumber]>-1) {
int ret = Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
topPointers[StackNumber]--;
return ret;
} else {
System.out.println("Error: "+StackNumber+" is empty");
return ErrorCode;
}
}
public void push(int data, int StackNumber) {
int maxSize = (ArraySize*StackNumber)-1;
if(topPointers[StackNumber-1]<maxSize) {
topPointers[StackNumber-1]++;
int nextLoc = (ArraySize*(StackNumber-1))+topPointers[StackNumber-1];
Array[nextLoc]=data;
} else {
System.out.println("Stack "+StackNumber+" is full");
}
}
public void print3Stacks() {
StringBuffer sb =new StringBuffer();
for(int i=0; i<=topPointers[0]; i++) {
sb.append(Array[i]);
}
System.out.println(sb.toString());
sb =new StringBuffer();
for(int i=ArraySize; i<=ArraySize+topPointers[1]; i++) {
sb.append(Array[i]);
}
System.out.println(sb.toString());
sb =new StringBuffer();
for(int i=(ArraySize*2); i<=(ArraySize*2)+topPointers[2]; i++) {
sb.append(Array[i]);
}
System.out.println(sb.toString());
}
}
Labels:
Array,
Data Structures,
Jeevan,
Jeevan Rex,
Jeevanus,
Stack
Create and Detect Loop in Linked List
The Linked List program is available here: link
public boolean isLoopExist() {
LinkedList L = this;
LinkedList slow = L;
LinkedList fast = L;
boolean isLoop = false;
while(fast.next!=null) {
slow=slow.next;
fast=fast.next.next;
if(slow==fast) {
isLoop = true;
break;
}
}
return isLoop;
}
public void createLoop(int index) {
LinkedList L = this;
for(int i=2; i<index; i++) {
L=L.next;
}
LinkedList indexPrevNode = L;
while(L.next!=null) {
L=L.next;
}
L.next=indexPrevNode.next;
}
public boolean isLoopExist() {
LinkedList L = this;
LinkedList slow = L;
LinkedList fast = L;
boolean isLoop = false;
while(fast.next!=null) {
slow=slow.next;
fast=fast.next.next;
if(slow==fast) {
isLoop = true;
break;
}
}
return isLoop;
}
public void createLoop(int index) {
LinkedList L = this;
for(int i=2; i<index; i++) {
L=L.next;
}
LinkedList indexPrevNode = L;
while(L.next!=null) {
L=L.next;
}
L.next=indexPrevNode.next;
}
Stack Implementation using Linked List
This is a Stack Implementation using LinkedList in Java. As in Java we don't have pointers and hard to remove head node in a empty list, we are using a dummy head node.
public class Stack {
Stack next;
int data;
private int size;
public Stack() {
this.size=-1;
this.data=-999; //Garbage Value to denote Head
this.next=null;
}
public Stack(int data) {
this.data=data;
this.next=null;
}
public void push(int... data) {
int s = data.length;
for(int i=0; i<s; i++)
push(data[i]);
}
public void push(int data) {
Stack S = this;
if(size==-1) {
S.next=new Stack(data);
} else {
Stack newNode = new Stack(data);
newNode.next=S.next; //Head is a dummy node here
S.next=newNode;
}
size++;
}
public final static int ErrorCode = -999;
public int pop() {
Stack S = this;
if(size>-1) {
int value = S.next.data;
S.next=S.next.next;
size--;
return value;
} else {
System.out.println("Error: Stack is Empty");
return ErrorCode;
}
}
public int size() {
return size;
}
public int peek() {
Stack S = this;
if(size>-1) {
return S.next.data;
} else {
System.out.println("Error: Stack is Empty");
return ErrorCode;
}
}
public void printStack() {
Stack S = this;
S=S.next; // first node is dummy
StringBuffer sb = new StringBuffer();
while(S!=null) {
sb.append(S.data).append(", ");
S=S.next;
}
System.out.println(sb.toString());
}
}
public class Stack {
Stack next;
int data;
private int size;
public Stack() {
this.size=-1;
this.data=-999; //Garbage Value to denote Head
this.next=null;
}
public Stack(int data) {
this.data=data;
this.next=null;
}
public void push(int... data) {
int s = data.length;
for(int i=0; i<s; i++)
push(data[i]);
}
public void push(int data) {
Stack S = this;
if(size==-1) {
S.next=new Stack(data);
} else {
Stack newNode = new Stack(data);
newNode.next=S.next; //Head is a dummy node here
S.next=newNode;
}
size++;
}
public final static int ErrorCode = -999;
public int pop() {
Stack S = this;
if(size>-1) {
int value = S.next.data;
S.next=S.next.next;
size--;
return value;
} else {
System.out.println("Error: Stack is Empty");
return ErrorCode;
}
}
public int size() {
return size;
}
public int peek() {
Stack S = this;
if(size>-1) {
return S.next.data;
} else {
System.out.println("Error: Stack is Empty");
return ErrorCode;
}
}
public void printStack() {
Stack S = this;
S=S.next; // first node is dummy
StringBuffer sb = new StringBuffer();
while(S!=null) {
sb.append(S.data).append(", ");
S=S.next;
}
System.out.println(sb.toString());
}
}
Friday, November 27, 2015
Stack implementation using Array
public class Stack {
int[] array;
private int top;
private int size;
public Stack(int size) {
this.size=size;
array = new int[size];
top = -1;
}
public void push (int... data) {
int size = data.length;
for(int i=0; i<size; i++)
push(data[i]);
}
public void push (int data) {
if (top<size-1) {
top++;
array[top]=data;
}
}
public final static int ErrorCode = -999;
public int pop() {
if(!isEmpty()) {
int a = array[top];
top--;
return a;
} else return ErrorCode;
}
public int peek() {
return array[top];
}
public boolean isEmpty() {
if(top<0) return true;
else return false;
}
public void printArray() {
int size = top+1;
StringBuffer sb = new StringBuffer();
for(int i=0; i<size; i++)
sb.append(array[i]).append(", ");
System.out.println(sb.toString());
}
}
int[] array;
private int top;
private int size;
public Stack(int size) {
this.size=size;
array = new int[size];
top = -1;
}
public void push (int... data) {
int size = data.length;
for(int i=0; i<size; i++)
push(data[i]);
}
public void push (int data) {
if (top<size-1) {
top++;
array[top]=data;
}
}
public final static int ErrorCode = -999;
public int pop() {
if(!isEmpty()) {
int a = array[top];
top--;
return a;
} else return ErrorCode;
}
public int peek() {
return array[top];
}
public boolean isEmpty() {
if(top<0) return true;
else return false;
}
public void printArray() {
int size = top+1;
StringBuffer sb = new StringBuffer();
for(int i=0; i<size; i++)
sb.append(array[i]).append(", ");
System.out.println(sb.toString());
}
}
Labels:
Array,
Data Structures,
Java,
Jeevan,
Jeevan Rex,
Jeevanus,
Stack
Thursday, November 26, 2015
LinkedList print kth to last element
This module returns kth to last element of a Linked List
public String kthLastElement(int k) {
LinkedList L = this;
for(int i=1; i<k; i++) {
L=L.next;
}
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append(L.data).append(", ");
L=L.next;
}
return sb.toString();
}
public String kthLastElement(int k) {
LinkedList L = this;
for(int i=1; i<k; i++) {
L=L.next;
}
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append(L.data).append(", ");
L=L.next;
}
return sb.toString();
}
Check if a LinkedList is a Palindrome
Input:
LinkedList L = new LinkedList("HeleH");
L.printList();
System.out.println(L.isPalindrome());
Program:
import java.util.Stack;
public class LinkedList {
int data;
LinkedList next;
private LinkedList(int data) {
this.data=data;
this.next=null;
}
public LinkedList(String data) {
char[] a = data.toCharArray();
int size=a.length;
if(size>0) {
this.data=a[0];
this.next=null;
for(int i=1; i<size; i++)
append(a[i]);
}
}
public boolean isPalindrome() {
LinkedList L = this;
Stack<Integer> S=new Stack<Integer>();
LinkedList slow = L;
LinkedList fast = L;
while(fast!=null && fast.next!=null) {
S.push(slow.data);
fast = fast.next.next;
slow = slow.next;
}
boolean flag = true;
if(fast!=null) //String has odd number of char
slow = slow.next;
while(slow!=null) {
if(slow.data!=S.pop()) {
flag=false;
break;
}
slow = slow.next;
}
return flag;
}
public void append(int data) {
LinkedList L = this;
while(L.next!=null)
L=L.next;
L.next=new LinkedList(data);
}
public void printList() {
LinkedList L = this;
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append((char)L.data);
L=L.next;
}
System.out.println("String: "+sb.toString());
}
}
This program also shows how to use an integer data linked list to store characters.
LinkedList L = new LinkedList("HeleH");
L.printList();
System.out.println(L.isPalindrome());
Program:
import java.util.Stack;
public class LinkedList {
int data;
LinkedList next;
private LinkedList(int data) {
this.data=data;
this.next=null;
}
public LinkedList(String data) {
char[] a = data.toCharArray();
int size=a.length;
if(size>0) {
this.data=a[0];
this.next=null;
for(int i=1; i<size; i++)
append(a[i]);
}
}
public boolean isPalindrome() {
LinkedList L = this;
Stack<Integer> S=new Stack<Integer>();
LinkedList slow = L;
LinkedList fast = L;
while(fast!=null && fast.next!=null) {
S.push(slow.data);
fast = fast.next.next;
slow = slow.next;
}
boolean flag = true;
if(fast!=null) //String has odd number of char
slow = slow.next;
while(slow!=null) {
if(slow.data!=S.pop()) {
flag=false;
break;
}
slow = slow.next;
}
return flag;
}
public void append(int data) {
LinkedList L = this;
while(L.next!=null)
L=L.next;
L.next=new LinkedList(data);
}
public void printList() {
LinkedList L = this;
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append((char)L.data);
L=L.next;
}
System.out.println("String: "+sb.toString());
}
}
This program also shows how to use an integer data linked list to store characters.
Wednesday, November 25, 2015
Reverse a Single Linked List in Java using Recursion
You can refer for Linked List in Java program here: link
This is a program to reverse a linked list using recursion.
public String reverseList() {
return reverseList(this, new StringBuffer()).toString();
}
private StringBuffer reverseList(LinkedList L, StringBuffer sb) {
if(L!=null) {
reverseList(L.next, sb);
sb.append(L.data).append(", ");
}
return sb;
}
This is a program to reverse a linked list using recursion.
public String reverseList() {
return reverseList(this, new StringBuffer()).toString();
}
private StringBuffer reverseList(LinkedList L, StringBuffer sb) {
if(L!=null) {
reverseList(L.next, sb);
sb.append(L.data).append(", ");
}
return sb;
}
Amazon Interview Question
The Question is this:
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
There are 4 leaves, hence 4 root to leaf paths:
Path Sum
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Expected Answer: 632+6357+6354+654=13997
The Program is this:
public class Main {
public static void main(String[] args) {
BinaryTree T = new BinaryTree(6);
T.specialInsert();
int answer = new AddLinkedListContnents().addLinkedLists(T.rootToLeaf());
System.out.println("answer="+answer);
}
}
//--------------------------------------------------------------------------------------------
import java.util.ArrayList;
public class BinaryTree {
BinaryTree left, right;
int data;
public BinaryTree(int data) {
this.data=data;
this.left=null;
this.right=null;
}
public void specialInsert() {
/* 6
/ \
3 5
/ \ \
2 5 4
/ \
7 4 */
BinaryTree T = this;
T.left=new BinaryTree(3);
T.left.left=new BinaryTree(2);
T.left.right=new BinaryTree(5);
T.left.right.left=new BinaryTree(7);
T.left.right.right=new BinaryTree(4);
T.right=new BinaryTree(5);
T.right.right=new BinaryTree(4);
}
private ArrayList<LinkedList> ArrList;
public ArrayList<LinkedList> rootToLeaf() {
ArrList=new ArrayList<LinkedList>();
rootToLead(this, new ArrayList<Integer>());
for(LinkedList L:ArrList) {
L.printList();
}
return ArrList;
}
private void rootToLead(BinaryTree T, ArrayList<Integer> path) {
if(T!=null) {
path.add(T.data);
if(T.left==null && T.right==null) {
ArrList.add(new LinkedList(path));
} else {
rootToLead(T.left, new ArrayList<>(path));
rootToLead(T.right, new ArrayList<>(path));
}
}
}
}
//--------------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.util.Collections;
public class LinkedList {
LinkedList next;
int data;
private int size;
public LinkedList(int data) {
this.data=data;
this.next=null;
this.size++;
}
public LinkedList(ArrayList<Integer> values) {
Collections.reverse(values);
//Inserts Values in reverse
this.data=values.get(0);
this.next=null;
this.size++;
insert(values);
}
private void insert(ArrayList<Integer> values) {
int size = values.size();
if(size>0) {
LinkedList L = this;
for(int i=1; i<size; i++) {
L.next=new LinkedList(values.get(i));
L=L.next;
this.size++;
}
}
}
public void insert(int data) {
LinkedList L = this;
while(L!=null)
L=L.next;
L.next=new LinkedList(data);
this.size++;
}
public void printList() {
LinkedList L = this;
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append(L.data).append(", ");
L=L.next;
}
System.out.println(sb.toString());
}
public int getSize() {
return size;
}
/*public void setSize(int size) {
this.size = size;
}*/
}
//--------------------------------------------------------------------------------------------
import java.util.ArrayList;
public class AddLinkedListContnents {
public int addLinkedLists(ArrayList<LinkedList> ALs) {
int LargestArraySize=FindLargestArraySize(ALs);
int carry = 0;
StringBuffer sb = new StringBuffer();
for(int i=0; i<LargestArraySize; i++) {
int current_sum = carry;
int size = ALs.size();
for(int j=0; j<size; j++) {
if(ALs.get(j)!=null) {
current_sum=current_sum+ALs.get(j).data;
ALs.set(j, ALs.get(j).next);
}
}
carry=current_sum/10;
current_sum=current_sum%10;
sb.append(current_sum);
current_sum=0;
}
sb.append(carry);
return Integer.parseInt(sb.reverse().toString());
}
private int FindLargestArraySize(ArrayList<LinkedList> ALs) {
int size=0;
for(LinkedList L:ALs) {
if(size<L.getSize())
size=L.getSize();
}
return size;
}
}
//--------------------------------------------------------------------------------------------
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
There are 4 leaves, hence 4 root to leaf paths:
Path Sum
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Expected Answer: 632+6357+6354+654=13997
The Program is this:
public class Main {
public static void main(String[] args) {
BinaryTree T = new BinaryTree(6);
T.specialInsert();
int answer = new AddLinkedListContnents().addLinkedLists(T.rootToLeaf());
System.out.println("answer="+answer);
}
}
//--------------------------------------------------------------------------------------------
import java.util.ArrayList;
public class BinaryTree {
BinaryTree left, right;
int data;
public BinaryTree(int data) {
this.data=data;
this.left=null;
this.right=null;
}
public void specialInsert() {
/* 6
/ \
3 5
/ \ \
2 5 4
/ \
7 4 */
BinaryTree T = this;
T.left=new BinaryTree(3);
T.left.left=new BinaryTree(2);
T.left.right=new BinaryTree(5);
T.left.right.left=new BinaryTree(7);
T.left.right.right=new BinaryTree(4);
T.right=new BinaryTree(5);
T.right.right=new BinaryTree(4);
}
private ArrayList<LinkedList> ArrList;
public ArrayList<LinkedList> rootToLeaf() {
ArrList=new ArrayList<LinkedList>();
rootToLead(this, new ArrayList<Integer>());
for(LinkedList L:ArrList) {
L.printList();
}
return ArrList;
}
private void rootToLead(BinaryTree T, ArrayList<Integer> path) {
if(T!=null) {
path.add(T.data);
if(T.left==null && T.right==null) {
ArrList.add(new LinkedList(path));
} else {
rootToLead(T.left, new ArrayList<>(path));
rootToLead(T.right, new ArrayList<>(path));
}
}
}
}
//--------------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.util.Collections;
public class LinkedList {
LinkedList next;
int data;
private int size;
public LinkedList(int data) {
this.data=data;
this.next=null;
this.size++;
}
public LinkedList(ArrayList<Integer> values) {
Collections.reverse(values);
//Inserts Values in reverse
this.data=values.get(0);
this.next=null;
this.size++;
insert(values);
}
private void insert(ArrayList<Integer> values) {
int size = values.size();
if(size>0) {
LinkedList L = this;
for(int i=1; i<size; i++) {
L.next=new LinkedList(values.get(i));
L=L.next;
this.size++;
}
}
}
public void insert(int data) {
LinkedList L = this;
while(L!=null)
L=L.next;
L.next=new LinkedList(data);
this.size++;
}
public void printList() {
LinkedList L = this;
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append(L.data).append(", ");
L=L.next;
}
System.out.println(sb.toString());
}
public int getSize() {
return size;
}
/*public void setSize(int size) {
this.size = size;
}*/
}
//--------------------------------------------------------------------------------------------
import java.util.ArrayList;
public class AddLinkedListContnents {
public int addLinkedLists(ArrayList<LinkedList> ALs) {
int LargestArraySize=FindLargestArraySize(ALs);
int carry = 0;
StringBuffer sb = new StringBuffer();
for(int i=0; i<LargestArraySize; i++) {
int current_sum = carry;
int size = ALs.size();
for(int j=0; j<size; j++) {
if(ALs.get(j)!=null) {
current_sum=current_sum+ALs.get(j).data;
ALs.set(j, ALs.get(j).next);
}
}
carry=current_sum/10;
current_sum=current_sum%10;
sb.append(current_sum);
current_sum=0;
}
sb.append(carry);
return Integer.parseInt(sb.reverse().toString());
}
private int FindLargestArraySize(ArrayList<LinkedList> ALs) {
int size=0;
for(LinkedList L:ALs) {
if(size<L.getSize())
size=L.getSize();
}
return size;
}
}
//--------------------------------------------------------------------------------------------
Tuesday, November 24, 2015
Binary Tree Insertion
NOTE: This is not a BinarySearchTree
public class BinaryTree {
BinaryTree left, right;
int data;
public BinaryTree(int data) {
this.data=data;
this.left=null;
this.right=null;
}
public void insert(int data) {
BinaryTree T = this;
Queue<BinaryTree> Q = new LinkedList<BinaryTree>();
Q.add(T);
while(Q.size()>0) {
BinaryTree Current = Q.remove();
if(Current.left==null) {
Current.left=new BinaryTree(data);
break;
}
else if(Current.right==null) {
Current.right=new BinaryTree(data);
break;
}
else {
Q.add(Current.left);
Q.add(Current.right);
}
}
}
}
public class BinaryTree {
BinaryTree left, right;
int data;
public BinaryTree(int data) {
this.data=data;
this.left=null;
this.right=null;
}
public void insert(int data) {
BinaryTree T = this;
Queue<BinaryTree> Q = new LinkedList<BinaryTree>();
Q.add(T);
while(Q.size()>0) {
BinaryTree Current = Q.remove();
if(Current.left==null) {
Current.left=new BinaryTree(data);
break;
}
else if(Current.right==null) {
Current.right=new BinaryTree(data);
break;
}
else {
Q.add(Current.left);
Q.add(Current.right);
}
}
}
}
Monday, November 23, 2015
Delete Node if you have access only to that node
The Linked List program is available here: link
public void deleteNode(LinkedList Node) {
if(Node!=null && Node.next!=null) {
Node.data=Node.next.data;
Node.next=Node.next.next;
}
}
public void deleteNode(LinkedList Node) {
if(Node!=null && Node.next!=null) {
Node.data=Node.next.data;
Node.next=Node.next.next;
}
}
Kth to Last Element in Linked List
The Linked List program is available here: link
public String kthLastElement(int k) {
LinkedList L = this;
for(int i=1; i<k; i++) {
L=L.next;
}
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append(L.data).append(", ");
L=L.next;
}
return sb.toString();
}
public String kthLastElement(int k) {
LinkedList L = this;
for(int i=1; i<k; i++) {
L=L.next;
}
StringBuffer sb = new StringBuffer();
while(L!=null) {
sb.append(L.data).append(", ");
L=L.next;
}
return sb.toString();
}
Remove Duplicates in Linked List
The Linked List program is available here: link
public void RemoveDuplicatesWithBuffer() {
LinkedList L = this;
LinkedList previous = null;
HashSet<Integer> H = new HashSet<>();
while(L!=null) {
if(H.contains(L.data)) {
previous.next = L.next;
} else {
H.add(L.data);
previous=L;
}
L=L.next;
}
}
public void RemoveDuplicatesWithoutBuffer() {
LinkedList L = this;
while(L!=null) {
LinkedList runner = L;
while(runner.next!=null) {
if(runner.next.data==L.data)
runner.next=runner.next.next;
else
runner=runner.next;
}
L=L.next;
}
}
public void RemoveDuplicatesWithBuffer() {
LinkedList L = this;
LinkedList previous = null;
HashSet<Integer> H = new HashSet<>();
while(L!=null) {
if(H.contains(L.data)) {
previous.next = L.next;
} else {
H.add(L.data);
previous=L;
}
L=L.next;
}
}
public void RemoveDuplicatesWithoutBuffer() {
LinkedList L = this;
while(L!=null) {
LinkedList runner = L;
while(runner.next!=null) {
if(runner.next.data==L.data)
runner.next=runner.next.next;
else
runner=runner.next;
}
L=L.next;
}
}
Sunday, November 8, 2015
Find all Root to Leaf Path of a Binary Tree
This program uses the Binary Search Tree program available here: link
The same program can also be used for Binary Tree
public void FindAllRoot2LeefPath() {
ArrList = new ArrayList<CustomLinkedList>();
FindAllRoot2LeefPath(this, new ArrayList<Integer>());
for(CustomLinkedList L:ArrList) {
L.printList();
}
}
public ArrayList<CustomLinkedList> ArrList;
private ArrayList<Integer> FindAllRoot2LeefPath(BinarySearchTree T, ArrayList<Integer> path) {
if(T!=null){
path.add(T.data);
if(T.left==null && T.right==null) {
CustomLinkedList L = new CustomLinkedList(path.get(0));
L.appendList(path);
ArrList.add(L);
System.out.println(path);
} else {
FindAllRoot2LeefPath(T.left, new ArrayList<>(path));
FindAllRoot2LeefPath(T.right, new ArrayList<>(path));
}
}
return path;
}
/*-----------------------------------------------------------------------------------------------*/
CustomLinkedList is a program given here: link
I added one more method there for this:
public void appendList(ArrayList<Integer> ArrList) {
int size = ArrList.size();
/*Starts from i=1 because
* Head Element already need to be added when creating a new list*/
for(int i=1;i<size;i++) {
append(ArrList.get(i));
}
}
The same program can also be used for Binary Tree
public void FindAllRoot2LeefPath() {
ArrList = new ArrayList<CustomLinkedList>();
FindAllRoot2LeefPath(this, new ArrayList<Integer>());
for(CustomLinkedList L:ArrList) {
L.printList();
}
}
public ArrayList<CustomLinkedList> ArrList;
private ArrayList<Integer> FindAllRoot2LeefPath(BinarySearchTree T, ArrayList<Integer> path) {
if(T!=null){
path.add(T.data);
if(T.left==null && T.right==null) {
CustomLinkedList L = new CustomLinkedList(path.get(0));
L.appendList(path);
ArrList.add(L);
System.out.println(path);
} else {
FindAllRoot2LeefPath(T.left, new ArrayList<>(path));
FindAllRoot2LeefPath(T.right, new ArrayList<>(path));
}
}
return path;
}
/*-----------------------------------------------------------------------------------------------*/
CustomLinkedList is a program given here: link
I added one more method there for this:
public void appendList(ArrayList<Integer> ArrList) {
int size = ArrList.size();
/*Starts from i=1 because
* Head Element already need to be added when creating a new list*/
for(int i=1;i<size;i++) {
append(ArrList.get(i));
}
}
Height of a Binary Tree
This program uses the Binary Search Tree program available here: link
The same program can also be used for Binary Tree
public int FindHeight() {
return FindHeight(this);
}
private int FindHeight(BinarySearchTree T) {
if(T!=null) {
return max(FindHeight(T.left), FindHeight(T.right))+1;
} else return -1;
}
private int max(int a, int b) {
if (a>b) return a;
else return b;
}
The same program can also be used for Binary Tree
public int FindHeight() {
return FindHeight(this);
}
private int FindHeight(BinarySearchTree T) {
if(T!=null) {
return max(FindHeight(T.left), FindHeight(T.right))+1;
} else return -1;
}
private int max(int a, int b) {
if (a>b) return a;
else return b;
}
Level Order Traversal or BFS in a Binary Tree
In a Binary Tree, Level Order Traversal is also known as Breadth-first search or BFS. This BFS is different from a non-Binary Tree Graph.
This program uses the Binary Search Tree program available here: link
The same program can also be used for Binary Tree
//BinarySearchTree Reffers to the link given above
public String LevelOrder() {
Queue<BinarySearchTree> Q = new LinkedList<BinarySearchTree>();
StringBuffer sb = new StringBuffer();
Q.add(this); //Inserting Root Node to Queue
while(Q.size()!=0) {
BinarySearchTree CurrentNode = Q.remove();
sb.append(CurrentNode.data).append(", ");
if(CurrentNode.left!=null)
Q.add(CurrentNode.left);
if(CurrentNode.right!=null)
Q.add(CurrentNode.right);
}
return sb.toString();
}
This program uses the Binary Search Tree program available here: link
The same program can also be used for Binary Tree
//BinarySearchTree Reffers to the link given above
public String LevelOrder() {
Queue<BinarySearchTree> Q = new LinkedList<BinarySearchTree>();
StringBuffer sb = new StringBuffer();
Q.add(this); //Inserting Root Node to Queue
while(Q.size()!=0) {
BinarySearchTree CurrentNode = Q.remove();
sb.append(CurrentNode.data).append(", ");
if(CurrentNode.left!=null)
Q.add(CurrentNode.left);
if(CurrentNode.right!=null)
Q.add(CurrentNode.right);
}
return sb.toString();
}
Saturday, November 7, 2015
Prof. Donald Johanson on Evolution vs Creationism
I am very excited that Prof. Donald C. Johanson, one of the most significant paleoanthropologist alive today has answered my question.
I enrolled to a course in edX named "Human Origins" conducted by him. I had the opportunity to ask him few questions and in one of it he has mentioned my name. I feel very much privileged.
I thank edX and Arizona State University for creating this opportunity for people around the world to interact with Prof. Don Johanson and learn a lot from him. The course was very interesting for me.
I enrolled to a course in edX named "Human Origins" conducted by him. I had the opportunity to ask him few questions and in one of it he has mentioned my name. I feel very much privileged.
I thank edX and Arizona State University for creating this opportunity for people around the world to interact with Prof. Don Johanson and learn a lot from him. The course was very interesting for me.
Thursday, November 5, 2015
Simple Binary Search Tree using Java
Input: List of Intigers
public class BinarySearchTree {
BinarySearchTree left, right;
int data;
public BinarySearchTree(int data) {
System.out.println("newNode "+data);
this.data = data;
left=null;
right=null;
}
public void insertElement(int... element) {
int size=element.length;
for(int i=0; i<size; i++) {
System.out.println(element[i]);
insertElement(this, element[i]);
}
}
public void insertElement(int element) {
insertElement(this,element);
}
private void insertElement(BinarySearchTree T, int element) {
if(element==T.data) {
System.out.println("ERROR: Data already exist");
} else if(T.left == null && T.right ==null) {
if(element<T.data)
T.left=new BinarySearchTree(element);
else
T.right=new BinarySearchTree(element);
} else if(T.left == null) {
if(element<T.data)
T.left=new BinarySearchTree(element);
else
insertElement(T.right, element);
} else if(T.right == null) {
if(element>T.data)
T.right=new BinarySearchTree(element);
else
insertElement(T.left, element);
} else { //Root has both Left and Right
if(element<T.data)
insertElement(T.left, element);
else
insertElement(T.right, element);
}
}
public String PreOrder() {
return PreOrder(new StringBuffer(), this).toString();
}
private StringBuffer PreOrder(StringBuffer sb, BinarySearchTree T) {
if(T!=null) {
PreOrder(sb, T.left);
PreOrder(sb, T.right);
sb.append(T.data).append(", ");
return sb;
} else return sb;
}
public String PostOrder() {
return PostOrder(new StringBuffer(), this).toString();
}
private StringBuffer PostOrder(StringBuffer sb, BinarySearchTree T) {
if(T!=null) {
sb.append(T.data).append(", ");
PreOrder(sb, T.left);
PreOrder(sb, T.right);
return sb;
} else return sb;
}
public String InOrder() {
return InOrder(new StringBuffer(), this).toString();
}
private StringBuffer InOrder(StringBuffer sb, BinarySearchTree T) {
if(T!=null) {
InOrder(sb, T.left);
sb.append(T.data).append(", ");
InOrder(sb, T.right);
return sb;
} else return sb;
}
}
Wednesday, November 4, 2015
Linked List Binary Search
This is a program to perform Binary Search in a Sorted Linked List
Input: Sorted List of Elements:
public int Search(int element) {
return Search(element, 1, sizeOfList());
}
private int Search(int element, int StartinDex, int EndInDex) {
LinkedList L = this;
int middle = (StartinDex+EndInDex)/2;
if(L.getValue(middle)==element) {
return middle;
} else if(L.getValue(middle)<element) {
return Search(element, middle+1, EndInDex);
} else {
return Search(element, StartinDex, middle-1);
}
}
For Linked List Code, look at this link
Input: Sorted List of Elements:
public int Search(int element) {
return Search(element, 1, sizeOfList());
}
private int Search(int element, int StartinDex, int EndInDex) {
LinkedList L = this;
int middle = (StartinDex+EndInDex)/2;
if(L.getValue(middle)==element) {
return middle;
} else if(L.getValue(middle)<element) {
return Search(element, middle+1, EndInDex);
} else {
return Search(element, StartinDex, middle-1);
}
}
For Linked List Code, look at this link
Tuesday, November 3, 2015
Reverse a Single Linked List in Java
Input:
LinkedList ll = new LinkedList(0);
ll.append(1);
ll.appendList(2,3,4,5,6,7,8,9);
ll.insertFirst(-1);
ll.insertMiddle(33, 3);
ll.printList();
ll.ReverseList();
ll.printList();
ll.ReverseList();
ll.printList();
Program:
public class LinkedList {
LinkedList next;
int data;
private int size;
public static final int ERROR_CODE = -99999;
public LinkedList(int data) {
next = null;
this.data = data;
this.size=0;
}
public int sizeOfList() {
return ((this.size)+1);
}
public void appendList(int... data) {
int length = data.length;
for(int i=0; i<length; i++)
append(data[i]);
}
public void append(int data) {
LinkedList L = this;
for(; L.next!=null; L=L.next) {
}
L.next = new LinkedList(data);
this.size++;
}
public void printList() {
LinkedList L = this;
StringBuffer sb = new StringBuffer();
for(; L.next!=null; L=L.next) {
sb.append(L.data);
sb.append(", ");
}
sb.append(L.data);
sb.append(", ");
System.out.println(sb.toString());
}
public int removeLast() {
LinkedList L = this;
for(;L.next.next!=null;L=L.next) {}
int pop = L.next.data;
L.next=null;
this.size--;
return pop;
}
public void insertFirst(int data) {
LinkedList L = this;
int headData = L.data;
LinkedList temp = L.next;
LinkedList newNode = new LinkedList(headData);
newNode.next = temp;
L.data = data;
L.next = newNode;
this.size++;
}
public void Rotate(int times) {
for(int i=0;i<times;i++) {
insertFirst(removeLast());
}
insertFirst(removeLast());
}
private int removeHead() {
LinkedList L = this;
if(L.next==null) {
System.out.println("Single Element List can't be removed");
return ERROR_CODE;
} else {
int val = L.data;
LinkedList temp = L.next.next;
L.data=L.next.data;
L.next=temp;
this.size--;
return val;
}
}
public void insertMiddle(int data, int possition) {
if(possition==1) insertFirst(data);
else if(possition==sizeOfList()) append(data);
else {
LinkedList L = this;
for(int i=2; i<possition; i++)
L=L.next;
LinkedList newNode = new LinkedList(data);
LinkedList temp = L.next;
L.next = newNode;
L.next.next=temp;
this.size++;
}
}
public int remove(int possition) {
if(possition==1) return removeHead();
else if(possition<=this.size) {
LinkedList L = this;
possition--;
for(int i=1; i<possition; i++)
L=L.next;
int val = L.next.data;
L.next=L.next.next;
this.size--;
return val;
} else if(possition==sizeOfList()) {
return removeLast();
}
else {
System.out.println("Error, no possition found");
return ERROR_CODE;
}
}
public int Replace(int data, int possition) {
LinkedList L = this;
if(possition>sizeOfList()) {
return ERROR_CODE;
} else if(possition==1) {
int val = L.data;
L.data=data;
return val;
} else {
for(int i=2; i<possition; i++)
L=L.next;
int val = L.next.data;
L.next.data=data;
return val;
}
}
public int getValue(int possition) {
LinkedList L = this;
if(possition>sizeOfList()) {
return ERROR_CODE;
} else if(possition==1) {
return L.data;
} else {
for(int i=2; i<possition; i++)
L=L.next;
return L.next.data;
}
}
public void SwapPossitions(int a, int b) {
if(a>sizeOfList()||b>sizeOfList()) {
System.out.println("Error Out of Bound Possition");
} else if(a==b) return;
else {
Replace(Replace(getValue(a), b), a);
}
}
public void ReverseList() {
int half = sizeOfList()/2;
for(int i=1; i<half; i++) {
SwapPossitions(i, (sizeOfList()-i+1));
}
}
}
LinkedList ll = new LinkedList(0);
ll.append(1);
ll.appendList(2,3,4,5,6,7,8,9);
ll.insertFirst(-1);
ll.insertMiddle(33, 3);
ll.printList();
ll.ReverseList();
ll.printList();
ll.ReverseList();
ll.printList();
Program:
public class LinkedList {
LinkedList next;
int data;
private int size;
public static final int ERROR_CODE = -99999;
public LinkedList(int data) {
next = null;
this.data = data;
this.size=0;
}
public int sizeOfList() {
return ((this.size)+1);
}
public void appendList(int... data) {
int length = data.length;
for(int i=0; i<length; i++)
append(data[i]);
}
public void append(int data) {
LinkedList L = this;
for(; L.next!=null; L=L.next) {
}
L.next = new LinkedList(data);
this.size++;
}
public void printList() {
LinkedList L = this;
StringBuffer sb = new StringBuffer();
for(; L.next!=null; L=L.next) {
sb.append(L.data);
sb.append(", ");
}
sb.append(L.data);
sb.append(", ");
System.out.println(sb.toString());
}
public int removeLast() {
LinkedList L = this;
for(;L.next.next!=null;L=L.next) {}
int pop = L.next.data;
L.next=null;
this.size--;
return pop;
}
public void insertFirst(int data) {
LinkedList L = this;
int headData = L.data;
LinkedList temp = L.next;
LinkedList newNode = new LinkedList(headData);
newNode.next = temp;
L.data = data;
L.next = newNode;
this.size++;
}
public void Rotate(int times) {
for(int i=0;i<times;i++) {
insertFirst(removeLast());
}
insertFirst(removeLast());
}
private int removeHead() {
LinkedList L = this;
if(L.next==null) {
System.out.println("Single Element List can't be removed");
return ERROR_CODE;
} else {
int val = L.data;
LinkedList temp = L.next.next;
L.data=L.next.data;
L.next=temp;
this.size--;
return val;
}
}
public void insertMiddle(int data, int possition) {
if(possition==1) insertFirst(data);
else if(possition==sizeOfList()) append(data);
else {
LinkedList L = this;
for(int i=2; i<possition; i++)
L=L.next;
LinkedList newNode = new LinkedList(data);
LinkedList temp = L.next;
L.next = newNode;
L.next.next=temp;
this.size++;
}
}
public int remove(int possition) {
if(possition==1) return removeHead();
else if(possition<=this.size) {
LinkedList L = this;
possition--;
for(int i=1; i<possition; i++)
L=L.next;
int val = L.next.data;
L.next=L.next.next;
this.size--;
return val;
} else if(possition==sizeOfList()) {
return removeLast();
}
else {
System.out.println("Error, no possition found");
return ERROR_CODE;
}
}
public int Replace(int data, int possition) {
LinkedList L = this;
if(possition>sizeOfList()) {
return ERROR_CODE;
} else if(possition==1) {
int val = L.data;
L.data=data;
return val;
} else {
for(int i=2; i<possition; i++)
L=L.next;
int val = L.next.data;
L.next.data=data;
return val;
}
}
public int getValue(int possition) {
LinkedList L = this;
if(possition>sizeOfList()) {
return ERROR_CODE;
} else if(possition==1) {
return L.data;
} else {
for(int i=2; i<possition; i++)
L=L.next;
return L.next.data;
}
}
public void SwapPossitions(int a, int b) {
if(a>sizeOfList()||b>sizeOfList()) {
System.out.println("Error Out of Bound Possition");
} else if(a==b) return;
else {
Replace(Replace(getValue(a), b), a);
}
}
public void ReverseList() {
int half = sizeOfList()/2;
for(int i=1; i<half; i++) {
SwapPossitions(i, (sizeOfList()-i+1));
}
}
}
Subscribe to:
Posts (Atom)