private class Stack {
Node top;
Object pop() {
if(top != null){
Object item = top.data;
top = top.next;
return item;
}
return null;
}
void push(Object item) {
Node t = new Node(item);
t.next = top;
top = t;
}
Object peek() {
if(top != null)
return top.data;
else
return null;
}
}
private class Node {
Object data;
Node next;
Node(Object item){
data = item;
}
}class Queue {
Node first, last;
void enqueue(Object item) {
if(first == null){
last = new Node(item);
first = last;
} else {
last.next = new Node(item);
last = last.next;
}
}
Object dequeue() {
if(first != null){
Object item = first.data;
first = first.next;
return item;
}
return null;
}
}
class Node {
Object data;
Node next;
Node(Object item){
data = item;
}
}void bfs(Node root) {
Queue queue = new Queue();
queue.enqueue(root);
while(!queue.isEmpty()){
Node node = (Node)queue.dequeue();
if(node.getLeft() != null){
queue.enqueue(node.getLeft());
}
if(node.getRight() != null){
queue.enqueue(node.getRight());
}
}
}
private class Node {
private Object data;
private Node left;
private Node right;
Node(Object item, Node left, Node right){
this.data = item;
this.left = left;
this.right = right;
}
public Object getData() {
return data;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
}
private class Queue {
Node first, last;
void enqueue(Object item) {
if(first == null){
last = new Node(item);
first = last;
} else {
last.next = new Node(item);
last = last.next;
}
}
Object dequeue() {
if(first != null){
Object item = first.data;
first = first.next;
return item;
}
return null;
}
boolean isEmpty() {
if(first != null)
return false;
else
return true;
}
}void preOrderDFS(Node root) {
if(root == null)
return;
Stack stack = new Stack();
stack.push(root);
while(!stack.isEmpty()){
Node node = (Node)stack.pop();
Node left = node.getLeft();
Node right = node.getRight();
if(right != null){
stack.push(right);
}
if(left != null){
stack.push(left);
}
}
}
void inOrderDFS(Node root) {
if(root == null)
return;
Stack stack = new Stack();
Node p = root;
while(!stack.isEmpty() || p != null){
if(p != null){ // if it is not null, push to stack and go down the tree to left
stack.push(p);
p = p.left;
} else { // if no left child pop stack, process the node then let p point to the right
Node temp = (Node)stack.pop();
p = temp.right;
}
}
}
void postOrderDFS(Node root) {
if(root == null)
return;
Stack stack = new Stack();
stack.push(root);
while(!stack.isEmpty()){
Node node = (Node)stack.peek();
Node left = node.getLeft();
Node right = node.getRight();
if(left == null && right == null){ // leaf node
stack.pop();
} else {
if(right != null){
stack.push(right);
node.right = null;
}
if(left != null){
stack.push(left);
node.left = null;
}
}
}
}
private class Stack {
Node top;
Object pop() {
if(top != null){
Object item = top.data;
top = top.next;
return item;
}
return null;
}
void push(Object item) {
Node t = new Node(item);
t.next = top;
top = t;
}
Object peek() {
if(top != null)
return top.data;
else
return null;
}
boolean isEmpty() {
if(peek()!=null){
return false;
} else {
return true;
}
}
}
private class Node {
private Object data;
private Node left;
private Node right;
Node(Object item, Node left, Node right){
this.data = item;
this.left = left;
this.right = right;
}
public Object getData() {
return data;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
}int binarySearch(int[] a, int target) {
int low = 0;
int high = a.length - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if(a[mid] < target) {
low = mid + 1;
} else if(a[mid] > target){
high = mid - 1;
} else {
return mid;
}
}
return -1; // Error
}
int binarySearchRecursive(int[] a, int target, int low, int high) {
if (low > high) return -1; // Error
int mid = (low + high) / 2;
if (a[mid] < target) {
return binarySearchRecursive(a, target, mid + 1, high);
} else if(a[mid] > target){
return binarySearchRecursive(a, target, low, mid - 1);
} else{
return mid;
}
}void mergesort(int[] array) {
int[] helper = new int[array.length];
mergesort(array, helper, 0, array.length - 1);
}
void mergesort(int[] array, int[] helper, int low, int high){
if (low < high) {
int middle = (low + high) / 2;
mergesort(array, helper, low, middle); // Sort left half
mergesort(array, helper, middle+1, high); // Sort right half
merge(array, helper, low, middle, high); // Merge them
}
}
void merge(int[] array, int[] helper, int low, int middle, int high) {
/* Copy both halves into a helper array */
for (int i = low; i <= high; i++) {
helper[i] = array[i];
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
/* Iterate through helper array. Compare the left and right
* half, copying back the smaller element from the two halves
* into the original array. */
while (helperLeft <= middle && helperRight <= high) {
if (helper[helperLeft] <= helper[helperRight]) {
array[current] = helper[helperLeft];
helperLeft++;
} else { // If right element is smaller than left element
array[current] = helper[helperRight];
helperRight++;
}
current++;
}
/* Copy the rest of the left side of the array into the
* target array */
int remaining = middle - helperLeft;
for (int i = 0; i <= remaining; i++) {
array [current + i] = helper[helperLeft + i];
}
}void quickSort(int[] array) {
quickSort(array, 0, array.length-1);
}
void quickSort(int[] array, int left, int right) {
int index = partition(array, left, right);
if (left < index - 1){ // Sort left half
quickSort(array, left, index - 1);
}
if (index < right) { // Sort right half
quickSort(array, index, right);
}
}
int partition(int[] array, int left, int right) {
int pivot = array[(left + right) / 2]; // Pick pivot point
while (left <= right) {
// Find element on left that should be on right
while (array[left] < pivot)
left++;
// Find element on right that should be on left
while (array[right] > pivot)
right--;
// Swap elements, and move left and right indices
if (left <= right) {
swap(array, left, right); // swaps elements
left++;
right--;
}
}
return left;
}
void swap(int array[], int left, int right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}void selectionSort(int[] array){
int i, j, first;
for (i = array.length - 1; i > 0; i--){
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j++){ //locate smallest element between positions 1 and i.
if(array[j] > array[first])
first = j;
}
swap(array, first, i); //swap smallest found with element in position i.
}
}
void swap(int array[], int left, int right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}void bubbleSort(int[] array) {
boolean flag = true; // set flag to true to begin first pass
while (flag) {
flag = false; //set flag to false awaiting a possible swap
for (int j = 0; j<array.length-1; j++) {
if (array[j] > array[j+1]){
swap(array, j, j+1);
flag = true; //shows a swap occurred
}
}
}
}
void swap(int array[], int left, int right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}void radixSort(int[] a){
int i, m = a[0], exp = 1, n = a.length;
int[] b = new int[10];
for (i = 1; i < n; i++)
if (a[i] > m)
m = a[i];
while (m / exp > 0){
int[] bucket = new int[10];
for (i = 0; i < n; i++)
bucket[(a[i] / exp) % 10]++;
for (i = 1; i < 10; i++)
bucket[i] += bucket[i - 1];
for (i = n - 1; i >= 0; i--)
b[--bucket[(a[i] / exp) % 10]] = a[i];
for (i = 0; i < n; i++)
a[i] = b[i];
exp *= 10;
}
}f(n)=g(n)+h(n) where n is the last node on the path, g(n) is the cost of the path from the start node to n, and h(n) is a heuristic that estimates the cost of the cheapest path from n to the goal. public class Activity extends ApplicationContext {
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
}
is the right shift operator.
public final class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Implementation of the Factory Design Pattern :
public interface Shape {
void draw();
}public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of circle
shape3.draw();
}
}Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
public int factorial(int n) {
if (n <= 1) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else
// recursion step
return n * factorial(n - 1);
}int fibonacci(int n) {
int[] memoizationArray = new int[n+1];
Arrays.fill(memoizationArray, -1);
return fibonacci(n, memoizationArray);
}
int fibonacci(int n, int[] a) {
if (n <= 2) {
return 1;
} else if (a[n] != -1) {
return a[n]; // Return cached result.
} else {
a[n] = fibonacci(n-1, a) + fibonacci(n-2, a); // Cache result
}
return a[n];
}class Shape{
void draw(){}
}
class Circle extends Shape{
private int x, y, r;
Circle(int x, int y, int r){
this.x = x;
this.y = y;
this.r = r;
}
// For brevity, I've omitted getX(), getY(), and getRadius() methods.
@Override
void draw(){
System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")");
}
}
class Rectangle extends Shape{
private int x, y, w, h;
Rectangle(int x, int y, int w, int h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
// For brevity, I've omitted getX(), getY(), getWidth(), and getHeight()
// methods.
@Override
void draw(){
System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," +
h + ")");
}
}
class Shapes{
public static void main(String[] args){
Shape[] shapes = { new Circle(10, 20, 30),
new Rectangle(20, 30, 40, 50) };
for (int i = 0; i < shapes.length; i++)
shapes[i].draw();
}
}public interface Predator {
boolean chasePrey(Prey p);
void eatPrey(Prey p);
}
public class Lion implements Predator {
@Override
public boolean chasePrey(Prey p) {
// programming to chase prey p (specifically for a lion)
}
@Override
public void eatPrey(Prey p) {
// programming to eat prey p (specifically for a lion)
}
}public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
@Override
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}
}
Output :
The static method in Animal
The instance method in Catpublic class DataArtist {
public void draw(String s) {}
public void draw(int i) {}
public void draw(double f) {}
public void draw(int i, double f) {}
}WeakReference weakWidget = new WeakReference(widget);private List<String> getMostFrequentWords(String document, int numOfWords){
List<String> mostFrequentWords = new ArrayList<>();
if(numOfWords<=0 || TextUtils.isEmpty(document)){
return mostFrequentWords;
}
String[] tokens = document.split("\\s*[^a-zA-Z']*?\\s+");
Map<String, Integer> wordFrequencies = new HashMap<>();
for(String token : tokens){
if(wordFrequencies.containsKey(token))
wordFrequencies.put(token, wordFrequencies.get(token) + 1);
else
wordFrequencies.put(token, 1);
}
PriorityQueue maxHeap = new PriorityQueue(wordFrequencies.size(), new Comparator<Object>() {
@Override
public int compare(Object lhs, Object rhs) {
int freq1 = ((Word)lhs).getFrequency();
int freq2 = ((Word)rhs).getFrequency();
if(freq1 < freq2){
return 1;
} else if(freq1 > freq2){
return -1;
} else {
return 0;
}
}
});
for ( String key : wordFrequencies.keySet() ) {
Word word = new Word(key, wordFrequencies.get(key));
maxHeap.add(word);
}
for(int i=0; maxHeap.size()>0 && i<numOfWords; i++){
Word word = (Word) maxHeap.poll();
mostFrequentWords.add(word.getText());
}
return mostFrequentWords;
}
private class Word{
// region Member Variables
private String text;
private int frequency;
// endregion
// region Constructors
public Word(String text, int frequency){
this.text = text;
this.frequency = frequency;
}
// endregion
// region Getters
public int getFrequency() {
return this.frequency;
}
public String getText() {
return this.text;
}
// endregion
// region Setters
public void setText(String text) {
this.text = text;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
// endregion
}public String lcs(String a, String b){
if(TextUtils.isEmpty(a) || TextUtils.isEmpty(b))
return "";
else if(a.charAt(a.length()-1) == b.charAt(b.length()-1)){
return lcs(a.substring(0, a.length()-1), b.substring(0, b.length()-1)) + a.substring(a.length()-1);
} else {
return maxSequence(lcs(a.substring(0, a.length()-1), b.substring(0, b.length())),
lcs(a.substring(0, a.length()), b.substring(0, b.length()-1)) );
}
}
private String maxSequence(String firstSequence, String secondSequence){
if(firstSequence.length() > secondSequence.length()){
return firstSequence;
} else {
return secondSequence;
}
} public String stringCompression(String uncompressedString){
String compressedString = "";
if(TextUtils.isEmpty(uncompressedString))
return "";
int repeatedFreqCount = 0;
for(int i=0; i<uncompressedString.length(); i++){
if(i == 0){
repeatedFreqCount++;
} else {
if(uncompressedString.charAt(i) == uncompressedString.charAt(i-1)){
repeatedFreqCount++;
} else {
compressedString += uncompressedString.charAt(i-1)+""+repeatedFreqCount;
repeatedFreqCount = 1;
}
if(i == uncompressedString.length()-1){
compressedString += uncompressedString.charAt(i)+""+repeatedFreqCount;
}
}
}
if(compressedString.length() < uncompressedString.length()){
return compressedString;
} else {
return uncompressedString;
}
}public void twoSum(int[] array, int sum){
Map<Integer, List<Integer>> map = new HashMap<>();
for(int i=0; i<array.length; i++){
if(map.containsKey(array[i])){
List<Integer> indices = map.get(array[i]);
indices.add(i);
map.put(array[i], indices);
} else {
List<Integer> indices = new ArrayList<>();
indices.add(i);
map.put(array[i], indices);
}
}
for(int i=0; i<array.length; i++){
int b = sum - array[i];
if(map.containsKey(b)){
List<Integer> indices = map.get(b);
for(Integer index : indices){
if(i!=index && i < index){
System.out.println(String.format("twoSum() : Indices %d and %d add up to the target %d", i, index, sum));
}
}
}
}
}public static int BOARD_DIMENSION = 9;
public boolean isSudokuBoardValid(int[][] board){
// check rows
for(int i=0; i<BOARD_DIMENSION; i++){
if(!isRowValid(board, i)){
return false;
}
}
// check columns
for(int j=0; j<BOARD_DIMENSION; j++){
if(!isColumnValid(board, j)){
return false;
}
}
// check sections
int i=0;
int j=0;
for( ; i<BOARD_DIMENSION; ){
for( ; j<BOARD_DIMENSION; ){
if(!isRegionValid(board, i, i + 2, j, j + 2)){
return false;
}
j+=3;
}
i+=3;
}
return true;
}
private boolean isRowValid(int[][] board, int row){
Set<Integer> uniqueNumbers = new HashSet<>();
for(int i=0; i<BOARD_DIMENSION; i++){
int value = board[row][i];
if(value<1 || value>9){
return false;
}
if(uniqueNumbers.contains(value)){ // found duplicate
return false;
} else {
uniqueNumbers.add(value);
}
}
return true;
}
private boolean isColumnValid(int[][] board, int column){
Set<Integer> uniqueNumbers = new HashSet<>();
for(int i=0; i<BOARD_DIMENSION; i++){
int value = board[i][column];
if(value<1 || value>9){
return false;
}
if(uniqueNumbers.contains(value)){ // found duplicate
return false;
} else {
uniqueNumbers.add(value);
}
}
return true;
}
private boolean isRegionValid(int[][] board, int rowStartIndex, int rowEndIndex, int columnStartIndex, int columnEndIndex){
Set<Integer> uniqueNumbers = new HashSet<>();
for(int i=rowStartIndex; i <rowEndIndex; i++){
for(int j=columnStartIndex; j<columnEndIndex; j++){
int value = board[i][j];
if(value<1 || value>9){
return false;
}
if(uniqueNumbers.contains(value)){ // found duplicate
return false;
} else {
uniqueNumbers.add(value);
}
}
}
return true;
}private String multiplesOfThree(int[] a){
String indices = "";
for(int i=0; i<a.length; i++){
if(a[i] % 3 == 0){
if(i == a.length){
indices += i+"";
} else {
indices += i+",";
}
}
}
return indices.substring(0, indices.length()-1);
}int fibonacci(int n) {
int[] memoizationArray = new int[n+1];
Arrays.fill(memoizationArray, -1);
return fibonacci(n, memoizationArray);
}
int fibonacci(int n, int[] a) {
if (n <= 2) {
return 1;
} else if (a[n] != -1) {
return a[n]; // Return cached result.
} else {
a[n] = fibonacci(n-1, a) + fibonacci(n-2, a); // Cache result
}
return a[n];
}public String sum(String a, String b) {
int d1, d2, tempSum;
int carry = 0;
int sumLength = (a.length()>b.length()) ? a.length() : b.length();
StringBuilder sb = new StringBuilder(sumLength);
int i=a.length()-1;
int j=b.length()-1;
while(i>=0 || j>=0){
d1 = 0;
d2 = 0;
if(i>=0) {
d1 = a.charAt(i) - '0';
i--;
}
if(j>=0) {
d2 = b.charAt(j) - '0';
j--;
}
tempSum = d1+d2+carry;
if(tempSum>9){
carry = tempSum / 10;
tempSum = tempSum % 10;
} else {
carry = 0;
}
sb.insert(0, tempSum);
}
return sb.toString();
}get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.public class LRUCache {
// region Member Variables
private int capacity;
private Map<Integer, Node> data;
private Node head;
private Node tail;
// endregion
// region Constructors
public LRUCache(int capacity) {
this.capacity = capacity;
this.data = new HashMap<>();
}
// endregion
public int get(int key){
// Existing key
if(data.containsKey(key)){
// Move to first
Node node = data.get(key);
moveFirst(node);
return node.value;
}
// Not found
return -1;
}
public void set(int key, int value){
// Existing slot
if(data.containsKey(key)){
Node node = data.get(key);
node.value = value;
moveFirst(node);
return;
}
// Out of capacity, cleaning the oldest slot
if(data.size() >= capacity){
int id = tail.key;
removeLast();
data.remove(id);
}
// New slot
Node node = new Node(key, value);
add(node);
data.put(key, node);
}
private void add(Node node){
// Reset position
node.prev = null;
node.next = null;
// First element
if(head == null){
head = node;
tail = node;
return;
}
// Existing element
head.prev = node;
node.next = head;
head = node;
}
private void remove(Node node){
// Nothing to do
if(node == null || head == null){
return;
}
// The only one item
if(head == tail && node == head){
head = null;
tail = null;
return;
}
// Remove from head
if(node == head){
head.next.prev = null;
head = head.next;
return;
}
// Remove from end
if(node == tail){
tail.prev.next = null;
tail = tail.prev;
return;
}
// Remove in the middle
node.prev.next = node.next;
node.next.prev = node.prev;
}
// move a node to the head (for a cache hit)
private void moveFirst(Node node){
remove(node);
add(node);
}
// remove the oldest item which is the tail
private void removeLast(){
remove(tail);
}
public void printContents(){
if(head == null){
System.out.println("LRUCache is empty");
return;
}
Node currNode = head;
String contents = "";
while(currNode != null){
contents += String.format("%s ", currNode.value);
currNode = currNode.next;
}
System.out.println(String.format("LRUCache contents : %s", contents));
}
// region Inner Classes
private class Node {
Node prev;
Node next;
int key;
int value;
private Node(int key, int value) {
this.key = key;
this.value = value;
}
}
// endregion
}boolean hasCycle(Node first) {
Node slow = first;
Node fast = first;
while(fast != null && fast.next != null) {
slow = slow.next; // 1 hop
fast = fast.next.next; // 2 hops
if(slow == fast) // fast caught up to slow, so there is a loop
return true;
}
return false; // fast reached null, so the list terminates
}void reverseStack(Stack stack) {
if (stack.isEmpty()) {
return;
} else {
Object obj = stack.pop();
reverseStack(stack);
insert(stack, obj);
}
}
void insert(Stack stack, Object obj){
if (stack.isEmpty()) {
stack.push(obj);
} else {
Object element = stack.pop();
insert(stack, obj);
stack.push(element);
}
}String a = "((0+4)+(1x3) )";
String b = "( { } ) { ] [ }";
String c = "{ ( [ (1*3) +2 ] ) / a+ [12 ] }";
String d = "{ ( a+b )";
System.out.println(String.format("Exp a is %b", isValidExpression(a)));
System.out.println(String.format("Exp b is %b", isValidExpression(b)));
System.out.println(String.format("Exp c is %b", isValidExpression(c)));
System.out.println(String.format("Exp d is %b", isValidExpression(d)));
public static boolean isValidExpression(String exp){
Stack<Character> bracesStack = new Stack<Character>();
for(int i=0; i<exp.length(); i++){
char c1 = exp.charAt(i);
if(isOpeningChar(c1)){
bracesStack.push(c1);
} else if(isClosingChar(c1)) {
char c2 = bracesStack.peek();
if(isMatchingBrace(c2, c1))
bracesStack.pop();
else
return false;
}
}
if(bracesStack.isEmpty())
return true;
return false;
}
private static boolean isOpeningChar(char c1){
if(c1 == '(' || c1 == '[' || c1 == '{')
return true;
else
return false;
}
private static boolean isClosingChar(char c1){
if(c1 == ')' || c1 == ']' || c1 == '}')
return true;
else
return false;
}
private static boolean isMatchingBrace(char c1, char c2){
if(c1 == '(' && c2 == ')'){
return true;
} else if(c1 == '{' && c2 == '}'){
return true;
} else if(c1 == '[' && c2 == ']'){
return true;
}
return false;
}