Friday, 22 March 2019

Binary Search Tree Points and Implementation need to complete before an Interview.

Binary Tree : A data structure in which we have nodes containing data and two references to other nodes, one on the left and one on the right.
Binary Tree consist of Nodes
  • Nodes are nothing but objects of a class and each node has data and a link to the left node and right node.
  • Usually we call the starting node of a tree as root.
class Node{
 int data;
 Node left;
 Node right; 
 public Node(int data){
  this.data = data;
  left = null;
  right = null;
 }
}
  •  Left and right node of a Leaf node points to NULL so you will know that you have reached to the end of the tree.
Binary Search Tree:
Often we call it as BST, is a type of Binary tree which has a special property.
Nodes smaller than root goes to the left of the root and Nodes greater than root goes to the right of the root.
Operations:
Insert(int n) : Add a node the tree with value n. Its O(lgn)
Find(int n) : Find a node the tree with value n. Its O(lgn)
Delete (int n) : Delete a node the tree with value n. Its O(lgn)
Display(): Prints the entire tree in increasing order. O(n).
Detail Explanations for the Operations:
Find(int n):
  • Its very simple operation to perform.
  • start from the root and compare root.data with n
  • if root.data is greater than n that means we need to go to the left of the root.
  • if root.data is smaller than n that means we need to go to the right of the root.
  • if any point of time root.data is equal to the n then we have found the node, return true.
  • if we reach to the leaves (end of the tree) return false, we didn’t find the element
Insert(int n):
  • Very much similar to find() operation.
  • To insert a node our first task is to find the place to insert the node.
  • Take current = root .
  • start from the current and compare root.data with n
  • if current.data is greater than n that means we need to go to the left of the root.
  • if current.data is smaller than n that means we need to go to the right of the root.
  • if any point of time current is null that means we have reached to the leaf node, insert your node here with the help of parent node. (See code)
Delete(int n):
Complicated than Find() and Insert() operations. Here we have to deal with 3 cases.
  • Node to be deleted is a leaf node ( No Children).
  • Node to be deleted has only one child.
  • Node to be deleted has two childrens.
Node to be deleted is a leaf node ( No Children).
its a very simple case, if a node to be deleted has no children then just traverse to that node, keep track of parent node and the side in which the node exist(left or right) and set parent.left = null or parent.right = null;

Node to be deleted has only one child.
  1. its a slightly complex case. if a node to be deleted(deleteNode) has only one child then just traverse to that node, keep track of parent node and the side in which the node exist(left or right).
  2. check which side child is null (since it has only one child).
  3. Say node to be deleted has child on its left side . Then take the entire sub tree from the left side and add it to the parent and the side on which deleteNode exist, see step 1 and example.
Node to be deleted has two children.
Now this is quite exciting 🙂
You just cannot replace the deleteNode with any of its child, Why? Lets try out a example.
What to do now?????
Dont worry we have solution for this 🙂
Find The Successor:
Successor is the node which will replace the deleted node. Now the question is to how to find it and where to find it.
Successor is the smaller node in the right sub tree of the node to be deleted.
Display() : To know about how we are displaying nodes in increasing order, Click Here
Complete Example :

Complete Example Code:
public class BinarySearchTree {
public static Node root;
public BinarySearchTree(){
this.root = null;
}
public boolean find(int id){
Node current = root;
while(current!=null){
if(current.data==id){
return true;
}else if(current.data>id){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
public boolean delete(int id){
Node parent = root;
Node current = root;
boolean isLeftChild = false;
while(current.data!=id){
parent = current;
if(current.data>id){
isLeftChild = true;
current = current.left;
}else{
isLeftChild = false;
current = current.right;
}
if(current ==null){
return false;
}
}
//if i am here that means we have found the node
//Case 1: if node to be deleted has no children
if(current.left==null && current.right==null){
if(current==root){
root = null;
}
if(isLeftChild ==true){
parent.left = null;
}else{
parent.right = null;
}
}
//Case 2 : if node to be deleted has only one child
else if(current.right==null){
if(current==root){
root = current.left;
}else if(isLeftChild){
parent.left = current.left;
}else{
parent.right = current.left;
}
}
else if(current.left==null){
if(current==root){
root = current.right;
}else if(isLeftChild){
parent.left = current.right;
}else{
parent.right = current.right;
}
}else if(current.left!=null && current.right!=null){
//now we have found the minimum element in the right sub tree
Node successor = getSuccessor(current);
if(current==root){
root = successor;
}else if(isLeftChild){
parent.left = successor;
}else{
parent.right = successor;
}
successor.left = current.left;
}
return true;
}
public Node getSuccessor(Node deleleNode){
Node successsor =null;
Node successsorParent =null;
Node current = deleleNode.right;
while(current!=null){
successsorParent = successsor;
successsor = current;
current = current.left;
}
//check if successor has the right child, it cannot have left child for sure
// if it does have the right child, add it to the left of successorParent.
// successsorParent
if(successsor!=deleleNode.right){
successsorParent.left = successsor.right;
successsor.right = deleleNode.right;
}
return successsor;
}
public void insert(int id){
Node newNode = new Node(id);
if(root==null){
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id<current.data){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
return;
}
}
}
}
public void display(Node root){
if(root!=null){
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static void main(String arg[]){
BinarySearchTree b = new BinarySearchTree();
b.insert(3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
System.out.println("Original Tree : ");
b.display(b.root);
System.out.println("");
System.out.println("Check whether Node with value 4 exists : " + b.find(4));
System.out.println("Delete Node with no children (2) : " + b.delete(2));
b.display(root);
System.out.println("\n Delete Node with one child (4) : " + b.delete(4));
b.display(root);
System.out.println("\n Delete Node with Two children (10) : " + b.delete(10));
b.display(root);
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
Output:
Original Tree :
1 2 3 4 6 8 9 10 15 16 20 25
Check whether Node with value 4 exists : true
Delete Node with no children (2) : true
1 3 4 6 8 9 10 15 16 20 25
Delete Node with one child (4) : true
1 3 6 8 9 10 15 16 20 25
Delete Node with Two children (10) : true
1 3 6 8 9 15 16 20 25

Implementation of Binary search tree using Java

BST.java


import java.util.NoSuchElementException;

/**
 *  The {@code BST} class represents an ordered symbol table of generic
 *  key-value pairs.
 *  It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,
 *  <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.
 *  It also provides ordered methods for finding the <em>minimum</em>,
 *  <em>maximum</em>, <em>floor</em>, <em>select</em>, <em>ceiling</em>.
 *  It also provides a <em>keys</em> method for iterating over all of the keys.
 *  A symbol table implements the <em>associative array</em> abstraction:
 *  when associating a value with a key that is already in the symbol table,
 *  the convention is to replace the old value with the new value.
 *  Unlike {@link java.util.Map}, this class uses the convention that
 *  values cannot be {@code null}—setting the
 *  value associated with a key to {@code null} is equivalent to deleting the key
 *  from the symbol table.
 *  <p>
 *  This implementation uses an (unbalanced) binary search tree. It requires that
 *  the key type implements the {@code Comparable} interface and calls the
 *  {@code compareTo()} and method to compare two keys. It does not call either
 *  {@code equals()} or {@code hashCode()}.
 *  The <em>put</em>, <em>contains</em>, <em>remove</em>, <em>minimum</em>,
 *  <em>maximum</em>, <em>ceiling</em>, <em>floor</em>, <em>select</em>, and
 *  <em>rank</em>  operations each take
 *  linear time in the worst case, if the tree becomes unbalanced.
 *  The <em>size</em>, and <em>is-empty</em> operations take constant time.
 *  Construction takes constant time.
 *  <p>
 *  For other implementations, see {@link ST}, {@link BinarySearchST},
 *  {@link SequentialSearchST}, {@link RedBlackBST},
 *  {@link SeparateChainingHashST}, and {@link LinearProbingHashST},
 *
 *  @author Nishant Sharma
 */

 public class BST<Key extends Comparable<Key>, Value> {
    private Node root;             // root of BST

    private class Node {
        private Key key;           // sorted by key
        private Value val;         // associated data
        private Node left, right;  // left and right subtrees
        private int size;          // number of nodes in subtree

        public Node(Key key, Value val, int size) {
            this.key = key;
            this.val = val;
            this.size = size;
        }
    }

    /**
     * Initializes an empty symbol table.
     */
    public BST() {
    }

    /**
     * Returns true if this symbol table is empty.
     * @return {@code true} if this symbol table is empty; {@code false} otherwise
     */
    public boolean isEmpty() {
        return size() == 0;
    }

    /**
     * Returns the number of key-value pairs in this symbol table.
     * @return the number of key-value pairs in this symbol table
     */
    public int size() {
        return size(root);
    }

    // return number of key-value pairs in BST rooted at x
    private int size(Node x) {
        if (x == null) return 0;
        else return x.size;
    }

    /**
     * Does this symbol table contain the given key?
     *
     * @param  key the key
     * @return {@code true} if this symbol table contains {@code key} and
     *         {@code false} otherwise
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public boolean contains(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to contains() is null");
        return get(key) != null;
    }

    /**
     * Returns the value associated with the given key.
     *
     * @param  key the key
     * @return the value associated with the given key if the key is in the symbol table
     *         and {@code null} if the key is not in the symbol table
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public Value get(Key key) {
        return get(root, key);
    }

    private Value get(Node x, Key key) {
        if (key == null) throw new IllegalArgumentException("calls get() with a null key");
        if (x == null) return null;
        int cmp = key.compareTo(x.key);
        if      (cmp < 0) return get(x.left, key);
        else if (cmp > 0) return get(x.right, key);
        else              return x.val;
    }

    /**
     * Inserts the specified key-value pair into the symbol table, overwriting the old 
     * value with the new value if the symbol table already contains the specified key.
     * Deletes the specified key (and its associated value) from this symbol table
     * if the specified value is {@code null}.
     *
     * @param  key the key
     * @param  val the value
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public void put(Key key, Value val) {
        if (key == null) throw new IllegalArgumentException("calls put() with a null key");
        if (val == null) {
            delete(key);
            return;
        }
        root = put(root, key, val);
        assert check();
    }

    private Node put(Node x, Key key, Value val) {
        if (x == null) return new Node(key, val, 1);
        int cmp = key.compareTo(x.key);
        if      (cmp < 0) x.left  = put(x.left,  key, val);
        else if (cmp > 0) x.right = put(x.right, key, val);
        else              x.val   = val;
        x.size = 1 + size(x.left) + size(x.right);
        return x;
    }


    /**
     * Removes the smallest key and associated value from the symbol table.
     *
     * @throws NoSuchElementException if the symbol table is empty
     */
    public void deleteMin() {
        if (isEmpty()) throw new NoSuchElementException("Symbol table underflow");
        root = deleteMin(root);
        assert check();
    }

    private Node deleteMin(Node x) {
        if (x.left == null) return x.right;
        x.left = deleteMin(x.left);
        x.size = size(x.left) + size(x.right) + 1;
        return x;
    }

    /**
     * Removes the largest key and associated value from the symbol table.
     *
     * @throws NoSuchElementException if the symbol table is empty
     */
    public void deleteMax() {
        if (isEmpty()) throw new NoSuchElementException("Symbol table underflow");
        root = deleteMax(root);
        assert check();
    }

    private Node deleteMax(Node x) {
        if (x.right == null) return x.left;
        x.right = deleteMax(x.right);
        x.size = size(x.left) + size(x.right) + 1;
        return x;
    }

    /**
     * Removes the specified key and its associated value from this symbol table     
     * (if the key is in this symbol table).    
     *
     * @param  key the key
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public void delete(Key key) {
        if (key == null) throw new IllegalArgumentException("calls delete() with a null key");
        root = delete(root, key);
        assert check();
    }

    private Node delete(Node x, Key key) {
        if (x == null) return null;

        int cmp = key.compareTo(x.key);
        if      (cmp < 0) x.left  = delete(x.left,  key);
        else if (cmp > 0) x.right = delete(x.right, key);
        else { 
            if (x.right == null) return x.left;
            if (x.left  == null) return x.right;
            Node t = x;
            x = min(t.right);
            x.right = deleteMin(t.right);
            x.left = t.left;
        } 
        x.size = size(x.left) + size(x.right) + 1;
        return x;
    } 


    /**
     * Returns the smallest key in the symbol table.
     *
     * @return the smallest key in the symbol table
     * @throws NoSuchElementException if the symbol table is empty
     */
    public Key min() {
        if (isEmpty()) throw new NoSuchElementException("calls min() with empty symbol table");
        return min(root).key;
    } 

    private Node min(Node x) { 
        if (x.left == null) return x; 
        else                return min(x.left); 
    } 

    /**
     * Returns the largest key in the symbol table.
     *
     * @return the largest key in the symbol table
     * @throws NoSuchElementException if the symbol table is empty
     */
    public Key max() {
        if (isEmpty()) throw new NoSuchElementException("calls max() with empty symbol table");
        return max(root).key;
    } 

    private Node max(Node x) {
        if (x.right == null) return x; 
        else                 return max(x.right); 
    } 

    /**
     * Returns the largest key in the symbol table less than or equal to {@code key}.
     *
     * @param  key the key
     * @return the largest key in the symbol table less than or equal to {@code key}
     * @throws NoSuchElementException if there is no such key
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public Key floor(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to floor() is null");
        if (isEmpty()) throw new NoSuchElementException("calls floor() with empty symbol table");
        Node x = floor(root, key);
        if (x == null) return null;
        else return x.key;
    } 

    private Node floor(Node x, Key key) {
        if (x == null) return null;
        int cmp = key.compareTo(x.key);
        if (cmp == 0) return x;
        if (cmp <  0) return floor(x.left, key);
        Node t = floor(x.right, key); 
        if (t != null) return t;
        else return x; 
    } 

    public Key floor2(Key key) {
        return floor2(root, key, null);
    }

    private Key floor2(Node x, Key key, Key best) {
        if (x == null) return best;
        int cmp = key.compareTo(x.key);
        if      (cmp  < 0) return floor2(x.left, key, best);
        else if (cmp  > 0) return floor2(x.right, key, x.key);
        else               return x.key;
    } 

    /**
     * Returns the smallest key in the symbol table greater than or equal to {@code key}.
     *
     * @param  key the key
     * @return the smallest key in the symbol table greater than or equal to {@code key}
     * @throws NoSuchElementException if there is no such key
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public Key ceiling(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
        if (isEmpty()) throw new NoSuchElementException("calls ceiling() with empty symbol table");
        Node x = ceiling(root, key);
        if (x == null) return null;
        else return x.key;
    }

    private Node ceiling(Node x, Key key) {
        if (x == null) return null;
        int cmp = key.compareTo(x.key);
        if (cmp == 0) return x;
        if (cmp < 0) { 
            Node t = ceiling(x.left, key); 
            if (t != null) return t;
            else return x; 
        } 
        return ceiling(x.right, key); 
    } 

    /**
     * Return the key in the symbol table whose rank is {@code k}.
     * This is the (k+1)st smallest key in the symbol table.
     *
     * @param  k the order statistic
     * @return the key in the symbol table of rank {@code k}
     * @throws IllegalArgumentException unless {@code k} is between 0 and
     *        <em>n</em>–1
     */
    public Key select(int k) {
        if (k < 0 || k >= size()) {
            throw new IllegalArgumentException("argument to select() is invalid: " + k);
        }
        Node x = select(root, k);
        return x.key;
    }

    // Return key of rank k. 
    private Node select(Node x, int k) {
        if (x == null) return null; 
        int t = size(x.left); 
        if      (t > k) return select(x.left,  k); 
        else if (t < k) return select(x.right, k-t-1); 
        else            return x; 
    } 

    /**
     * Return the number of keys in the symbol table strictly less than {@code key}.
     *
     * @param  key the key
     * @return the number of keys in the symbol table strictly less than {@code key}
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public int rank(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to rank() is null");
        return rank(key, root);
    } 

    // Number of keys in the subtree less than key.
    private int rank(Key key, Node x) {
        if (x == null) return 0; 
        int cmp = key.compareTo(x.key); 
        if      (cmp < 0) return rank(key, x.left); 
        else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); 
        else              return size(x.left); 
    } 

    /**
     * Returns all keys in the symbol table as an {@code Iterable}.
     * To iterate over all of the keys in the symbol table named {@code st},
     * use the foreach notation: {@code for (Key key : st.keys())}.
     *
     * @return all keys in the symbol table
     */
    public Iterable<Key> keys() {
        if (isEmpty()) return new Queue<Key>();
        return keys(min(), max());
    }

    /**
     * Returns all keys in the symbol table in the given range,
     * as an {@code Iterable}.
     *
     * @param  lo minimum endpoint
     * @param  hi maximum endpoint
     * @return all keys in the symbol table between {@code lo} 
     *         (inclusive) and {@code hi} (inclusive)
     * @throws IllegalArgumentException if either {@code lo} or {@code hi}
     *         is {@code null}
     */
    public Iterable<Key> keys(Key lo, Key hi) {
        if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
        if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");

        Queue<Key> queue = new Queue<Key>();
        keys(root, queue, lo, hi);
        return queue;
    } 

    private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { 
        if (x == null) return; 
        int cmplo = lo.compareTo(x.key); 
        int cmphi = hi.compareTo(x.key); 
        if (cmplo < 0) keys(x.left, queue, lo, hi); 
        if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); 
        if (cmphi > 0) keys(x.right, queue, lo, hi); 
    } 

    /**
     * Returns the number of keys in the symbol table in the given range.
     *
     * @param  lo minimum endpoint
     * @param  hi maximum endpoint
     * @return the number of keys in the symbol table between {@code lo} 
     *         (inclusive) and {@code hi} (inclusive)
     * @throws IllegalArgumentException if either {@code lo} or {@code hi}
     *         is {@code null}
     */
    public int size(Key lo, Key hi) {
        if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
        if (hi == null) throw new IllegalArgumentException("second argument to size() is null");

        if (lo.compareTo(hi) > 0) return 0;
        if (contains(hi)) return rank(hi) - rank(lo) + 1;
        else              return rank(hi) - rank(lo);
    }

    /**
     * Returns the height of the BST (for debugging).
     *
     * @return the height of the BST (a 1-node tree has height 0)
     */
    public int height() {
        return height(root);
    }
    private int height(Node x) {
        if (x == null) return -1;
        return 1 + Math.max(height(x.left), height(x.right));
    }

    /**
     * Returns the keys in the BST in level order (for debugging).
     *
     * @return the keys in the BST in level order traversal
     */
    public Iterable<Key> levelOrder() {
        Queue<Key> keys = new Queue<Key>();
        Queue<Node> queue = new Queue<Node>();
        queue.enqueue(root);
        while (!queue.isEmpty()) {
            Node x = queue.dequeue();
            if (x == null) continue;
            keys.enqueue(x.key);
            queue.enqueue(x.left);
            queue.enqueue(x.right);
        }
        return keys;
    }

  /*************************************************************************
    *  Check integrity of BST data structure.
    ***************************************************************************/
    private boolean check() {
        if (!isBST())            StdOut.println("Not in symmetric order");
        if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
        if (!isRankConsistent()) StdOut.println("Ranks not consistent");
        return isBST() && isSizeConsistent() && isRankConsistent();
    }

    // does this binary tree satisfy symmetric order?
    // Note: this test also ensures that data structure is a binary tree since order is strict
    private boolean isBST() {
        return isBST(root, null, null);
    }

    // is the tree rooted at x a BST with all keys strictly between min and max
    // (if min or max is null, treat as empty constraint)
    // Credit: Bob Dondero's elegant solution
    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);
    } 

    // are the size fields correct?
    private boolean isSizeConsistent() { return isSizeConsistent(root); }
    private boolean isSizeConsistent(Node x) {
        if (x == null) return true;
        if (x.size != size(x.left) + size(x.right) + 1) return false;
        return isSizeConsistent(x.left) && isSizeConsistent(x.right);
    } 

    // check that ranks are consistent
    private boolean isRankConsistent() {
        for (int i = 0; i < size(); i++)
            if (i != rank(select(i))) return false;
        for (Key key : keys())
            if (key.compareTo(select(rank(key))) != 0) return false;
        return true;
    }


    /**
     * Unit tests the {@code BST} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) { 
        BST<String, Integer> st = new BST<String, Integer>();
        for (int i = 0; !StdIn.isEmpty(); i++) {
            String key = StdIn.readString();
            if ((st.size() > 1) && (st.floor(key) != st.floor2(key)))
                throw new RuntimeException("floor() function inconsistent");
            st.put(key, i);
        }

        for (String s : st.levelOrder())
            StdOut.println(s + " " + st.get(s));

        StdOut.println();

        for (String s : st.keys())
            StdOut.println(s + " " + st.get(s));
    }
}

Thursday, 14 March 2019

LinkedList based Programs : Good to practice before an interview

Program 1: Find the middle element of a singly linked list in one pass?

public class LinkedList{

private Node head;

private static class Node {
private int value;
private Node next;

Node(int value) {
this.value = value;

}
}

public void addToTheLast(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}

// This function will find middle element in linkedlist
public Node findMiddleNode(Node head)
{
Node slowPointer, fastPointer;
slowPointer = fastPointer = head;

while(fastPointer !=null) {
fastPointer = fastPointer.next;
if(fastPointer != null && fastPointer.next != null) {
slowPointer = slowPointer.next;
fastPointer = fastPointer.next;
}
}

return slowPointer;

}

public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list
Node head=new Node(5);
list.addToTheLast(head);
list.addToTheLast(new Node(6));
list.addToTheLast(new Node(7));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));

list.printList();
// finding middle element
Node middle= list.findMiddleNode(head);
System.out.println("Middle node will be: "+ middle.value);

}
}

output :

5 6 7 1 2
Middle node is: 7


Program 2: Reverse a linked list in java ?

public class LinkedList{

private Node head;

private static class Node {
private int value;
private Node next;

Node(int value) {
this.value = value;

}
}

public void addToTheLast(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}

// Reverse linkedlist using this function
public static Node reverseLinkedList(Node currentNode)
{
// For first node, previousNode will be null
Node previousNode=null;
Node nextNode;
while(currentNode!=null)
{
nextNode=currentNode.next;
// reversing the link
currentNode.next=previousNode;
// moving currentNode and previousNode by 1 node
previousNode=currentNode;
currentNode=nextNode;
}
return previousNode;
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list
Node head=new Node(5);
list.addToTheLast(head);
list.addToTheLast(new Node(6));
list.addToTheLast(new Node(7));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));

list.printList(head);
//Reversing LinkedList
Node reverseHead=reverseLinkedList(head);
System.out.println("After reversing");
list.printList(reverseHead);

}

}


Output :

5 6 7 1 2
After reversing
2 1 7 6 5


Program 3: How to detect loop in a linked list in java ? or linked list contains loop in java ?

public class LinkedList{

private Node head;

private static class Node {
private int value;
private Node next;

Node(int value) {
this.value = value;

}
}

public void addToTheLast(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}

public boolean ifLoopExists() {
Node fastPtr = head;
Node slowPtr = head;
while (fastPtr != null && fastPtr.next != null) {
fastPtr = fastPtr.next.next;
slowPtr = slowPtr.next;
if (slowPtr == fastPtr)
return true;

}
return false;
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list

list.addToTheLast(new Node(5));
list.addToTheLast(new Node(6));
list.addToTheLast(new Node(7));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));


list.printList();

// Test if loop existed or not
System.out.println("Loop existed-->" + list.ifLoopExists());

}
}

output:

5 6 7 1 2
Loop existed-->false


Program 4: Find start node of loop in linked list in java ?

public class LinkedList{

private Node head;

private static class Node {
private int value;
private Node next;

Node(int value) {
this.value = value;

}
}

public void addToTheLast(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}

public Node  findStartNodeOfTheLoop() {
Node fastPtr = head;
Node slowPtr = head;
boolean loopExists=false;
while (fastPtr != null && fastPtr.next != null) {
fastPtr = fastPtr.next.next;
slowPtr = slowPtr.next;
if (slowPtr == fastPtr)
{
loopExists=true;
break;
}

}
if(loopExists)
{
slowPtr=head;

while(slowPtr!=fastPtr)
{
slowPtr=slowPtr.next;
fastPtr=fastPtr.next;
}


}
else
{
System.out.println("Loop does not exists");
slowPtr=null;
}
return slowPtr;
}


public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list
Node loopNode=new Node(7);
list.addToTheLast(new Node(5));
list.addToTheLast(new Node(6));
list.addToTheLast(loopNode);
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));

list.printList();
list.addToTheLast(loopNode); 

Node startNode=list.findStartNodeOfTheLoop();
if(startNode!=null)
System.out.println("start Node of loop is "+ startNode.value);
}
}

output:

5 6 7 1 2
start Node of loop is 7



Program 5:  Find nth element from end of linked list using java ?

public class LinkedList{

private Node head;

private static class Node {
private int value;
private Node next;

Node(int value) {
this.value = value;

}
}

public void addToTheLast(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}


public Node nthFromLastNode(Node head,int n)
{
Node firstPtr=head;
Node secondPtr=head;

for (int i = 0; i < n; i++) {
firstPtr=firstPtr.next;

}

while(firstPtr!=null)
{
firstPtr=firstPtr.next;
secondPtr=secondPtr.next;
}

return secondPtr;
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list
Node head=new Node(5);
list.addToTheLast(head);
list.addToTheLast(new Node(6));
list.addToTheLast(new Node(7));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));

list.printList();
// Finding 3rd node from end
Node nthNodeFromLast= list.nthFromLastNode(head,3);
System.out.println("3th node from end is : "+ nthNodeFromLast.value);

}
}

output:

5 6 7 1 2
3th node from end is : 7


Program 6: How to check if linked list is palindrome in java ?


public class LinkedListPalindromeCheck{

private Node head;

private static class Node {
private int value;
private Node next;

Node(int value) {
this.value = value;

}
}

public void addToTheLast(Node node) {

if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;

temp.next = node;
}
}


public void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}

// This function will find middle element in linkedlist
public static Node findMiddleNode(Node head)
{
// step 1
Node slowPointer, fastPointer;
slowPointer = fastPointer = head;

while(fastPointer !=null) {
fastPointer = fastPointer.next;
if(fastPointer != null && fastPointer.next != null) {
slowPointer = slowPointer.next;
fastPointer = fastPointer.next;
}
}

return slowPointer;
}

// Function to check if linked list is palindrome or not
public static boolean checkPalindrome (Node head)
{
// Find middle node using slow and fast pointer
Node middleNode=findMiddleNode(head);
// we got head of second part
Node secondHead=middleNode.next;
// It is end of first part of linked list
middleNode.next=null;
// get reversed linked list for second part
Node reverseSecondHead=reverseLinkedList(secondHead);

while(head!=null && reverseSecondHead!=null)
{
if(head.value==reverseSecondHead.value)
{
head=head.next;
reverseSecondHead=reverseSecondHead.next;
continue;
}
else
{
return false;
}
}

return true;


}

public static Node reverseLinkedList(Node currentNode)
{
// For first node, previousNode will be null
Node previousNode=null;
Node nextNode;
while(currentNode!=null)
{
nextNode=currentNode.next;
// reversing the link
currentNode.next=previousNode;
// moving currentNode and previousNode by 1 node
previousNode=currentNode;
currentNode=nextNode;
}
return previousNode;
}


public static void main(String[] args) {
LinkedListPalindromeCheck list = new LinkedListPalindromeCheck();
// Creating a linked list
Node head=new Node(1);
list.addToTheLast(head);
list.addToTheLast(new Node(2));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));
list.addToTheLast(new Node(1));

list.printList();

System.out.println("Linked list palidrome: "+checkPalindrome(head));
}
}


output :

1 2 1 2 1
Linked list palidrome: true


Program 7: Find the sum of two linked list using Stack


import java.util.Stack;

public class AddNumbersLinkedList
{
    private class ListNode
    {
        int value;
        ListNode next;

        ListNode(int value)
        {
            this.value = value;
        }
    }
   
    ListNode head;
    ListNode tail;
   
    // appends node at the end of the list
    private void appendNode(int value)
    {
        if (head == null)
        {
            head = new ListNode(value);
            tail = head;
            return;
        }
       
        ListNode n = new ListNode(value);
        tail.next = n;
        tail = n;
    }

    // creates and returns a new list with node values taken from the stack 's'
    private ListNode createLinkedList(Stack<Integer> s)
    {
        // if the head is pointing to some existing list, make it null
        // let the clients handle and store the reference to head
        if (head != null)
        {
            head = null;
        }
       
        while (!s.isEmpty())
        {
            appendNode(s.pop());
        }
        return head;
    }
   
    // creates and returns a new list with node values taken from number[] array
    public ListNode createLinkedList(int[] number)
    {
        // if the head is pointing to some existing list, make it null
        // let the clients handle and store the reference to head
        if (head != null)
        {
            head = null;
        }
       
        for (int i = 0; i < number.length; i++)
        {
            appendNode(number[i]);
        }
        return head;
    }
   
    public void printList(ListNode head)
    {
        ListNode temp = head;
       
        while (temp != null)
        {
            System.out.print(temp.value + "->");
            temp = temp.next;
        }
        System.out.print("null");
    }
   
   
    public ListNode addLists(ListNode node1, ListNode node2)
    {
        if (node1 == null)
        {
            return node2;
        }
        if (node2 == null)
        {
            return node1;
        }
       
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        Stack<Integer> s3 = new Stack<Integer>();
       
        // push list1 into the first stack
        ListNode temp = node1;
        while (temp != null)
        {
            s1.push(temp.value);
            temp = temp.next;
        }
       
        // push list2 into the second stack
        temp = node2;
        while (temp != null)
        {
            s2.push(temp.value);
            temp = temp.next;
        }

        int sum = 0, carry = 0, value1, value2;
       
        // keep adding the popped digits to the sum until one of the stacks becomes empty
        // sum itself is stored in a stack
        while ((!s1.empty()) && (!s2.empty()))
        {
            value1 = s1.pop();
            value2 = s2.pop();
           
            sum   = (value1 + value2 + carry) % 10;
            carry = (value1 + value2 + carry) / 10;
           
            s3.push(sum);
        }
       
        // if stack1 still has some digits left, add those digits to the sum
        while (!s1.isEmpty())
        {
            value1 = s1.pop();
           
            sum   = (value1 + carry) % 10;
            carry = (value1 + carry) / 10;
           
            s3.push(sum);
        }
       
        // if stack2 still has some digits left, add those digits to the sum
        while (!s2.isEmpty())
        {
            value2 = s2.pop();
           
            sum   = (value2 + carry) % 10;
            carry = (value2 + carry) / 10;
           
            s3.push(sum);
        }
       
        // after adding digits from both the stack, if the remaining carry is greater than 0
        // add that carry to the sum
        if (carry > 0)
        {
            s3.push(carry);
        }
       
        // finally, from the resultant stack, which stores the sum create a new linked list
        // return this newly created linked list
        return createLinkedList(s3);
    }
   
   
    public static void main(String[] args)
    {
        AddNumbersLinkedList solution = new AddNumbersLinkedList();

        int[] firstNumber  = {9,9,9,7,1}; // number: 99971
        int[] secondNumber = {9,9,8}; // number: 998
       
        // 9->9->9->7->1->null
        ListNode head1 = solution.createLinkedList(firstNumber);
       
        // 9->9->8->null
        ListNode head2 = solution.createLinkedList(secondNumber);
       
        ListNode result = solution.addLists(head1, head2);
       
        System.out.print("Resultant sum represented as a linked list is: \n");
        solution.printList(result);
    }
}


Program 8: Find the length of a singly linked list?


public class LinkedListMain {
 // Find length of linked list using recursion
public int lengthOfLinkedList()
{
  Node temp=head;
  int count = 0;
  while(temp!=null)
  {
   temp=temp.next;
   count++; 
  }
  return count;
} 
  public static void main(String args[])
  {
   SinglyLinkedList myLinkedlist = new SinglyLinkedList();
   myLinkedlist.insertFirst(5);
   myLinkedlist.insertFirst(6);
   myLinkedlist.insertFirst(7);
   myLinkedlist.insertFirst(1);
   myLinkedlist.insertLast(2);
   myLinkedlist.printLinkedList();
   // Linked list will be
   // 2 -> 1 ->  7 -> 6 -> 5
   System.out.println("Length of Linked List using iteration: "+myLinkedlist.lengthOfLinkedList());
   System.out.println("Length of Linked List Using recursion: "+myLinkedlist.lengthOfLinkedListRec(myLinkedlist.getHead()));
 }
}

output:

1
2
3
4
5
6
7
8
9
10

Printing LinkedList (head --> last)
{ 1 }
{ 7 }
{ 6 }
{ 5 }
{ 2 }

Length of Linked List using iteration: 5
Length of Linked List Using recursion: 5

class Node {
 public int data;
 public Node next;

 public void displayNodeData() {
  System.out.println("{ " + data + " } ");
 }
}

public class SinglyLinkedList {
 private Node head;

 public boolean isEmpty() {
  return (head == null);
 }

 // used to insert a node at the start of linked list
 public void insertFirst(int data) {
  Node newNode = new Node();
  newNode.data = data;
  newNode.next = head;
  head = newNode;
 }

// Find length of linked list using iterative method
public int lengthOfLinkedList()
{
   Node temp=head;
   int count = 0;
   while(temp!=null)
   {
  temp=temp.next;
  count++; 
   }
    return count;
}
// Find length of linked list using recursion
public int lengthOfLinkedListRec(Node head)
 {
   Node temp=head;
   if(temp==null)
   {
      return 0;
    }
   else
   {
      return 1+ lengthOfLinkedListRec(temp.next);
    }
}
 // used to delete node from start of linked list
 public Node deleteFirst() {
  Node temp = head;
  head = head.next;
  return temp;
 }

 // used to delete node from start of linked list
 public Node deleteFirst(Node node) {
  Node temp = head;
  head = head.next;
  return temp;
 }

 // Use to delete node after particular node
 public void deleteAfter(Node after) {
  Node temp = head;
  while (temp.next != null && temp.data != after.data) {
   temp = temp.next;
  }
  if (temp.next != null)
   temp.next = temp.next.next;
 }

 // used to insert a node at the start of linked list
 public void insertLast(int data) {
  Node current = head;
  while (current.next != null) {
   current = current.next; // we'll loop until current.next is null
  }
  Node newNode = new Node();
  newNode.data = data;
  current.next = newNode;
 }

 // For printing Linked List
 public void printLinkedList() {
  System.out.println("Printing LinkedList (head --> last) ");
  Node current = head;
  while (current != null) {
   current.displayNodeData();
   current = current.next;
  }
  System.out.println();
 }
}

Program 9: Remove duplicate nodes in an unsorted linked list?

import java.util.HashMap;
import java.util.Map;

public class RemoveDuplicateLinkedList {
public static void main(String[] args) {

Node head = new Node("1");
head.next = new Node("2");
head.next.next = new Node("2");
head.next.next.next = new Node("4");
head.next.next.next.next = new Node("5");
head.next.next.next.next.next = new Node("4");
head.next.next.next.next.next.next = new Node("3");
       
System.out.println("Original List : ");
        display(head);
       
        System.out.println("\nUpdated List: ");
        Node update = deDup(head);
        display(update);
}

private static Node deDup(Node head) {

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

Node prevNode = head;
Node currNode = head.next;
Node temp = null;

Map<String, Integer> map = new HashMap<>();

map.put(prevNode.data, 1);

while(currNode != null) {

if(map.containsKey(currNode.data)) {
temp = currNode;
prevNode.next = currNode.next;
currNode = currNode.next;
temp = null;
}else {
map.put(currNode.data, 1);
prevNode = currNode;
currNode = currNode.next;
}

}
return head;
}

private static void display(Node head){
        Node n=head;
        while(n!=null){
            System.out.print("->" + n.data);
            n=n.next;
        }
}

}

public class Node {

    Node next;
    String data;
   
    public Node(String data) {
super();
this.data = data;
     }
}

Array and Matrix based Programs : Good to Practice before an interview


Program 1: Find a missing number in given integer array of 1 to 100?

// Java program to find missing Number

class Nishant001
{
// Function to ind missing number
static int getMissingNo (int a[], int n)
{
int i, total;
total = (n+1)*(n+2)/2;
for ( i = 0; i< n; i++)
total -= a[i];
return total;
}

/* program to test above function */
public static void main(String args[])
{
int a[] = {1,2,4,5,6};
int miss = getMissingNo(a,5);
System.out.println(miss);
}
}

Output : 3

Time Complexity : O(n)


Program 2: Find the duplicate number on a given integer array?

class RepeatElement
{
void printRepeating(int arr[], int size)
{
int i, j;
System.out.println("Repeated Elements are :");
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size; j++)
{
if (arr[i] == arr[j])
System.out.print(arr[i] + " ");
}
}
}

public static void main(String[] args)
{
RepeatElement repeat = new RepeatElement();
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = arr.length;
repeat.printRepeating(arr, arr_size);
}
}

Output :

Repeating elements are 4 2
Time Complexity: O(n*n)
Auxiliary Space: O(1)


Program 3: Largest and smallest number in an unsorted integer array?

public class LargestSmallest
{
public static void main(String[] args)
{
int a[] = new int[] { 23, 34, 13, 64, 72, 90, 10, 15, 9, 27 };

int min = a[0]; //  assume first elements as smallest number
int max = a[0]; //  assume first elements as largest number

for (int i = 1; i < a.length; i++)  // iterate for loop from arrays 1st index (second element)
{
if (a[i] > max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}

System.out.println("Largest Number in a given array is : " + max);
System.out.println("Smallest Number in a given array is : " + min);
}
}


Program 4: Find all pairs of integer array whose sum is equal to a given number

public class PairsOfElementsInArray
{
    static void findThePairs(int inputArray[], int inputNumber)
    {
        System.out.println("Pairs of elements whose sum is "+inputNumber+" are : ");

        for (int i = 0; i < inputArray.length; i++)
        {
            for (int j = i+1; j < inputArray.length; j++)
            {
                if(inputArray[i]+inputArray[j] == inputNumber)
                {
                    System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
                }
            }
        }
    }

    public static void main(String[] args)
    {
        findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);

        findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);

        findThePairs(new int[] {12, 13, 40, 15, 8, 10, -15}, 25);

        findThePairs(new int[] {12, 23, 125, 41, -75, 38, 27, 11}, 50);
    }
}


Program 5: Sort an integer array in place using QuickSort algorithm?

public class QuickSortExample
{
    public static void main(String[] args)
    {
        // This is unsorted array
        Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };

        // Let's sort using quick sort
        quickSort( array, 0, array.length - 1 );

        // Verify sorted array
        System.out.println(Arrays.toString(array));
    }

    public static void quickSort(Integer[] arr, int low, int high)
    {
        //check for empty or null array
        if (arr == null || arr.length == 0){
            return;
        }
       
        if (low >= high){
            return;
        }

        //Get the pivot element from the middle of the list
        int middle = low + (high - low) / 2;
        int pivot = arr[middle];

        // make left < pivot and right > pivot
        int i = low, j = high;
        while (i <= j)
        {
            //Check until all values on left side array are lower than pivot
            while (arr[i] < pivot)
            {
                i++;
            }
            //Check until all values on left side array are greater than pivot
            while (arr[j] > pivot)
            {
                j--;
            }
            //Now compare values from both side of lists to see if they need swapping
            //After swapping move the iterator on both lists
            if (i <= j)
            {
                swap (arr, i, j);
                i++;
                j--;
            }
        }
        //Do same operation as above recursively to sort two sub arrays
        if (low < j){
            quickSort(arr, low, j);
        }
        if (high > i){
            quickSort(arr, i, high);
        }
    }
   
    public static void swap (Integer array[], int x, int y)
    {
        int temp = array[x];
        array[x] = array[y];
        array[y] = temp;
    }
}

Output: [3, 6, 10, 12, 13, 24, 70, 90]


Program 6: Perform a binary search in given array?

public class MyBinarySearch {

    public int binarySearch(int[] inputArr, int key) {
       
        int start = 0;
        int end = inputArr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (key == inputArr[mid]) {
                return mid;
            }
            if (key < inputArr[mid]) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }
 
    public static void main(String[] args) {
       
        MyBinarySearch mbs = new MyBinarySearch();
        int[] arr = {2, 4, 6, 8, 10, 12, 14, 16};
        System.out.println("Key 14's position: "+mbs.binarySearch(arr, 14));
        int[] arr1 = {6,34,78,123,432,900};
        System.out.println("Key 432's position: "+mbs.binarySearch(arr1, 432));
    }
}

Output:
Key 14's position: 6
Key 432's position: 4


Program 7: Multiply two Matrices in Java

import java.util.Scanner;

class MatrixMultiplication
{
   public static void main(String args[])
   {
      int m, n, p, q, sum = 0, c, d, k;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of rows and columns of first matrix");
      m = in.nextInt();
      n = in.nextInt();

      int first[][] = new int[m][n];

      System.out.println("Enter elements of first matrix");

      for (c = 0; c < m; c++)
         for (d = 0; d < n; d++)
            first[c][d] = in.nextInt();

      System.out.println("Enter the number of rows and columns of second matrix");
      p = in.nextInt();
      q = in.nextInt();

      if (n != p)
         System.out.println("The matrices can't be multiplied with each other.");
      else
      {
         int second[][] = new int[p][q];
         int multiply[][] = new int[m][q];

         System.out.println("Enter elements of second matrix");

         for (c = 0; c < p; c++)
            for (d = 0; d < q; d++)
               second[c][d] = in.nextInt();

         for (c = 0; c < m; c++)
         {
            for (d = 0; d < q; d++)
            { 
               for (k = 0; k < p; k++)
               {
                  sum = sum + first[c][k]*second[k][d];
               }

               multiply[c][d] = sum;
               sum = 0;
            }
         }

         System.out.println("Product of the matrices:");

         for (c = 0; c < m; c++)
         {
            for (d = 0; d < q; d++)
               System.out.print(multiply[c][d]+"\t");

            System.out.print("\n");
         }
      }
   }
}

String Based Programs : Good to practice before an interview

Program 1: Print duplicate characters from String Using Java ?

public class Nishant001 
{
/*
Typically, ASCII characters are 256, so we use our Hash array size as 256.
*/
    static final int NO_OF_CHARS = 256;
     
    /* Fills count array with frequency of characters */
    static void fillCharCounts(String str, int[] count)
    {
       for (int i = 0; i < str.length();  i++)
          count[str.charAt(i)]++;
    }
     
    /* Print duplicates present in the passed string */
    static void printDups(String str)
    {
      // Create an array of size 256 and fill count of every character in it
      int count[] = new int[NO_OF_CHARS];
      fillCharCounts(str, count);
     
      for (int i = 0; i < NO_OF_CHARS; i++)
        if(count[i] > 1)
            System.out.printf("%c,  count = %d \n", i,  count[i]);
     
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "test string";
        printDups(str);
    }
}

Output:

s,  count = 2
t,  count = 3

Time Complexity : O(n)


Program 2: Print maximum occurring character in an input string

// Java program to output the maximum occurring character
// in a string
/*
Typically, ASCII characters are 256, so we use our Hash array size as 256.
But if we know that our input string will have characters with value from 0 to 127 only,
we can limit Hash array size as 128. Similarly, based on extra info known about input string,
the Hash array size can be limited to 26.
*/
 
public class Nishant002
{
    static final int ASCII_SIZE = 256;
    static char getMaxOccuringChar(String str)
    {
        // Create array to keep the count of individual
        // characters and initialize the array as 0
        int count[] = new int[ASCII_SIZE];
     
        // Construct character count array from the input
        // string.
        int len = str.length();
        for (int i=0; i<len; i++)
            count[str.charAt(i)]++;
     
        int max = -1;  // Initialize max count
        char result = ' ';   // Initialize result
     
        // Traversing through the string and maintaining
        // the count of each character
        for (int i = 0; i < len; i++) {
            if (max < count[str.charAt(i)]) {
                max = count[str.charAt(i)];
                result = str.charAt(i);
            }
        }
     
        return result;
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "sample string";
        System.out.println("Max occurring character is " +
                            getMaxOccuringChar(str));
    }
}


output:

Max occurring character is s

Time Complexity: O(n)
Space Complexity: O(1) — Because we are using fixed space (Hash array) irrespective of input string size.


Program 3: Remove duplicates from a given string


import java.util.Arrays;
public class Nishant003
{
    /* Method to remove duplicates in a sorted array */
    static String removeDupsSorted(String str)
    {
        int res_ind = 1, ip_ind = 1;
         
        // Character array for removal of duplicate characters
        char arr[] = str.toCharArray();
         
        /* In place removal of duplicate characters*/
        while (ip_ind != arr.length)
        {
            if(arr[ip_ind] != arr[ip_ind-1])
            {
                arr[res_ind] = arr[ip_ind];
                res_ind++;
            }
            ip_ind++;
           
        }
     
        str = new String(arr);
        return str.substring(0,res_ind);
    }
     
    /* Method removes duplicate characters from the string
       This function work in-place and fills null characters
       in the extra space left */
    static String removeDups(String str)
    {
       // Sort the character array
       char temp[] = str.toCharArray();
       Arrays.sort(temp);
       str = new String(temp);
       
       // Remove duplicates from sorted
       return removeDupsSorted(str);
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "nishantsharma";
        System.out.println(removeDups(str));
    }
}

output:

nishatrm

Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort.

// Java prigram to remove duplicates
import java.util.*;
 
class RemoveDuplicates
{
    /* Function removes duplicate characters from the string
    This function work in-place */
    void removeDuplicates(String str)
    {
        LinkedHashSet<Character> lhs = new LinkedHashSet<>();
        for(int i=0;i<str.length();i++)
            lhs.add(str.charAt(i));
         
        // print string after deleting duplicate elements
        for(Character ch : lhs)
            System.out.print(ch);
    }
     
    /* Driver program to test removeDuplicates */
    public static void main(String args[])
    {
        String str = "nishantsharma";
        RemoveDuplicates r = new RemoveDuplicates();
        r.removeDuplicates(str);
    }
}

output:

nishatrm

Time Complexity: O(n)


Program 4: Program to check if input is an integer or a string


import java.io.*;
public class Nishant004{

// Returns true if s is
// a number else false
static boolean isNumber(String s)
{
for (int i = 0; i < s.length(); i++)
if (Character.isDigit(s.charAt(i))
== false)
return false;

return true;
}

// Driver code
static public void main (String[] args)
{
// Saving the input in a string
String str = "6790";

// Function returns 1 if all elements
// are in range '0 - 9'
if (isNumber(str))
System.out.println("Integer");

// Function returns 0 if the
// input is not an integer
else
System.out.println("String");

}
}


Program 5: Print all the duplicates in the input string

// Java program to count all duplicates from string using hashing

public class Nishant005
{
static final int NO_OF_CHARS = 256;

/* Fills count array with frequency of characters */
static void fillCharCounts(String str, int[] count)
{
for (int i = 0; i < str.length(); i++)
count[str.charAt(i)]++;
}

/* Print duplicates present in the passed string */
static void printDups(String str)
{
// Create an array of size 256 and fill count of every character in it
int count[] = new int[NO_OF_CHARS];
fillCharCounts(str, count);

for (int i = 0; i < NO_OF_CHARS; i++)
if(count[i] > 1)
System.out.printf("%c, count = %d \n", i, count[i]);

}

// Driver Method
public static void main(String[] args)
{
String str = "test string";
printDups(str);
}
}


Program 6: Write a program to print all permutations of a given string

public class Nishant006
{
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
Nishant006 permutation = new Nishant006();
permutation.permute(str, 0, n-1);
}

/**
* permutation function
* @param str string to calculate permutation for
* @param l starting index
* @param r end index
*/
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}

/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}

}

Output:

ABC
ACB
BAC
BCA
CBA
CAB


Program 007: Write a program to check whether two strings are anagram of each other.

/*
An anagram of a string is another string that contains same characters, only the order of characters can be different.
For example, “abcd” and “dabc” are anagram of each other.
*/

// JAVA program to check whether two strings
// are anagrams of each other
import java.io.*;
import java.util.Arrays;
import java.util.Collections;

class Nishant007 {

/* function to check whether two strings are
anagram of each other */
static boolean areAnagram(char[] str1, char[] str2)
{
// Get lenghts of both strings
int n1 = str1.length;
int n2 = str2.length;

// If length of both strings is not same,
// then they cannot be anagram
if (n1 != n2)
return false;

// Sort both strings
Arrays.sort(str1);
Arrays.sort(str2);

// Compare sorted strings
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;

return true;
}

/* Driver program to test to print printDups*/
public static void main(String args[])
{
char str1[] = { 't', 'e', 's', 't' };
char str2[] = { 't', 't', 'e', 'w' };
if (areAnagram(str1, str2))
System.out.println("The two strings are"
+ " anagram of each other");
else
System.out.println("The two strings are not"
+ " anagram of each other");
}
}

Output:  The two strings are not anagram of each other


JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...