Thursday, August 5, 2021

How to sort an HashMap based on value

 
 

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortHashMapByValue {

	public static void main(String[] args) {

		HashMap<String,Integer> unsortMap = new HashMap<String, Integer>();
		unsortMap.put("Ram", 10);
		unsortMap.put("Syam", 50);
		unsortMap.put("Radhe", 5);
		unsortMap.put("Krishna", 80);
		unsortMap.put("Suneel", 20);
		
		System.out.println("Before sorting:");
		printMap(unsortMap);
        
		System.out.println("\n");
		System.out.println("Sorting sorting:");
		HashMap<String,Integer> sortedMap = (sortHashMap(unsortMap));
		printMap(sortedMap);
		
	}

	private static HashMap<String, Integer> sortHashMap(HashMap<String, Integer> unsortMap) {
		List<Entry<String, Integer>> list = new LinkedList<Map.Entry<String,Integer>>(unsortMap.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {

			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for (Entry<String, Integer> entry : list) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		return sortedMap;
	}

	private static void printMap(HashMap<String, Integer> unsortMap) {
		
		for(Entry<String, Integer> entry : unsortMap.entrySet()) {
			
			System.out.println("The Key is :- "+entry.getKey()+" The Value is:- "+entry.getValue());
		}
	}

}

Output:-

Before sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Krishna The Value is:- 80 The Key is :- Syam The Value is:- 50 The Key is :- Suneel The Value is:- 20 The Key is :- Ram The Value is:- 10 Sorting sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Ram The Value is:- 10 The Key is :- Suneel The Value is:- 20 The Key is :- Syam The Value is:- 50 The Key is :- Krishna The Value is:- 80

How to reverse linked list without using inbuild function or extra loop

  
import java.util.LinkedList;

public class LinkedListReversePractice {

	public static void main(String[] args) {

		LinkedList<Integer> numbers = new LinkedList<Integer>();
		numbers.add(1);
		numbers.add(2);
		numbers.add(3);
		numbers.add(4);
		numbers.add(5);
		
		System.out.println("LinkedList before reversion:- "+numbers);
		
		numbers = reverseLinkedList(numbers);
		System.out.println("LinkedList after reversion:- "+numbers);
		
	}

	private static LinkedList<Integer> reverseLinkedList(LinkedList<Integer> numbers) {
		
		for(int i = 0; i< numbers.size()/2; i++) {
			 
			int temp = numbers.get(i);
			numbers.set(i, numbers.get(numbers.size()-1-i));
			numbers.set(numbers.size()-1-i, temp);
			
		}
		return numbers;
	}
	
}

Output:-

LinkedList before reversion:- [1, 2, 3, 4, 5] LinkedList after reversion:- [5, 4, 3, 2, 1]

How to find prime numbers from 1 to 100


public class PrimeNumber1To100 {

	public static void main(String[] args) {

		System.out.println("Prime numbers from 1 to 100 are :");

		for(int i=1;i<=100;i++) {
			
			int counter=0;
			for(int num = i;num>=1;num--) {
				
				if(i%num == 0) {
					
					counter++;
				}
			}
			if(counter == 2) {
				System.out.print(i+" ");
			}
		}
	}

}

Output:-

Prime numbers from 1 to 100 are : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Least repeated Item in the Integer Array

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

public class LeastRepeatedNumber {

	public static void main(String[] args) {

		int[] array1 = {1,1,3,2,3,1,4,2,2};
		System.out.println("Least Repeated Number is : "+findLeastRepatedNumber(array1));

	}
	public static Integer findLeastRepatedNumber(int ...array) {
		Integer leastRepatedCount=0;
		Map<nteger,Integer> map = new HashMap<>();
		Integer leastRepeatedItem=null;
		for(int i:array) {

			if(map.containsKey(i)) {
				int counter = map.get(i)+1;
				map.put(i, counter);
			}else {
				map.put(i,1);
			}

		}

		for(Entry<Integer, Integer> entry : map.entrySet()) {

			int v = entry.getValue();
			int k = entry.getKey();
			if(v>1) {

				if(leastRepatedCount==0 || v<leastRepatedCount) {
					leastRepatedCount = v;
					leastRepeatedItem = k;
				}

			}

		}
		return leastRepeatedItem;
	}
}


Output:-

Least Repeated Number is : 3

Thursday, March 18, 2021

Common elements in two sorted arrays



import java.util.ArrayList;
import java.util.Arrays;

public class CommonNumbers {

	public static void main(String[] args) {
          int[] array1A = {1, 3, 4, 6, 7, 9};
          int[] array2A = {1, 2, 4, 5, 9, 10};
          Integer[] com = common(array1A,array2A);
          for(int i : com) {
              System.out.println(i);
          }

	}

	public static Integer[] common(int array1[], int array2[]) {
		
		int p1=0,p2=0;
		ArrayList<Integer> list = new ArrayList<>();
		while(p1<array1.length && p2 < array2.length) {
			
			if(array1[p1]  == array2[p2]) {
				list.add(array1[p1]);
				p1++;
				p2++;
			}else if(array1[p1] > array2[p2]) {
				p2++;
			}else {
				p1++;
			}
		}
		Integer[] common = new Integer[list.size()];
		return list.toArray(common);
	}
}

Output:-

1 4 9

Wednesday, March 17, 2021

How to find pair of two numbers that's multiply equals to Key

  

    import java.util.ArrayList;

    public class FindPair {

        public static void main(String[] args) {
            int arr[] = {1,2,4,6,3,5}; 
            int key = 20; 
            findPair(arr,key);


        }

        private static void findPair(int[] arr, int key) {
            ArrayList<Integer> numbers = new ArrayList<>();
            boolean status = false;
            for(int num : arr) {

                int anotherNumber = (key/num);
                if(numbers.contains(anotherNumber) && (anotherNumber*num) == key) {
                    status=true;
                    System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
                }
                numbers.add(num);
            }
            if(!status)
                System.out.print("No such pair"); 

        }

    }

Output:-

Pair Found:- (4,5)

Most Frequently Occurring Item in an Array

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

  public class MostOccuranceNumber {

      public static void main(String[] args) {

          int[] array1 = {1,2,4,1,3,6,1};
          System.out.println(mostOccurance(array1));

      }
      public static Integer mostOccurance(int ...array) {
          Integer mostCount=0;
          Map<Integer,Integer> map = new HashMap<>();
          Integer mostItem=null;
          for(int i:array) {

              if(map.containsKey(i)) {
                  int counter = map.get(i)+1;
                  map.put(i, counter);
              }else {
                  map.put(i,1);
              }
              if(map.get(i) > mostCount) {
                  mostCount = map.get(i);
                  mostItem = i;
              }
          }
          return mostItem;
      }
  }

Output:-

1

Monday, February 8, 2021

How to find middle element of LinkedList without using inbuilt method or extra loop

 

1) List Interface Implementation

public interface List<T extends Comparable<T>> { public Node<T> getMiddleNode(); public void insert(T data); public void remove(T data); public void traverse(); public int size(); public void reverse(); }

2) Linked List's Node Implementation

public class Node<T extends Comparable<T>> { private Node<T> nextNode; T data; public Node(T data){ this.data = data; } public Node<T> getNextNode() { return nextNode; } public void setNextNode(Node<T> nextNode) { this.nextNode = nextNode; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return data+"-> "; } }

3) Linked List Implementation

public class LinkedList<T extends Comparable<T>> implements List<T> { private Node<T> head; int sizeCounter=0; @Override public Node<T> getMiddleNode() { ==> Example to find middle node of LinkedList Node<T> slow = head; Node<T> fast = head; while(fast.getNextNode() != null && fast.getNextNode().getNextNode() != null) { slow = slow.getNextNode(); fast = fast.getNextNode().getNextNode(); } return slow; } @Override public void insert(T data) { sizeCounter++; if(head==null) { head = new Node<T>(data); }else { insertBiginning(data); } } private void insertBiginning(T data) { Node<T> node = new Node<T>(data); node.setNextNode(head); head = node; } @Override public void remove(T data) { if(head == null) return; if(head.getData().compareTo(data) == 0) { head = head.getNextNode(); }else { remove(data,head, head.getNextNode()); } } private void remove(T data, Node<T> previousNode, Node<T> actualNode) { while(actualNode != null) { if(actualNode.getData().compareTo(data)==0) { ==> This is the reason we use generic type which extends Comparable sizeCounter--; previousNode.setNextNode(actualNode.getNextNode()); actualNode=null; return; } previousNode = actualNode; actualNode = actualNode.getNextNode(); } } @Override public void traverse() { ==> Example to traverse linked list r if(head==null) return; Node<T> actualNode = head; while(actualNode != null) { System.out.print(actualNode); actualNode = actualNode.getNextNode(); } } @Override public int size() { return sizeCounter; } @Override public void reverse() { ==> Example to reverse LinkedList Node<T> prev = null; Node<T> next = null; Node<T> current = head; while(current != null) { next = current.getNextNode(); current.setNextNode(prev); prev = current; current = next; } head = prev; } }

4) Linked List uses example

public class AppRunner { public static void main(String[] args) { LinkedList<String> names = new LinkedList<>(); names.insert("narayan"); names.insert("Pawan"); names.insert("Karan"); names.insert("Sonu"); names.insert("Ram"); names.traverse(); ==> Traversing Linked List System.out.println(""); System.out.println("Middle node is :- "+names.getMiddleNode());==> Finding middle element without using extra loop names.reverse(); ==> Reversing linkedList without inbuilt function System.out.println(""); names.traverse(); } }

5) Output:-

Before Reverse:- Tarun-> Nishant-> Gajendra-> Sonpal-> Ravi-> Anurag-> Narayan-> After ReversingNarayan-> Anurag-> Ravi-> Sonpal-> Gajendra-> Nishant-> Tarun-> Middle node is :- Sonpal->

Friday, February 5, 2021

What will be the output of given example



public class StringConcating {

	public static void main(String[] args) {
		String str ="Hello";
		String str2 = "Narayan";
		String str3 = "HelloNarayan";
		String str4 = str+str2;
		
		if(str3 == str4) {
			System.out.println("Match");
		}else {
			System.out.println("Not Match");
		}
	}

}


Output:-
Not Match


Now you may wordering bcoz both object have same value still not match
so reason behind of this is when we do any operation over string it
return new object that will store in heap memory so we can say that str4 store
in heap while str3 will store in string constant pool and can't change value
of it since string is immutable

Thursday, February 4, 2021

How to reverse an Array without using extra memory



public class ReverseArrayWithoutExtraMemory {

	public static void main(String[] args) {
		int arr[] = {1,2,3,4,5,6};
		int swapArray[] = new ReverseArrayWithoutExtraMemory().swapArray(arr);
		for (int i : swapArray) {
			System.out.print(i+" ");
		}
	}

	public int[] swapArray(int[] arr) {
		int startIndex=0;
		
		int lastIndex= arr.length-1;
		while(lastIndex > startIndex) {
			
			swapItem(arr, startIndex, lastIndex);
			lastIndex--;
			startIndex++;
		}
		return arr;
	}

	public void swapItem(int[] arr, int startIndex, int lastIndex) {
		int temp = arr[startIndex];
		arr[startIndex] = arr[lastIndex];
		arr[lastIndex] = temp;
		
	}

}

Output:-
6 5 4 3 2 1

How to find biggest item in the array within constant time complexity




public class BiggestnumberInArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[] = {1,8,10,40,30,60,50,0,-2}; 
		System.out.println("The biggest Item is : "+
        new BiggestnumberInArray().findBiggestItem(arr));
	}

	public int findBiggestItem(int arr[]) {
		int biggest=0;
		for (int i : arr) {
			
			if(biggest==0) {
				biggest=i;
			}
			if(biggest < i) {
				biggest = i;
			}
		}
		return biggest;
	}
}


Output:-
The biggest Item is : 60

How to find smallest item in the array within constant time complexity

	
    
public class SmallestItemIntoArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[] = {1,8,10,40,30,60,50,0,-2}; 
        
		System.out.println("The smallest Item is : "+
        	new SmallestItemIntoArray().smallestItem(arr));
	}

	public int smallestItem(int arr[]) {
		int smallest=0;
		for (int i : arr) {
			
			if(smallest==0) {
				smallest=i;
			}
			if(smallest > i) {
				smallest = i;
			}
		}
		return smallest;
	}
}


Output:-
The smallest Item is : -2
    

Stack Implementation using Array Data structure


Stack Implementation

import java.util.Arrays;
public class Stack {

	private int count=0;
	private T[] data;
	
	Stack(){
		data = (T[]) new Object[1];
	}
	
	public int size() {
		return count;
	}
	public boolean isEmpty() {
		return count==0;
	}
	public void push(T newItem) {
		
		if(count==data.length) {
			resize(2*data.length);
		}
		data[count++] = newItem;
	}
	public T pop() {
		T item = data[--count];
		if(count>0 && count == (data.length/4)){
			resize(data.length/2);
		}
		return item;
	}
	public void resize(int newCapacity){
		T stackCopy[] = Arrays.copyOf(data, newCapacity);
		data = stackCopy;
	}
}



App Runner:-


public class StackApp {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Stack stack = new Stack();
		stack.push(10);
		stack.push(30);
		stack.push(4);
		stack.push(7);
		stack.push(14);
		
		while(!stack.isEmpty())
			System.out.println(stack.pop());
	}

}


Output:-
14
7
4
30
10

How to find pair of two numbers whose difference equivalent to given key less than N square time complexity


  
public class DifferencePair {

	public static void main(String[] args) {
		int arr[] = {1,8,10,40,30,60,50}; 
		int n = 10;  
		findPair(arr,n);

	}

	private static void findPair(int[] arr, int n) {
		ArrayList<Integer> numbers = new ArrayList<>();
		boolean status = false;
		for(int num : arr) {
			
			if(numbers.contains((num-n))){
				status=true;
				System.out.println("Pair Found: "+"( "+(num-n)+", "+ num+" )"); 
			}
			
			if (numbers.contains((num+n))) {
				status=true;
				System.out.println("Pair Found: "+"( "+(num+n)+", "+ num+" )"); 
			}

			numbers.add(num);
		}
		if(!status)
			System.out.print("No such pair"); 
	}

}

Output:-
Pair Found: ( 40, 30 )
Pair Found: ( 40, 50 )
Pair Found: ( 60, 50 )

How to find Pair of two sum element equivalent to given key less than N square time complexity


  
public class SumPair {

	public static void main(String[] args) {
		int arr[] = {5,7,8,3,1,4,6,9,2}; 
		int n = 12; 
		findPair(arr,n);

	}

	private static void findPair(int[] arr, int n) {
		ArrayList<Integer> numbers = new ArrayList<>();
		boolean status = false;
		for(int num : arr) {
			
			int anotherNumber = (n-num);
			if(numbers.contains(anotherNumber) && (anotherNumber+num) == n) {
				status=true;
				System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
			}
			numbers.add(num);
		}
		if(!status)
			System.out.print("No such pair");
	}

}

Output:- 

Pair Found: ( 5, 7 )
Pair Found: ( 8, 4 )
Pair Found: ( 3, 9 )

How to sort an HashMap based on value

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java....