Create Own HashMap



package linklist.hashmap;

class Entry<K, V> {

    private K key;
    private V value;
    private Entry<K, V> next;

    public Entry(K key, V value, Entry<K, V> next){
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public Entry getNext() {
        return next;
    }

    public void setNext(Entry<K, V> next) {
        this.next = next;
    }
}

class CustomHashMap<K, V> {
    private int capacity = 16; //Initial default capacity

    private Entry<K, V>[] table; //Array of Entry object

    public CustomHashMap(){
        table = new Entry[capacity];
    }

    public CustomHashMap(int capacity){
        this.capacity = capacity;
        table = new Entry[capacity];
    }

    public void put(K key, V value){
        int index = index(key);
        Entry newEntry = new Entry(key, value, null);
        if(table[index] == null){
            table[index] = newEntry;
        }else {
            Entry<K, V> previousNode = null;
            Entry<K, V> currentNode = table[index];
            while(currentNode != null){
                if(currentNode.getKey().equals(key)){
                    currentNode.setValue(value);
                    break;
                }
                previousNode = currentNode;
                currentNode = currentNode.getNext();
            }
            if(previousNode != null)
                previousNode.setNext(newEntry);
        }
    }

    public V get(K key){
        V value = null;
        int index = index(key);
        Entry<K, V> entry = table[index];
        while (entry != null){
            if(entry.getKey().equals(key)) {
                value = entry.getValue();
                break;
            }
            entry = entry.getNext();
        }
        return value;
    }

    public void remove(K key){
        int index = index(key);
        Entry previous = null;
        Entry entry = table[index];
        while (entry != null){
            if(entry.getKey().equals(key)){
                if(previous == null){
                    entry = entry.getNext();
                    table[index] = entry;
                    return;
                }else {
                    previous.setNext(entry.getNext());
                    return;
                }
            }
            previous = entry;
            entry = entry.getNext();
        }
    }

    public void display(){
        for(int i = 0; i < capacity; i++){
            if(table[i] != null){
                Entry<K, V> currentNode = table[i];
                while (currentNode != null){
                    System.out.println(String.format("Key is %s and value is %s", currentNode.getKey(), currentNode.getValue()));
                    currentNode = currentNode.getNext();
                }
            }
        }
    }

    private int index(K key){
        if(key == null){
            return 0;
        }
        return Math.abs(key.hashCode() % capacity);
    }
}

public class HashMapRunner {
    public static void main(String[] args) {
        CustomHashMap<Integer, String> map = new CustomHashMap<Integer, String>();
        System.out.println("Going to add entries in map");
        map.put(null, "Nothing");
        map.put(1, "ETC");
        map.put(2, "John");
        System.out.println("Displaying all the entry in map");
        map.display();
        System.out.println("Removing the entry with key 2");
        map.remove(2);
        map.display();
        System.out.println("Adding duplicate key 1 in map");
        map.put(1, "CSE");
        map.put(2, "John again");
        System.out.println("Displaying all the entry in map again");
        map.display();
        System.out.println("Adding entry with key 17 in map");
        map.put(17, "CS");
        map.display();
    }
}



Sub-Matrix With All 1s



public class SubMatrix {
    static void getMaxSubSquare(int M[][])
    {
        int i, j;
        int R = M.length; // no of rows in M[][]
        int C = M[0].length; // no of columns in M[][]
        int S[][] = new int[R][C];

        int maxS, maxI, maxJ;

        /* Set first column of S[][]*/
        for (i = 0; i < R; i++)
            S[i][0] = M[i][0];

        /* Set first row of S[][]*/
        for (j = 0; j < C; j++)
            S[0][j] = M[0][j];

        /* Construct other entries of S[][]*/
        for (i = 1; i < R; i++) {
            for (j = 1; j < C; j++) {
                if (M[i][j] == 1)
                    S[i][j] = Math.min(
                            S[i][j - 1],
                            Math.min(S[i - 1][j],
                                    S[i - 1][j - 1]))
                            + 1;
                else
                    S[i][j] = 0;
            }
        }

        /* Find the maximum entry, and indexes of maximum
           entry in S[][] */
        maxS = S[0][0];
        maxI = 0;
        maxJ = 0;
        for (i = 0; i < R; i++) {
            for (j = 0; j < C; j++) {
                if (maxS < S[i][j]) {
                    maxS = S[i][j];
                    maxI = i;
                    maxJ = j;
                }
            }
        }

        System.out.println("Maximum size sub-matrix is: ");
        for (i = maxI; i > maxI - maxS; i--) {
            for (j = maxJ; j > maxJ - maxS; j--) {
                System.out.print(M[i][j] + " ");
            }
            System.out.println();
        }
    }

    // Driver program
    public static void main(String[] args)
    {
        int M[][]
                = { { 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0 },
                { 0, 1, 1, 1, 0 }, { 1, 1, 1, 1, 0 },
                { 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0 } };

        getMaxSubSquare(M);
    }
        //Time Complexity: O(m*n)
    // where m is the number of rows and n is the number of columns in the given matrix.
    //Auxiliary Space: O(m*n)
    // where m is the number of rows and n is the number of columns in the given matrix.
}

Link-List-Palindrome




public class LinkListPalindrome {
    Node head; // head of list
    Node slp, ftp, secHalf;

    /* Linked list Node*/
    class Node {
        char data;
        Node next;

        Node(char d)
        {
            data = d;
            next = null;
        }
    }

    /* Function to check if given linked list is
       palindrome or not */
    boolean isPalindrome(Node head)
    {
        slp = head;
        ftp = head;
        Node prev_of_slow_ptr = head;
        Node midnode = null; // To handle odd size list
        boolean res = true; // initialize result

        if (head != null && head.next != null) {
            /* Get the middle of the list. Move slow_ptr by
               1 and fast_ptr by 2, slow_ptr will have the
               middle node */
            while (ftp != null
                    && ftp.next != null) {
                ftp = ftp.next.next;

                /*We need previous of the slow_ptr for
                  linked lists  with odd elements */
                prev_of_slow_ptr = slp;
                slp = slp.next;
            }

            /* fast_ptr would become NULL when there are
               even elements in the list and not NULL for
               odd elements. We need to skip the middle node
               for odd case and store it somewhere so that
               we can restore the original list */
            if (ftp != null) {
                midnode = slp;
                slp = slp.next;
            }

            // Now reverse the second half and compare it
            // with first half
            secHalf = slp;
            prev_of_slow_ptr.next
                    = null; // NULL terminate first half
            reverse(); // Reverse the second half
            res = compareLists(head,
                    secHalf); // compare

            /* Construct the original list back */
            reverse(); // Reverse the second half again

            if (midnode != null) {
                // If there was a mid node (odd size case)
                // which was not part of either first half
                // or second half.
                prev_of_slow_ptr.next = midnode;
                midnode.next = secHalf;
            }
            else
                prev_of_slow_ptr.next = secHalf;
        }
        return res;
    }

    /* Function to reverse the linked list  Note that this
       function may change the head */
    void reverse()
    {
        Node prev = null;
        Node current = secHalf;
        Node next;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        secHalf = prev;
    }

    /* Function to check if two input lists have same data*/
    boolean compareLists(Node head1, Node head2)
    {
        Node temp1 = head1;
        Node temp2 = head2;

        while (temp1 != null && temp2 != null) {
            if (temp1.data == temp2.data) {
                temp1 = temp1.next;
                temp2 = temp2.next;
            }
            else
                return false;
        }

        /* Both are empty return 1*/
        if (temp1 == null && temp2 == null)
            return true;

        /* Will reach here when one is NULL
           and other is not */
        return false;
    }

    /* Push a node to linked list. Note that this function
       changes the head */
    public void push(char new_data)
    {
        /* Allocate the Node &
           Put in the data */
        Node new_node = new Node(new_data);

        /* link the old list of the new one */
        new_node.next = head;

        /* Move the head to point to new Node */
        head = new_node;
    }

    // A utility function to print a given linked list
    void printList(Node ptr)
    {
        while (ptr != null) {
            System.out.print(ptr.data + "->");
            ptr = ptr.next;
        }
        System.out.println("NULL");
    }

    /* Driver program to test the above functions */
    public static void main(String[] args)
    {

        /* Start with the empty list */
        LinkListPalindrome llist = new LinkListPalindrome();

        char str[] = { 'a', 'b', 'a', 'c', 'a', 'b', 'a' };
        String string = new String(str);
        for (int i = 0; i < 7; i++) {
            llist.push(str[i]);
        }
        if (llist.isPalindrome(llist.head) != false) {
            System.out.println("Is Palindrome");
            System.out.println("");
        }
        else {
            System.out.println("Not Palindrome");
            System.out.println("");
        }
    }
}

Tree-Traverse-Order-Level-Frame





import java.util.*;

// structure of the node of the binary tree
class Node{
    int data;
    Node left;
    Node right;
    public Node(int data)
    {
        this.data=data;
    }
}
public class TraversTreeAndFrame {

    static ArrayList<Object[]> traversal;

    // function to traverse the binary
    // tree in the level order fashion
    public static void levelOrderTraversal(Node root)
    {
        // current node is marked as the root node
        Node curr=root;
        int level=0;
        // loop to traverse the binary tree until the current node
        // is not null
        while(curr!=null)
        {
            // if left child is null, print the
            // current node data and update the
            // current pointer to right child.
            if(curr.left==null)
            {
                // return the current node with
                // its level
                traversal.add(new Object[]{curr,new Integer(level)});
                curr=curr.right;
                if(curr!=null)
                {
                    level++;
                }else
                    level--;
            }
            else{
                // find the inorder predecessor
                Node prev=curr.left;
                int toUp=0;

                // loop to find the right most
                // node of the left child of the current node
                while(prev.right!=null && prev.right!=curr)
                {
                    prev=prev.right;
                    toUp++;
                }
                // If the right child of inorder
                // predecessor already points to
                // the current node, update the
                // current with it's right child
                if(prev.right==curr)
                {
                    prev.right=null;
                    curr=curr.right;
                    level-=toUp+1;
                }
                // else If right child doesn't
                // point to the current node,
                // then print this node's data
                // and update the right child
                // pointer with the current node
                // and update the current with
                // it's left child
                else{
                    traversal.add(new Object[]{curr,new Integer(level)});
                    prev.right=curr;
                    curr=curr.left;
                    level++;
                }
            }
        }
    }
    public static void main(String[] args)
    {
        // create a binary tree
        Node root=new Node(5);
        root.left=new Node(2);
        root.right=new Node(3);
        root.left.right=new Node(6);
        root.right.left=new Node(7);
        root.right.right=new Node(8);
        traversal=new ArrayList<>();

        // traverse the tree in level order traversal
        levelOrderTraversal(root);

        // find the height of the tree
        int h=0;
        for(Object[] i:traversal)
        {
            h=Math.max(h,(int)i[1]+1);
        }

        // print the date of nodes at each level
        for(int i = 0; i<h; i++){
            for(Object[] j : traversal){
                if((int)j[1] == i){

                    System.out.print(((Node)j[0]).data+" ");
                }
            }
            System.out.println();
        }
    }
  //Time Complexity: As in the above approach, every node is
    // touched at max twice due to which the time complexity is O(N),
    // where N is the number of nodes.
    //Auxiliary Space: As in the above approach,
    // there is no extra space used due to which auxiliary space used will be O(1) 
  
    
}


Tree-Traverse-Order-Level-Queue



import java.util.LinkedList;
import java.util.Queue;


class Node {
    int data;
    Node left, right;

    public Node(int item)
    {
        data = item;
        left = null;
        right = null;
    }
}
class LevelOrderQueue {

    Node root;

    void printLevelOrder()
    {
       Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while (!queue.isEmpty()) {

            Node tempNode = queue.poll();
            System.out.print(tempNode.data + " ");
            if (tempNode.left != null) {
                queue.add(tempNode.left);
            }
            if (tempNode.right != null) {
                queue.add(tempNode.right);
            }
        }
    }

    public static void main(String args[])
    {
        LevelOrderQueue tree_level = new LevelOrderQueue();
        tree_level.root = new Node(1);
        tree_level.root.left = new Node(2);
        tree_level.root.right = new Node(3);
        tree_level.root.left.left = new Node(4);
        tree_level.root.left.right = new Node(5);

        tree_level.printLevelOrder();
    }

//Firstly we insert the root into the queue and iterate over
//the queue until the queue is empty.
//In every iteration, we will pop from the top of
// the queue and print the value at the top of the queue.
//Then, add its left and right nodes to the end of the queue
// Time Complexity: O(N) where n is the number of nodes in the binary tree.
//Space Complexity: O(N) where n is the number of nodes in the binary tree.
}

Tree-Traverse-Order-Level-Recursive



package treesample.levelorder.recursive;


class Node {
    int data;
    Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

class LevelOrderRecursive {
    Node root;

    public LevelOrderRecursive() { root = null; }

    void LevelOrder()
    {
        int h = height(root);
        int i;
        for (i=1; i<=h; i++)
            CurrentLevel(root, i);
    }
    int height(Node root) {
        if (root == null)
            return 0;
        else {
            int lheight = height(root.left);
            int rheight = height(root.right);
            if (lheight > rheight)
                return(lheight+1);
            else return(rheight+1);
        }
    }
    void CurrentLevel (Node root ,int level) {
        if (root == null){
            return;
        }
        if (level == 1){
            System.out.print(root.data + " ");
        }
        else if (level > 1) {
            CurrentLevel(root.left, level-1);
            CurrentLevel(root.right, level-1);
        }
    }
    public static void main(String args[])
    {
        LevelOrderRecursive tree = new LevelOrderRecursive();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        tree.LevelOrder();

    }
//There are basically two functions in this approach. 
// One of them is used to print all nodes at a particular level (CurrentLevel),
// and another is used to print level order traversal of the tree (Levelorder).
//
//In the CurrentLevel function, we find the height of the tree and call the LevelOrder 
// function for every level between 1 to height.
//In the LevelOrder function we pass two parameters level and root. we follow the below steps:
//First check if root is null then return.
//Check if level is equal to 1 then print the current root value.
//Now, call recursively call both the children of the current root with 
// decrementing the value of level by 1.
//Time complexity: For a skewed tree, time complexity will be O(n^2).
//Space complexity: For a skewed tree space complexity will be O(n) and for a
}

Tree Traverse In Order Recursive Approach And Display





class Node {
    int key;
    Node left, right;

    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}
public class TreeTraversalInOrderAndDisplay {
    // Root of Binary Tree
    Node root;

    TreeTraversalInOrderAndDisplay() { root = null; }

    /* Given a binary tree, print its nodes in inorder*/
    void printInorder(Node node)
    {
        if (node == null)
            return;

        /* first recur on left child */
        printInorder(node.left);

        /* then print the data of node */
        System.out.print(node.key + " ");

        /* now recur on right child */
        printInorder(node.right);
    }

    // Wrappers over above recursive functions
    void printInorder() { printInorder(root); }

    // Driver code
    public static void main(String[] args)
    {
        TreeTraversalInOrderAndDisplay tree = new TreeTraversalInOrderAndDisplay();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        // Function call
        System.out.println(
                "\nTraversal of binary tree is ");
        tree.printInorder();

        //Time Complexity: O(N)
        //Auxiliary Space: If we don’t consider the size of the stack for function
        // calls then O(1) otherwise O(h) where h is the height of the tree.
    }
}



SubArray Max Sum



public class SubArrayMaxSum {

    public static void main(String[] args) {

        int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 };
        System.out.println("Maximum contiguous sum is "
                + sum(a));
    }

    public static int sum(int arr[]){

       int sum1=Integer.MIN_VALUE,sum2=0,size=arr.length;

       for(int i=0;i<size;i++){
           sum2=sum2+arr[i];
           if(sum1<sum2){
               sum1=sum2;
           }
           if(sum2<0){
               sum2=0;
           }
       }
       return sum1;
    }
}

Detect And Remove Loop from LinkList


import java.util.HashSet;

class LinkList3{

    Node head;

    Node sl;
    Node ft;
    class Node{
        int data;
        Node next;
        public Node(int data,boolean flag, Node node){
            this.data=data;
            this.next=null;
        }

        @Override
        public String toString() {
            return "{"+this.data+"}";
        }
    }

    public Node push(int data,boolean flag, Node node){
        Node link=new Node(data,flag,node);
        if(head==null){
            head=link;
        }else{
            Node current=head;
            while(current.next!=null){
                current=current.next;
            }

            if(flag && node!=null){
                link.next=node;
            }
            current.next=link;
        }


        return link;
    }
    public void display(){
        Node current=head;
        while(current!=null){
            System.out.print(current);
            current=current.next;
        }

    }
    public boolean detectLoop1(){

        HashSet set=new HashSet();
        Node current=head;
        boolean flag=false;
        while(current.next!=null){
            if(set.contains(current)){
                flag=true;
               break;
            }
            set.add(current);
            current=current.next;
        }
        return flag;
    }

    public boolean detectLoop2(){
        sl=head;
        ft=head.next;

       while(sl!=ft){
            if(ft==null || ft.next==null){
                return false;
            }
            sl=sl.next;
            ft=ft.next.next;
       }
        return true;
    }

    public boolean removeLoop1(){

        HashSet set=new HashSet();
        Node previous=head;
        Node current=head;
        while(current!=null){
            if(set.contains(current)){
                previous.next=null;
                return true;
            }
            set.add(current);
            previous=current;
            current=current.next;
        }

        return false;

    }
    public void removeLoop2(){
       ft=head;
        while(ft!=null){
            Node ptr=sl;
            while(ptr.next!=sl && ptr.next!=ft){
                ptr=ptr.next;
            }
            if(ptr.next==ft){
                ptr.next=null;
                return;
            }
            ft=ft.next;
        }

    }
}

public class DetectLoop2 {
    public static void main(String[] args) {
        LinkList3 linkList3=new LinkList3();
        linkList3.push(10,false,null);
        LinkList3.Node push = linkList3.push(20, false, null);
        linkList3.push(30,false,null);
        linkList3.push(40,false,null);
        linkList3.push(50,true,push);
        boolean flag=false;
        //linkList3.display();
       // flag= linkList3.detectLoop1();
        flag= linkList3.detectLoop2();
        if(flag){
            System.out.println("loop found");
        }else{
            System.out.println("loop not found");
        }
        //linkList3.removeLoop1();
        linkList3.removeLoop2();
        linkList3.display();
    }
}


Binary Array Minimum Adjacent Swaps Required To Sort Binary Array




public class BinaryArrayMinimumSwap {
    public static int minswaps(int arr[], int n)
    {
        int count = 0;
        int numUnplacedZeros = 0;

        for (int index = n - 1; index >= 0; index--)
        {
            if (arr[index] == 0)
                numUnplacedZeros += 1;
            else
                count += numUnplacedZeros;
        }
        return count;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 0, 0, 1, 0, 1, 0, 1, 1 };
        System.out.println(minswaps(arr, 8));

        //Space Optimized Solution: An auxiliary space is not needed.
        // We just need to start reading the list from the back and keep track of number
        // of zeros we encounter.
        // If we encounter a 1 the number of zeros is the number of swaps needed
        // to put the 1 in correct place.
        //Time Complexity: O(n)
        //Auxiliary Space: O(1)
    }
}


Segregate0and1




public class Segregate0and1 {
    static void segregate0and1(int arr[])
    {
        int type0 = 0;
        int type1 = arr.length - 1;

        while (type0 < type1) {
            if (arr[type0] == 1) {
                if (arr[type1] != 1) {
                    // swap
                    arr[type1] = arr[type1] + arr[type0];
                    arr[type0] = arr[type1] - arr[type0];
                    arr[type1] = arr[type1] - arr[type0];
                }
                type1--;
            }
            else {
                type0++;
            }
        }
    }

  
    public static void main(String[] args)
    {

        int[] array = { 0, 1, 0, 1, 1, 1 };

        segregate0and1(array);

        for (int a : array) {
            System.out.print(a + " ");
        }
        //Time complexity: O(n)
        //Auxiliary Space: O(1)
    }
}

First Non Repeating Character


public class FirstNonRepeating {
    static final int NO_OF_CHARS = 256;
    static char count[] = new char[NO_OF_CHARS];
    
    static void getCharCountArray(String str)
    {
        for (int i = 0; i < str.length(); i++)
            count[str.charAt(i)]++;
    }
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int index = -1, i;

        for (i = 0; i < str.length(); i++) {
            if (count[str.charAt(i)] == 1) {
                index = i;
                break;
            }
        }

        return index;
    }

    public static void main(String[] args) {
        String str = "algorithm";
        int index = firstNonRepeating(str);

        if(index == -1){
            System.out.println("First non-repeating character does not exists");
        }else {
            System.out.println("First non-repeating character is " + str.charAt(index));
        }
    }
}

Smallest Sub String



import java.util.*;
public class SmallSubString {
    static final int MAX_CHARS_COUNT = 256;

    static int maxDistChar(String str, int n)
    {
        int count[] = new int[MAX_CHARS_COUNT];
        int max_distinct = 0;
        for (int i = 0; i < n; i++) {
            count[str.charAt(i)]++;
            if (count[str.charAt(i)] == 1)
                max_distinct++;
        }
        return max_distinct;
    }

    static int smallestSubString(String str)
    {
        int n = str.length();
        int unique = maxDistChar(str, n);
        int res = Integer.MAX_VALUE;
        Map<Character, Integer> mp = new HashMap<Character, Integer>();
                 

        int j = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (mp.containsKey(c))
                mp.put(c, mp.get(c) + 1);
            else
                mp.put(c, 1);
            while (mp.size() == unique
                    && mp.get(str.charAt(j)) > 1) {
                mp.put(str.charAt(j),
                        (mp.get(str.charAt(j)) - 1));
                j++;
            }
            if (mp.size() == unique)
                res = Math.min(i - j + 1, res);
        }
        return res;
    }

    static public void main(String[] args)
    {
        String str = "AABBBCBB";

        int len = smallestSubString(str);
        System.out.println(
                " The length of the smallest substring characters "+ len);
    }
}

LinkList Rotate ClockWise



class ReverseLink1{
    Node head;
    class Node{
        int data;
        Node next;

        public Node(int data){
            this.data=data;
            this.next=null;
        }

        @Override
        public String toString() {
            return "{"+this.data +"}";
        }
    }

    public void push(int data){
        Node node=new Node(data);
        if(head==null){
            head=node;
        }else{
            Node current=head;
            while(current.next!=null){
                current=current.next;
            }
            current.next=node;
        }
    }
    public void display(Node head){
        if(head == null){
            System.out.println("No data");
        }else{
            Node current=head;
            while(current!=null){
                System.out.print(current);
                current=current.next;
            }
            System.out.println("");
        }
    }

    public Node revers(Node head, int k){
        if(head == null||head.next == null||k == 0) return head;
        //calculating length
        Node temp = head;
        int length = 1;
        while(temp.next != null) {
            ++length;
            temp = temp.next;
        }
        System.out.println("Length " +length);
        //link last node to first node
        temp.next = head;
        k = k%length; //when k is more than length of list
        int end = length-k; //to get end of the list
        while(end--!=0) temp = temp.next;
        //breaking last node link and pointing to NULL
        head = temp.next;
        temp.next = null;

        return head;
    }
}

public class ReverseLinkList1 {

    public static void main(String[] args) {
        ReverseLink1 reverseLink1=new ReverseLink1();
        reverseLink1.push(1);
        reverseLink1.push(2);
        reverseLink1.push(3);
        reverseLink1.push(4);
        reverseLink1.push(5);
        reverseLink1.push(6);
        reverseLink1.push(7);
        reverseLink1.display( reverseLink1.head);
        ReverseLink1.Node revers = reverseLink1.revers(reverseLink1.head, 3);
        reverseLink1.display(revers);

    }
}

 

LinkList Rotate AntiClockWise



class LinkListRotateAntiClock {
    Node head;
    class Node{
        int data;
        Node next;
        Node(int data){
            this.data=data;
            this.next=null;
        }

        @Override
        public String toString() {
            return "{"+this.data+"}";
        }
    }

    public void push(int data){
        Node node=new Node(data);
        if(head==null){
            head=node;
        }else{
            Node current=head;
            while(current.next!=null){
                current=current.next;
            }
            current.next=node;
        }
    }
    public Node rotateAntiClockWise(int k, Node node){
        if(node ==null || k<0){
             return node;
        }
        int sizeOfLinkList=getSizeOfList(node);
        k=k%sizeOfLinkList;
        if(k==0){
            return node;
        }
        Node tmp=node;
        int i=1;
        while(i < k){
            tmp=tmp.next;
          i++;
        }
        Node temp=tmp.next;
        Node head=temp;
        tmp.next=null;

        while(temp.next!=null){
            temp=temp.next;
        }
        temp.next=node;
        return head;

    }

    public int getSizeOfList(Node node){
            if(node ==null){
                return 0;
            }
            return getSizeOfList(node.next)+1;
    }

    public void display(Node head){

        if(head==null){
           return;
        }else{
            Node current=head;
            while(current!=null){
                System.out.print(current);
                current=current.next;
            }
            System.out.println("********");

        }
    }
}
 public class LinkListAntiClockwise {
     public static void main(String[] args) {
        LinkListRotateAntiClock linkListRotateAntiClock =new LinkListRotateAntiClock();
        linkListRotateAntiClock.push(1);
        linkListRotateAntiClock.push(2);
        linkListRotateAntiClock.push(3);
        linkListRotateAntiClock.push(4);
        linkListRotateAntiClock.push(5);
        linkListRotateAntiClock.push(5);


      linkListRotateAntiClock.display(linkListRotateAntiClock.head);
      LinkListRotateAntiClock.Node node = linkListRotateAntiClock.rotateAntiClockWise(2, linkListRotateAntiClock.head);
      linkListRotateAntiClock.display(node);
    }
}

 

Core-Java-Interview-Question

1) What is Java? 

2) List the features of Java Programming language. 

3) What do you understand by Java virtual machine? 

4) What is the difference between JDK, JRE, and JVM? 

5) How many types of memory areas are allocated by JVM? 

6) What is JIT compiler? 

7) What is classloader? 

8) What if I write static public void instead of public static void? 

10) What are the various access specifiers in Java? 

11) What are the advantages of Packages in Java? 

12) What is object-oriented paradigm? 

13) What is an object? 

14) What are the differences between the constructors and methods? 

15) What is the static method? 

16) Difference between static and final 

17) Can we override the static methods?

18) What is the static block?

19) Can we execute a program without main() method?

20) Can we declare the static variables and methods in an abstract class?

21) What is this keyword in java?

22) What are the main uses of this keyword? 

23) Can we assign the reference to this variable?

24) Can this keyword be used to refer static members?

25) How can constructor chaining be done using this keyword?

26) What are the advantages of passing this into a method instead of the current class object itself?

27) Which class is the superclass for all the classes?

28) Why is multiple inheritance not supported in java?

29) What is aggregation? 30) What is composition?

31) What is super in java?

32) How can constructor chaining be done by using the super keyword?

33) What are the main uses of the super keyword?

34) What are the differences between this and super keyword?

35) Can you use this() and super() both in a constructor?

36) What is object cloning?

37) What is method overloading?

38) Why is method overloading not possible by changing the return type in java?

39) Can we overload the methods by making them static?

40) Difference between method Overloading and Overriding ?

Wait, Notify and NotifyAll

The multiple thread communication happening via each other by wait(), notify() and notifyAll() method in java. 

The object contain many in-build method, wait(), notify() and notifyAll() is one of them. So today we will discuss about these thee method. 



wait, notify and notifyAll in Java


wait(), notify() and notifyAll() should be call from synchronized context and should acquire lock on object monitor else it throws java.lang.IllegalMonitorStateException exception.


Lets see in details.



wait 


Syntax :

public final void wait() throws InterruptedException



When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other threads


notify


Syntax :

public final void notify();

When notify() method is called, It's wake up only one thread that's waiting for an Object and that thread will start the further execution. When multiple thread is waiting to wakeup and notify method is called only one thread will wake-up and other thread will still wait for more(until next notify get called). this method does not return any value.


notifyAll


Syntax :

public final void notify();

 An Alternative to notify() is notifyAll(). As the name implies this method wakes up all threads that are waiting for on the given object but awakened thread will not be able to proceed further until current thread not release the lock on same object


Sleep() V/S Wait() Method in Java

Threading In Java

String Immutable

Exception Handling

OOPS Concept


In this page, we will learn about the basics of OOPs. As the name suggests, Object-Oriented Programming Or OOPs refer to programming languages that use objects in development. Object is key source to implements what is to happen in application development. 


Object means a real-word entity i.e car, table, employee, pen etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:


  • Object
  • Class
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism



Object:


It is a basic unit of Object-Oriented Programming.Any entity that has state and behaviour is known as an object. So Object has:

State: A state is represented by its attributes and properties.

Behaviour: A behaviour  is represented by the methods of an object. 

Identity: It’s gives a unique name to an object and enables  one object to interact with another object.


Example of an object: Car

  • Identity: Name of the car
  • State: Color, Brand , variant 
  • Behaviour:  Drive, Horn, Break, AC

Class: 


Class is not real-work entity, its logical entity. Collection of objects is called class. A class can also be defined as blueprint from which you can create an individual object. Class contains data member, method, constructor, nestled class and interface. 


Syntax to declare a class:

access_modifier class_name
	{  
  		data member;  
  	 	method;  
  	  	constructor;
    		nested class;
   		interface;
	}

A class is blueprint of or prototype from which object are created. It represent the set of properties or method that are common to all object of one type. 

  1. Modifiers: A class can be public or has default access
  2. Class keyword: class keyword is used to create a class.
  3. Class name: The name should begin with an initial letter
  4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  6. Body: The class body is surrounded by braces, { }.

 

Abstractions  :


Abstraction is a process of hiding unnecessary data and showing only relevant data. Out of an ocean of data, we are only maintaining the transparency of some data to the user. This important concept in object-oriented programming will reduce the complexity of the code and increases the readability.


Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects



Encapsulation: 


Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation hiding).


Encapsulation is binding the data members with member variables. This will avoid the direct access of variables, because direct access of variables may violate privacy, and hiding of the implementation will not be possible. While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing the interface to the user and hiding the details of implementation


In summary encapsulation is a procedure that takes place at the implementation level, while abstraction is a design-level process



Inheritance:


Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs. In Java, inheritance means creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class. In addition, you can add new fields and methods to your current class as well.  

Importance of Java inheritance


  • Code Reusability: Inheritance minimizes the complexity of a code by minimizing duplicate code. If the same code has to be used by another class, it can simply be inherited from that class to its sub-class. Hence, the code is better organized
  • Polymorphism: Method Overriding is achievable only through Inheritance. It is one of the ways by which java achieves Run Time Polymorphism.
  • Abstraction: The concept of abstract where we do not have to provide all details is achieved through inheritance. Abstraction only shows the functionality to the user.

Polymorphism:


Polymorphism is the ability of an object to take on different forms. n Java, polymorphism refers to the ability of a class to provide different implementations of a method, depending on the type of object that is passed to the method.


Polymorphism in Java is the task that performs a single action in different ways


Real-Life Examples of Polymorphism


A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations. This is called polymorphism. 


In Java polymorphism is mainly divided into two types: 

  • Compile-time Polymorphism (Method Overloading)
  • Runtime Polymorphism (Method Overriding)

Compile-time polymorphism : Compile-time polymorphism is also know as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. Method Overloading When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.


Runtime Polymorphism: It is also known as Dynamic Method Dispatch. Method overriding is the process when the subclass or a child class has the same method as declared in the parent class

Core Java


  • OOPS Concepts
  • Core Java
  • String Immutable 
  • Exception Handling 
  • Threading 
  • Immutable 
  • Comparator and Comparable