├── README.md ├── Recursion 1:Print Numbers ├── Recursion 1a:Multiplication (Recursive) ├── Assignment: Recursion 1a:Sum of digits (recursive) ├── Time and Space Complexity Analysis:Find the Unique Element ├── Recursion 1:Calculate Power ├── Recursion 1a:Geometric Sum ├── Recursion 1:Recursion 1 ├── Linked List 1:Print reverse LinkedList ├── Linked List 1:Length of LL ├── Time and Space Complexity Analysis:Duplicate in array ├── Recursion 1:Sum of Array ├── Recursion 2:Staircase ├── Linked List 2:Midpoint of Linked list ├── Recursion 1a:Count Zeros ├── Linked List 2:Delete node (recursive) ├── Recursion 1b:String to Integer ├── Recursion 2:Remove Duplicates Recursively ├── Linked List 1:Print ith Node ├── Recursion 1a:Check Palindrome (recursive) ├── DP - 1:Staircase ├── Recursion 1b:Remove X ├── Linked List 2:Reverse LL (Iterative) ├── Recursion 1:Check Number in Array ├── Recursion 2:Replace Character Recursively ├── Linked List 2:Find a node in LL (recursive) ├── Recursion 1b:Pair star ├── Recursion 1:First Index of Number ├── DP - 1:Minimum Count of Squares ├── Hashmaps::Extract Unique characters ├── Recursion 1b:Replace pi (recursive) ├── Linked List 1:Find a node in LL ├── Recursion 1:Last Index of Number ├── Recursion 1b:Tower of Hanoi ├── Recursion 2:Check AB ├── Test 1:Does s contain t ? ├── Time and Space Complexity Analysis:Pair sum in array ├── DP1:Min Steps to One ├── Recursion 2:Binary Search (Recursive) ├── Priority Queues:Kth largest element ├── DP - 1:Min Steps to One using DP ├── Linked List 1:Delete Node in LL ├── Time and Space Complexity Analysis:Rotate array ├── Priority Queues:Buy the ticket ├── Priority Queues:Merge K sorted arrays ├── Linked List 1:Eliminate duplicates from LL ├── Time and Space Complexity Analysis:Print Array intersection ├── DP-2:Longest Increasing Subsequence ├── Hashmaps:Maximum Frequency Number ├── Recursion 2:Print Permutations - String ├── Binary Search Trees:Search Node in BST ├── Binary Search Trees: Print Elements in Range ├── Priority Queues:K largest elements ├── Recursion 2:Return Permutations - String ├── Test 1:Split Array ├── Linked List 2:Delete every N nodes ├── Binary Search Trees:Create & Insert Duplicate Node ├── Recursion 1:All Indices of Number ├── DP - 2:0 1 Knapsack ├── DP-2: Edit Distance ├── FractionUse class ├── Time and Space Complexity Analysis:Check array rotation ├── Linked List 1:AppendLastNToFirst ├── Recursion 2:Print Subsets of Array ├── Binary Search Trees:LCA of Binary Tree ├── DP-2:Coin Tower ├── DP - 2:Loot Houses ├── BST and Binary Tree Assignment:replace with Sum of greater nodes ├── Linked List 2:Reverse LL (Recursive) ├── Recursion 2:Print Subset Sum to K ├── Recursion 2:Print all Codes - String ├── Linked List 2:Swap two Node of LL ├── Hashmaps:Print Intersection ├── Recursion 2: Return subset of an array ├── Binary Search Trees:Construct BST From Sorted Array ├── Recursion 2:Return subsets sum to K ├── Hashmaps:Longest subset zero sum ├── Linked List 2:Merge two sorted LL ├── Recursion 2:Return Keypad Code ├── Hashmaps:Pair Sum to 0 ├── Graphs:Is Connected ? ├── Linked List 1:Palindrome LinkedList ├── Linked List 2:kReverse ├── DP-2:Maximum Square Matrix With All Zeros ├── Graphs: Has Path ├── Recursion 2:Merge Sort Code ├── Binary Search Trees:LCA of BST ├── Graphs:BFS Traversal ├── ComplexNumbers ├── Stacks and Queues:Minimum bracket Reversal ├── Linked List 2:Bubble Sort (Iterative) LinkedList ├── Binary Search Trees:Find Path in BST ├── Graphs:Get Path - DFS ├── DynamicArray ├── Graphs:All connected components ├── Recursion 2:Return all codes - String ├── Priority Queues:Check Max-Heap ├── DP - 1:Number of Balanced BTs ├── Hashmaps:Pairs with difference K ├── Recursion 2:Print Keypad Combinations Code ├── BST and Binary Tree Assignment::Print nodes at distance k from node ├── Graphs-2:Dijkstra's Algorithm ├── Graphs-2:Prim's Algo ├── DP - 1:Number of Balanced BTs Using DP ├── Priority Queues:In-place heap sort ├── Fraction class ├── Binary Search Trees:BST to Sorted LL ├── Tries and Huffman Coding:Search word in Trie ├── Recursion 2:Quick Sort Code ├── Time and Space Complexity Analysis:Triplet Sum ├── Graphs:Get Path - BFS ├── Linked List 2:Merge Sort ├── Hashmaps:Longest consecutive Sequence ├── Linked List 2:Even after Odd LinkedList ├── Tries and Huffman Coding:Palindrome Pair ├── DP - 2:Knapsack(Memoization and DP) ├── Graphs-2: Kruskal's Algorithm ├── Tries and Huffman Coding:Pattern Matching ├── Binary Search Trees:Path Sum Root to Leaf ├── OOPS-4:Othello Move Function ├── Tries and Huffman Coding:Auto complete ├── BST and Binary Tree Assignment::Pair sum in a BST ├── Priority Queues:Running median ├── DP-2:Matrix Chain Multiplication ├── DP - 2:Edit Distance(Memoization and DP) ├── DP - 2:Maximum Square Matrix With All Zeros ├── Priority Queues:Max Priority Queue ├── Tries and Huffman Coding:Count Words in Trie ├── Binary Search Trees:Check if a Binary Tree is BST ├── Priority Queues:Remove Min ├── Polynomial class ├── Binary Search Trees:Pair sum BInary Tree ├── BST and Binary Tree Assignment:Largest BST └── Binary Search Trees:BST Class /README.md: -------------------------------------------------------------------------------- 1 | # Coding ninjas data structure through java all solutions 2 | -------------------------------------------------------------------------------- /Recursion 1:Print Numbers: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static void print(int n){ 4 | if(n == 0) 5 | return; 6 | 7 | print(n - 1); 8 | System.out.print(n+" "); 9 | 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Recursion 1a:Multiplication (Recursive): -------------------------------------------------------------------------------- 1 | public class solution 2 | { 3 | public static int multiplyTwoIntegers(int m, int n) 4 | { 5 | if(n==0) 6 | return 0; 7 | return m+multiplyTwoIntegers(m,n-1); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Assignment: Recursion 1a:Sum of digits (recursive): -------------------------------------------------------------------------------- 1 | public class solution { 2 | public static int sumOfDigits(int input){ 3 | // Write your code here 4 | if(input==0) 5 | return 0; 6 | return (input%10)+sumOfDigits(input/10); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Time and Space Complexity Analysis:Find the Unique Element: -------------------------------------------------------------------------------- 1 | public class FindUnique{ 2 | public static int findUnique(int[] arr){ 3 | int ans=arr[0]; 4 | for(int i=1;i root) { 3 | if(root==null) 4 | return; 5 | printReverseRecursive(root.next); 6 | System.out.print(root.data+" "); 7 | 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Linked List 1:Length of LL: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public static int length(LinkedListNode head){ 4 | LinkedListNode temp=head; 5 | int count=1; 6 | while(temp.next!=null){ 7 | temp=temp.next; 8 | count++; 9 | } 10 | return count; 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Time and Space Complexity Analysis:Duplicate in array: -------------------------------------------------------------------------------- 1 | public class DuplicateInArray{ 2 | public static int duplicate(int[] arr){ 3 | int sum=0; 4 | for(int i=0;i head) { 3 | LinkedListNode slow=head,fast=head; 4 | while(fast.next!=null && fast.next.next!=null) 5 | { 6 | slow=slow.next; 7 | fast=fast.next.next; 8 | } 9 | return slow.data;} 10 | } 11 | -------------------------------------------------------------------------------- /Recursion 1a:Count Zeros: -------------------------------------------------------------------------------- 1 | public class solution { 2 | public static int countZerosRec(int input){ 3 | if(input<10){ 4 | if(input==0) 5 | return 1; 6 | else 7 | return 0; 8 | } 9 | int smallAns= countZerosRec(input/10); 10 | if(input%10==0) 11 | smallAns=1+smallAns; 12 | return smallAns; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Linked List 2:Delete node (recursive): -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public static LinkedListNode deleteIthNodeRec(LinkedListNode head, int i) 4 | { 5 | if(head==null) 6 | return head; 7 | if(i==0) 8 | return head.next; 9 | head.next=deleteIthNodeRec(head.next,i-1); 10 | return head; 11 | 12 | 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Recursion 1b:String to Integer: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | public class solution 3 | { 4 | public static int convertStringToInt(String input) 5 | { 6 | if(input.length()==1) 7 | return input.charAt(0)-'0'; 8 | int ans=convertStringToInt(input.substring(1)); 9 | int x= input.charAt(0)-'0'; 10 | x= x*(int)Math.pow(10,input.length()-1)+ans; 11 | return x; 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Recursion 2:Remove Duplicates Recursively: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static String removeConsecutiveDuplicates(String s) { 3 | if(s.length()<=1) 4 | return s; 5 | String smallans=removeConsecutiveDuplicates(s.substring(1)); 6 | if(smallans.charAt(0)==s.charAt(0)) 7 | return smallans; 8 | else 9 | return s.charAt(0)+smallans; 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Linked List 1:Print ith Node: -------------------------------------------------------------------------------- 1 | 2 | public class Solution 3 | { 4 | public static void printIth(LinkedListNode head, int i) 5 | { 6 | int count=0; 7 | LinkedListNode temp=head; 8 | while(count!=i && temp!=null) 9 | { 10 | temp=temp.next; 11 | count++; 12 | } 13 | if( count==i &&temp!=null) 14 | System.out.println(temp.data); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Recursion 1a:Check Palindrome (recursive): -------------------------------------------------------------------------------- 1 | public class solution 2 | { 3 | public static boolean isStringPalindrome(String input) 4 | { 5 | if(input.length()<=1) 6 | return true; 7 | if(input.charAt(0)==input.charAt(input.length()-1)){ 8 | return isStringPalindrome(input.substring(1,input.length()-1)); 9 | 10 | } 11 | else 12 | return false; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DP - 1:Staircase: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | 4 | 5 | public static long staircase(int n){ 6 | long storage[]=new long[n+1]; 7 | storage[0]=1; 8 | storage[1]=1; 9 | for(int i=2;i=0) 13 | op2=storage[i-2]; 14 | if(i-3>=0) 15 | op3=storage[i-3]; 16 | storage[i]=op1+op2+op3; 17 | } 18 | return storage[n]; 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Recursion 1b:Remove X: -------------------------------------------------------------------------------- 1 | 2 | public class solution { 3 | 4 | // Return the changed string 5 | public static String removeX(String input){ 6 | // Write your code here 7 | if(input.length()==0) 8 | return input; 9 | 10 | if(input.charAt(0)=='x') 11 | return removeX(input.substring(1)); 12 | 13 | else 14 | return input.charAt(0)+removeX(input.substring(1)); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Linked List 2:Reverse LL (Iterative): -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public static LinkedListNode reverse_I(LinkedListNode head) 4 | { 5 | LinkedListNode prev=null,curr=head,temp; 6 | while(curr!=null) 7 | { 8 | temp=curr.next; 9 | curr.next=prev; 10 | prev=curr; 11 | curr=temp; 12 | } 13 | return prev; 14 | 15 | 16 | 17 | 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Recursion 1:Check Number in Array: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static boolean checkNumber(int input[], int x) { 4 | return checkNumber(input,x,0); 5 | } 6 | private static boolean checkNumber(int input[],int x,int startIndex){ 7 | if(startIndex==input.length) 8 | return false; 9 | if(input[startIndex]==x) 10 | return true; 11 | return checkNumber(input,x,startIndex+1); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Recursion 2:Replace Character Recursively: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public static String replaceCharacter(String input, char c1, char c2) 4 | { 5 | if(input.length()==0) 6 | return input; 7 | if(input.charAt(0)==c1) 8 | return c2+replaceCharacter(input.substring(1),c1,c2); 9 | else 10 | return input.charAt(0)+replaceCharacter(input.substring(1),c1,c2); 11 | 12 | 13 | 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Linked List 2:Find a node in LL (recursive): -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public static int indexOfNRec(LinkedListNode head, int n) { 4 | return helper(head,0,n); 5 | } 6 | public static int helper(LinkedListNode head,int index,int n){ 7 | if(head==null) 8 | return -1; 9 | if(head.data==n) 10 | return index; 11 | int ans= helper(head.next,index+1,n); 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Recursion 1b:Pair star: -------------------------------------------------------------------------------- 1 | public class solution { 2 | 3 | // Return the updated string 4 | public static String addStars(String s) { 5 | // Write your code here 6 | if(s.length()==1) 7 | return s; 8 | String smallans=addStars(s.substring(1)); 9 | if(s.charAt(0)==smallans.charAt(0)) 10 | return s.charAt(0)+"*"+smallans; 11 | else 12 | return s.charAt(0)+smallans; 13 | 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Recursion 1:First Index of Number: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int firstIndex(int input[], int x) { 3 | //method overloading 4 | return firstIndex(input,x,0); 5 | 6 | } 7 | private static int firstIndex(int input[],int x,int startIndex){ 8 | if(startIndex==input.length) 9 | return -1; 10 | if(input[startIndex]==x) 11 | return startIndex; 12 | return firstIndex(input,x,startIndex+1); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DP - 1:Minimum Count of Squares: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | 4 | public static int minCount(int n) { 5 | int storage[]=new int[n+1]; 6 | if(n<=3) { 7 | return n; 8 | } 9 | storage[0]=0; 10 | storage[1]=1; 11 | storage[2]=2; 12 | storage[3]=3; 13 | for(int i=4;i<=n;i++) { 14 | int ans=i; 15 | for(int j=1;j<=Math.sqrt(i);j++) { 16 | ans =Math.min(ans, storage[i-j*j]+1); 17 | } 18 | storage[i]=ans; 19 | } 20 | return storage[n]; 21 | 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Hashmaps::Extract Unique characters: -------------------------------------------------------------------------------- 1 | import java.util.Set; 2 | import java.util.HashMap; 3 | public class solution { 4 | 5 | public static String uniqueChar(String str){ 6 | HashMap h=new HashMap<>(); 7 | String s=""; 8 | for(int i=0;i head, int n) { 4 | if(head==null) 5 | return -1; 6 | LinkedListNode temp=head; 7 | int count=0; 8 | while(temp!=null && temp.data!=n) 9 | { 10 | temp=temp.next; 11 | count++; 12 | } 13 | if(temp!=null) 14 | return count; 15 | else 16 | return -1; 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Recursion 1:Last Index of Number: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | 4 | public static int lastIndex(int input[], int x) { 5 | return lastIndexHelper(input, x, 0); 6 | } 7 | public static int lastIndexHelper(int input[], int x, int si){ 8 | 9 | if(si==input.length){ 10 | return -1; 11 | } 12 | int sans=lastIndexHelper(input, x, si+1); 13 | if(sans != -1){ 14 | return sans; 15 | } 16 | else{ 17 | if(input[si]==x){ 18 | return si; 19 | } 20 | else 21 | return -1; 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Recursion 1b:Tower of Hanoi: -------------------------------------------------------------------------------- 1 | public class solution 2 | { 3 | public static void towerOfHanoi(int disks, char source, char auxiliary, char destination) 4 | { 5 | if(disks==0) 6 | return; 7 | else if(disks==1) 8 | { System.out.println(source+" "+destination); 9 | return; 10 | } 11 | 12 | towerOfHanoi(disks-1,source,destination,auxiliary); 13 | System.out.println(source+" "+destination); 14 | towerOfHanoi(disks-1,auxiliary,source,destination); 15 | 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Recursion 2:Check AB: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static boolean checkAB(String input) { 4 | // Write your code here 5 | 6 | if(input.length() == 0){ 7 | return true; 8 | } 9 | 10 | if(input.charAt(0) == 'a'){ 11 | if(input.substring(1).length() > 1 && input.substring(1,3).equals("bb")){ 12 | return checkAB(input.substring(3)); 13 | }else{ 14 | return checkAB(input.substring(1)); 15 | } 16 | } 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Test 1:Does s contain t ?: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public static boolean checkSequence(String a, String b) { 4 | if(b.length() == 0){ 5 | return true; 6 | } 7 | if(a.length() == 0){ 8 | return false; 9 | } 10 | 11 | if(a.charAt(0) == b.charAt(0)){ 12 | a = a.substring(1); 13 | b = b.substring(1); 14 | }else{ 15 | a = a.substring(1); 16 | } 17 | 18 | boolean ans = checkSequence(a,b); 19 | 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Time and Space Complexity Analysis:Pair sum in array: -------------------------------------------------------------------------------- 1 | public class PairSum{ 2 | public static void pairSum(int[] arr, int num){ 3 | 4 | for(int i=0;io3) 16 | minSteps=o3;} 17 | 18 | 19 | if(n%2==0){ 20 | int o2=countStepsTo1(n/2); 21 | if(minSteps>o2) 22 | minSteps=o2; 23 | } 24 | 25 | return 1+minSteps; 26 | 27 | 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Recursion 2:Binary Search (Recursive): -------------------------------------------------------------------------------- 1 | public class solution { 2 | public static int binarySearch(int input[], int element) { 3 | return helper(input,element,0,input.length-1); 4 | } 5 | private static int helper(int input[],int element,int si,int ei) 6 | { 7 | if(si>ei) 8 | return -1; 9 | 10 | int mid=(si+ei)/2 ; 11 | if(element==input[mid]) 12 | return mid; 13 | else if(element pq=new PriorityQueue<>(); 8 | int i=0; 9 | for(;i deleteIthNode(LinkedListNode head, int i) 5 | { 6 | if(head==null ) 7 | return head; 8 | if(i==0) 9 | return head.next; 10 | int count=0; 11 | LinkedListNode temp=head; 12 | while(temp!=null && countarr.length) 8 | d=d-arr.length; 9 | reverseArray(arr,0,arr.length-1); 10 | reverseArray(arr,0,arr.length-1-d); 11 | reverseArray(arr,arr.length-d,arr.length-1); 12 | 13 | } 14 | private static void reverseArray(int[] arr,int start,int end) 15 | { 16 | int temp; 17 | while(start pq = new PriorityQueue<>(Collections.reverseOrder()); 8 | 9 | for(int i=0;i mergeKSortedArrays(ArrayList> input) { 7 | ArrayList ary=new ArrayList<>(); 8 | PriorityQueue pq=new PriorityQueue<>(); 9 | for(int i=0;i temp=input.get(i); 11 | for(int j=0;j removeDuplicates(LinkedListNode head) 4 | { 5 | if(head==null) 6 | return head; 7 | if(head.next==null) 8 | return head; 9 | LinkedListNode t1=head,t2=head.next; 10 | LinkedListNode finalhead=head; 11 | while(t2!=null){ 12 | if(t1.data.equals(t2.data)) 13 | { 14 | t2=t2.next; 15 | } 16 | else{ 17 | t1.next=t2; 18 | t1=t2; 19 | } 20 | } 21 | 22 | t1.next=null; 23 | return finalhead; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Time and Space Complexity Analysis:Print Array intersection: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Intersection{ 3 | public static void intersection(int[] arr1, int[] arr2){ 4 | Arrays.sort(arr1); 5 | Arrays.sort(arr2); 6 | merge(arr1,arr2); 7 | 8 | } 9 | private static void merge(int arr1[] ,int arr2[]){ 10 | int i=0,j=0; 11 | 12 | while(i=0;j--){ 13 | if(arr[j]max) 21 | max=storage[i]; 22 | } 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Hashmaps:Maximum Frequency Number: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | public class Solution { 3 | 4 | public static int maxFrequencyNumber(int[] arr){ 5 | HashMap h=new HashMap<>(); 6 | for(int i=0;imax){ 19 | max=h.get(arr[i]); 20 | maxKey=arr[i];} 21 | } 22 | 23 | 24 | 25 | return maxKey ; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Recursion 2:Print Permutations - String: -------------------------------------------------------------------------------- 1 | public class solution { 2 | 3 | public static void permutations(String input){ 4 | // Write your code here 5 | 6 | print(input,""); 7 | 8 | } 9 | 10 | private static void print(String input,String output){ 11 | if(input.length() == 0){ 12 | System.out.println(output); 13 | return; 14 | } 15 | 16 | for(int i=0;i { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static BinaryTreeNode searchInBST(BinaryTreeNode root , int k){ 17 | if(root==null) 18 | return null; 19 | BinaryTreeNode ans; 20 | if(root.data==k) 21 | return root; 22 | 23 | else if(k>root.data) 24 | ans=searchInBST(root.right,k); 25 | else 26 | ans=searchInBST(root.left,k); 27 | return ans; 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Binary Search Trees: Print Elements in Range: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /* Binary Tree Node class 4 | * 5 | * class BinaryTreeNode { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static void printNodeFromK1ToK2(BinaryTreeNode root,int k1,int k2){ 17 | if(root==null) 18 | return ; 19 | 20 | if(root.data>k1) 21 | printNodeFromK1ToK2( root.left, k1, k2); 22 | if(root.data>=k1 && root.data<=k2){ 23 | System.out.print(root.data+" "); 24 | } 25 | if(root.data<=k2) 26 | printNodeFromK1ToK2( root.right, k1, k2); 27 | 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Priority Queues:K largest elements: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | import java.util.ArrayList; 3 | public class Solution 4 | { 5 | public static ArrayList kLargest(int input[], int k) 6 | { 7 | ArrayList ary=new ArrayList<>(); 8 | PriorityQueue pq= new PriorityQueue<>(); 9 | int i=0; 10 | for( ;i skipMdeleteN(LinkedListNode head, int M, int N) { 2 | if(head==null) 3 | return head; 4 | if(M==0) 5 | return null; 6 | if(N==0) 7 | return head; 8 | LinkedListNode curr=head,t; 9 | int count; 10 | while(curr!=null) 11 | { 12 | for(count=1;count { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static void insertDuplicateNode(BinaryTreeNode root) { 17 | // Write your code here 18 | if(root==null) 19 | return; 20 | BinaryTreeNode duplicateNode=new BinaryTreeNode(root.data); 21 | duplicateNode.left=root.left; 22 | root.left=duplicateNode; 23 | insertDuplicateNode(duplicateNode.left); 24 | insertDuplicateNode(root.right); 25 | return; 26 | 27 | 28 | 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Recursion 1:All Indices of Number: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int[] allIndexes(int input[], int x) { 3 | return allIndexes(input,x,0); 4 | 5 | } 6 | private static int[] allIndexes(int input[],int x,int startIndex){ 7 | if(startIndex==input.length) 8 | { 9 | int output[]=new int[0]; 10 | return output; 11 | } 12 | int smallAns[]=allIndexes(input,x,startIndex+1); 13 | if(input[startIndex]==x) 14 | { 15 | int answer[]=new int[smallAns.length+1]; 16 | answer[0]=startIndex; 17 | for(int i=0;imaxWeight) 11 | return knapsack(weight,sIndex+1,value,maxWeight,n-1); 12 | else 13 | { 14 | //===========//include that weight//=========// 15 | int op2=value[sIndex]+knapsack(weight,sIndex+1,value,maxWeight-weight[sIndex],n-1); 16 | int op3=knapsack(weight,sIndex+1,value,maxWeight,n-1); 17 | return Math.max(op2,op3); 18 | } 19 | 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DP-2: Edit Distance: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public static int editDistance(String s1, String s2){ 4 | if(s1.length()==0 && s2.length()==0) 5 | return 0; 6 | if(s2.length()==0) 7 | return s1.length(); 8 | if(s1.length()==0) 9 | return s2.length(); 10 | 11 | if(s1.charAt(0)==s2.charAt(0)) 12 | return editDistance(s1.substring(1),s2.substring(1)); 13 | else{ 14 | //insert 15 | int op1=editDistance(s1,s2.substring(1)); 16 | //delete 17 | int op2=editDistance(s1.substring(1),s2); 18 | //substitute 19 | int op3=editDistance(s1.substring(1),s2.substring(1)); 20 | return 1+Math.min(op1,Math.min(op2,op3)); 21 | 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /FractionUse class: -------------------------------------------------------------------------------- 1 | package classes_and_objects; 2 | 3 | public class FractionUse { 4 | 5 | public static void main(String[] args) { 6 | Fraction f1 = new Fraction(20,30); 7 | f1.print(); 8 | // 2/3 9 | 10 | f1.setNumerator(12); 11 | // 4/1 12 | int d = f1.getDenominator(); 13 | System.out.println(d); 14 | f1.print(); 15 | // 16 | f1.setNumerator(10); 17 | f1.setDenominator(30); 18 | // 1/3 19 | f1.print(); 20 | // 21 | Fraction f2 = new Fraction(3,4); 22 | f1.add(f2); 23 | f1.print(); 24 | // f1 => 13/12 25 | f2.print(); 26 | // f2 => 3/4 27 | // 28 | Fraction f3 = new Fraction(4,5); 29 | f3.multiply(f2); 30 | f3.print(); 31 | // f3 => 3/5 32 | f2.print(); 33 | // f2 => 3/4 34 | // 35 | Fraction f4 = Fraction.add(f1, f3); 36 | f1.print(); 37 | f3.print(); 38 | f4.print(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Time and Space Complexity Analysis:Check array rotation: -------------------------------------------------------------------------------- 1 | public class CheckRotation { 2 | 3 | public static int arrayRotateCheck(int[] arr){ 4 | int count=0; 5 | for(int i=0;i append(LinkedListNode root, int n) { 3 | 4 | LinkedListNode temp=root; 5 | int count=0; 6 | while(temp!=null ){ 7 | temp=temp.next; 8 | count++; 9 | } 10 | int newcount=count-n; 11 | count=0; 12 | LinkedListNode temp1=root; 13 | while(count temp2=temp1.next; 18 | LinkedListNode temp3=temp1.next; 19 | while(temp2.next!=null){ 20 | temp2=temp2.next; 21 | } 22 | temp2.next=root; 23 | temp1.next=null; 24 | return temp3; 25 | 26 | 27 | 28 | 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Recursion 2:Print Subsets of Array: -------------------------------------------------------------------------------- 1 | public class solution 2 | { 3 | public static void printSubsets(int input[]) 4 | { 5 | int output[]=new int[0]; 6 | printsubsets(input,0,output); 7 | } 8 | public static void printsubsets(int input[],int si,int output[]) 9 | { 10 | if(si==input.length) 11 | { 12 | for(int i:output){ 13 | System.out.print(i+" "); 14 | } 15 | System.out.println(); 16 | return; 17 | } 18 | printsubsets(input,si+1,output); 19 | 20 | int newoutput[]=new int[output.length+1]; 21 | int j=0; 22 | for( ;j { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static int lcaBinaryTree(BinaryTreeNode root , int a, int b){ 17 | // Write your code here 18 | if(root==null) 19 | return -1; 20 | if(root.data==a || root.data==b) 21 | return root.data; 22 | int c=lcaBinaryTree(root.left,a,b); 23 | int d=lcaBinaryTree(root.right,a,b); 24 | if(c==-1 && d==-1) 25 | return -1; 26 | else if(c==-1 && d!=-1) 27 | return d; 28 | else if(c!=-1 && d==-1) 29 | return c; 30 | else 31 | return root.data; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DP-2:Coin Tower: -------------------------------------------------------------------------------- 1 | public class solution { 2 | 3 | public String solve(int n,int x,int y){ 4 | 5 | // Write your code here . 6 | int dp [] = new int[n+1]; 7 | 8 | dp[1] = 1; 9 | 10 | int a1 = 0; 11 | int a2 = 0; 12 | int a3 = 0; 13 | 14 | for(int i=2;i= 1){ 22 | a1 = dp[i-x] ^ 1; 23 | } 24 | if(i-y >= 1){ 25 | a2 = dp[i-y] ^ 1; 26 | } 27 | 28 | a3 = dp[i-1] ^ 1; 29 | 30 | dp[i] = Math.max(a1 ,Math.max(a2 ,a3)); 31 | } 32 | 33 | if(dp[n] != 0){ 34 | return "Beerus"; 35 | }else{ 36 | return "Whis"; 37 | } 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /DP - 2:Loot Houses: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | //recursion 3 | // public static int getMaxMoney(int arr[], int n){ 4 | // return getMaxMoney(arr, n,0); 5 | // } 6 | // public static int getMaxMoney(int arr[], int n,int index){ 7 | // if( arr.length==0 || index>=arr.length) 8 | // return 0; 9 | // int op1=arr[index]+getMaxMoney(arr,n,index+2); 10 | // int op2=getMaxMoney(arr,n,index+1); 11 | // return Math.max(op1,op2); 12 | 13 | 14 | 15 | 16 | 17 | //DP 18 | public static int getMaxMoney(int arr[], int n){ 19 | if(arr.length==0) 20 | return 0; 21 | int storage[]=new int[arr.length]; 22 | storage[0]=arr[0]; 23 | storage[1]=Math.max(arr[1],storage[0]); 24 | for(int i=2;i { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static void replaceWithLargerNodesSum(BinaryTreeNode root) { 17 | if(root == null){ 18 | return; 19 | } 20 | int ans = replace(root ,0); 21 | 22 | 23 | } 24 | public static int replace(BinaryTreeNode root ,int sum){ 25 | if(root == null){ 26 | return 0; 27 | } 28 | 29 | int right = replace(root.right ,sum); 30 | int rootdata = root.data; 31 | root.data = root.data + right + sum; 32 | int left = replace(root.left ,root.data); 33 | 34 | return rootdata + right + left; 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Linked List 2:Reverse LL (Recursive): -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static LinkedListNode reverse_R(LinkedListNode head) { 4 | if(head==null) 5 | return head; 6 | if(head.next==null) 7 | return head; 8 | LinkedListNode tail=head.next; 9 | LinkedListNode smallhead=reverse_R(head.next); 10 | tail.next=head; 11 | head.next=null; 12 | return smallhead; 13 | 14 | 15 | } 16 | } 17 | //or 18 | public class Solution { 19 | public static LinkedListNode reverse_R(LinkedListNode head) { 20 | if(head==null) 21 | return head; 22 | if(head.next==null) 23 | return head; 24 | LinkedListNode head1=reverse_R(head.next); 25 | LinkedListNode temp=head1; 26 | while(temp.next!=null) 27 | { 28 | temp=temp.next; 29 | 30 | } 31 | temp.next=head; 32 | head.next=null; 33 | return head1; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Recursion 2:Print Subset Sum to K: -------------------------------------------------------------------------------- 1 | public class solution { 2 | public static void printSubsetsSumTok(int input[], int k) { 3 | int output[]=new int[0]; 4 | helper(input,0,k,output); 5 | 6 | } 7 | public static void helper(int input[],int si,int k,int output[]){ 8 | if(si==input.length){ 9 | if(k==0) 10 | { 11 | for(int i=0;i=2) 16 | { 17 | int ch2=input.charAt(0)-'0'; 18 | int ch3=input.charAt(1)-'0'; 19 | int x=ch2*10+ch3; 20 | if(x>=10 && x<=26) 21 | { 22 | char ch4=helper1(x); 23 | helper(input.substring(2),output+ch4); 24 | 25 | } 26 | 27 | 28 | } 29 | return;} 30 | private static char helper1(int ch){ 31 | return (char)('a'+ch-1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Linked List 2:Swap two Node of LL: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public static LinkedListNode swap_nodes(LinkedListNode head,int i,int j) 4 | { 5 | LinkedListNode temp=head,prev=null,c1=null,c2=null,p1=null,p2=null; 6 | int pos=0; 7 | while(temp!=null) 8 | { 9 | if(pos==i) 10 | { 11 | p1=prev; 12 | c1=temp; 13 | } 14 | else if(pos==j) 15 | { 16 | p2=prev; 17 | c2=temp; 18 | } 19 | prev=temp; 20 | temp=temp.next; 21 | pos++; 22 | } 23 | if(p1!=null) 24 | { 25 | p1.next=c2; 26 | } 27 | else{ 28 | head=c2; 29 | } 30 | if(p2!=null){ 31 | p2.next=c1; 32 | } 33 | else{ 34 | head=c1; 35 | } 36 | LinkedListNode temp1=c2.next; 37 | c2.next=c1.next; 38 | c1.next=temp1; 39 | return head; 40 | } 41 | } 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Hashmaps:Print Intersection: -------------------------------------------------------------------------------- 1 | import java.util.Set; 2 | import java.util.HashMap; 3 | public class Intersection{ 4 | public static void intersection(int[] arr1, int[] arr2){ 5 | if(arr1.length==0 || arr2.length==0) 6 | return ; 7 | HashMap harr1=new HashMap<>(); 8 | for(int i=0;i=input.length) 9 | { 10 | int ans[][]=new int[1][0]; 11 | return ans; 12 | } 13 | int[][] smallans=subsets(input,si+1); 14 | int[][] ans=new int[smallans.length*2][]; 15 | int k=0; 16 | for(int i=0;i { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static BinaryTreeNode SortedArrayToBST(int[] arr){ 17 | return SortedArrayToBST(arr,0,arr.length-1);} 18 | public static BinaryTreeNode SortedArrayToBST(int[] arr,int si,int ei){ 19 | 20 | if(si>ei) 21 | return null; 22 | 23 | // if(arr.length==0) 24 | // return null; 25 | // if(arr.length==1) 26 | // { 27 | // BinaryTreeNode root=new BinaryTreeNode<>(arr[0]); 28 | // return root; 29 | // } 30 | int mid=(ei+si)/2; 31 | BinaryTreeNode root=new BinaryTreeNode<>(arr[mid]); 32 | 33 | root.left=SortedArrayToBST(arr,si,mid-1); 34 | root.right=SortedArrayToBST(arr,mid+1,ei); 35 | return root; 36 | 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Recursion 2:Return subsets sum to K: -------------------------------------------------------------------------------- 1 | public class solution { 2 | 3 | // Return a 2D array that contains all the subsets which sum to k 4 | public static int[][] subsetsSumK(int input[], int k) { 5 | return helper(input,k,0); 6 | } 7 | public static int[][] helper(int input[], int k,int si) { 8 | if(si==input.length) 9 | { 10 | if(k==0) 11 | return new int[1][0]; 12 | else 13 | return new int[0][0]; 14 | } 15 | int op1[][]=helper(input,k-input[si],si+1);//////////// 16 | int op2[][]=helper(input,k,si+1); 17 | int output[][]=new int[op1.length+op2.length][];//////////////// 18 | int l=0; 19 | for(int i=0;i arr) 12 | { 13 | if(arr.size()==0) 14 | return 0; 15 | HashMap h=new HashMap<>(); 16 | int sum=0; 17 | int maxlength=0; 18 | int maxlength1=0; 19 | for(int i=0;imaxlength) 35 | maxlength=maxlength1; 36 | } 37 | return maxlength; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Linked List 2:Merge two sorted LL: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | 4 | public static LinkedListNode mergeTwoList(LinkedListNode head1, LinkedListNode head2) { 5 | if(head1==null) 6 | return head2; 7 | if(head2==null) 8 | return head1; 9 | LinkedListNode t1=head1,t2=head2,tail=null,head=null; 10 | if(t1.data<=t2.data) 11 | { 12 | head=t1; 13 | tail=t1; 14 | t1=t1.next; 15 | } 16 | else 17 | { 18 | head=t2; 19 | tail=t2; 20 | t2=t2.next; 21 | } 22 | while(t1!=null &&t2!=null) 23 | { 24 | if(t1.data<=t2.data) 25 | { 26 | tail.next=t1; 27 | tail=t1; 28 | t1=t1.next; 29 | } 30 | else 31 | { 32 | tail.next=t2; 33 | tail=tail.next; 34 | t2=t2.next; 35 | } 36 | } 37 | if(t1==null) 38 | tail.next=t2; 39 | if(t2==null) 40 | tail.next=t1; 41 | return head; 42 | 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Recursion 2:Return Keypad Code: -------------------------------------------------------------------------------- 1 | public class solution 2 | { 3 | public static String[] keypad(int n) 4 | { 5 | if(n==0||n==1) 6 | { 7 | String ans[]={""}; 8 | return ans; 9 | } 10 | int newN=n%10; 11 | String[] ans=keypad(n/10); 12 | String helpans=helper(newN); 13 | String finalans[]=new String[helpans.length()*ans.length]; 14 | int k=0; 15 | for(int i=0;i h=new HashMap<>(); 7 | for(int i=0;i0) 14 | System.out.println(-input[i] +" "+ input[i]); 15 | else 16 | System.out.println(input[i] +" "+( -input[i])); 17 | count--; 18 | } 19 | if(h.containsKey(input[i])) 20 | h.put(input[i],h.get(input[i])+1); 21 | else 22 | h.put(input[i],1); 23 | } 24 | else{ 25 | if(h.containsKey(input[i])){ 26 | h.put(input[i],h.get(input[i])+1); 27 | }else{ 28 | h.put(input[i] ,1); 29 | } 30 | } 31 | 32 | 33 | } 34 | 35 | } 36 | } 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Graphs:Is Connected ?: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.*; 3 | public class Solution { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | int V = s.nextInt(); 7 | int E = s.nextInt(); 8 | int edges[][]=new int[V][V]; 9 | for(int i=0;i head) { 3 | 4 | LinkedListNode temp=head,mid,h2; 5 | mid=midPoint(temp); 6 | h2=mid.next ; 7 | mid.next=null; 8 | h2=reverseIt(h2); 9 | boolean flag=false; 10 | while(temp!=null && h2!=null) 11 | { flag=false; 12 | if(temp.data.equals(h2.data)) 13 | flag=true; 14 | temp=temp.next; 15 | h2=h2.next; 16 | 17 | } 18 | return flag; 19 | } 20 | 21 | 22 | private static LinkedListNode reverseIt(LinkedListNode head) 23 | { if(head==null || head.next==null) 24 | return head; 25 | LinkedListNode tail=head.next; 26 | LinkedListNode ans=reverseIt(head.next); 27 | tail.next=head; 28 | head.next=null; 29 | return ans; 30 | 31 | 32 | } 33 | 34 | private static LinkedListNode midPoint(LinkedListNode head){ 35 | LinkedListNode slow=head,fast=head; 36 | while(fast.next!=null && fast.next.next!=null) 37 | { 38 | fast=fast.next.next; 39 | slow=slow.next; 40 | } 41 | return slow;} 42 | 43 | } 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Linked List 2:kReverse: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static LinkedListNode kReverse(LinkedListNode head, int k) { 3 | if(head==null) 4 | return head; 5 | if(head.next==null) 6 | return head; 7 | if(k==0) 8 | return head; 9 | LinkedListNode h1=head,h2,t1=head; 10 | int count=1; 11 | while(count secondHead=kReverse(h2,k); 23 | ans.tail.next=secondHead; 24 | return ans.head; 25 | 26 | } 27 | private static DoubleNode reversePart(LinkedListNode head) 28 | { 29 | if(head==null || head.next==null) 30 | { DoubleNode ans=new DoubleNode(); 31 | ans.head=head; 32 | ans.tail=head; 33 | return ans;} 34 | 35 | DoubleNode ans=reversePart(head.next); 36 | ans.tail.next=head; 37 | head.next=null; 38 | ans.tail=ans.tail.next; 39 | return ans; 40 | } 41 | 42 | } 43 | class DoubleNode{ 44 | LinkedListNode head; 45 | LinkedListNode tail;} 46 | 47 | 48 | -------------------------------------------------------------------------------- /DP-2:Maximum Square Matrix With All Zeros: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static int findMaxSquareWithAllZeros(int[][] input){ 4 | int arr [][] = new int[input.length][input[0].length]; 5 | 6 | for(int i=0;i maximum){ 38 | maximum = arr[i][j]; 39 | } 40 | } 41 | } 42 | 43 | return maximum; 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Graphs: Has Path: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.*; 3 | public class Solution { 4 | 5 | public static void main(String[] args) { 6 | Scanner s = new Scanner(System.in); 7 | int V = s.nextInt(); 8 | int E = s.nextInt(); 9 | int edges[][]=new int[V][V]; 10 | for(int i=0;i q=new LinkedList<>(); 26 | q.add(V1); 27 | visited[V1]=true; 28 | while(!q.isEmpty()){ 29 | int n=q.remove(); 30 | for(int i=0;i { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static int lcaInBST(BinaryTreeNode root , int a , int b){ 17 | // Write your code here 18 | 19 | if(root==null) 20 | return -1; 21 | int c=-1; 22 | if(root.data==a || root.data==b) 23 | return root.data; 24 | 25 | else if(aroot.data || a>root.data && broot.data &&b>root.data) 44 | { 45 | c=lcaInBST(root.right,a,b); 46 | } 47 | 48 | if(c!=-1) 49 | return c; 50 | else 51 | return -1; 52 | 53 | 54 | } 55 | } 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Graphs:BFS Traversal: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Queue; 3 | import java.util.*; 4 | 5 | public class Solution { 6 | 7 | public static void printHelper(int edges[][], int sv,boolean visited[]){ 8 | Queue q = new LinkedList<>(); 9 | q.add(sv); 10 | visited[sv]=true; 11 | while(q.size()!=0){ 12 | int firstelem = q.remove(); 13 | System.out.print(firstelem+" "); 14 | for(int i=0; i stk=new Stack<>(); 11 | for(int i=0;i bubbleSort(LinkedListNode head ) 5 | { if(head==null || head.next==null) 6 | return head; 7 | //Write your code here 8 | for(int i=0;i prev = null; 10 | LinkedListNode curr = head; 11 | LinkedListNode next = curr.next; 12 | 13 | while(curr.next != null){ 14 | if(curr.data > curr.next.data){ 15 | if(prev == null){ 16 | curr.next = next.next; 17 | next.next = curr; 18 | prev = next; 19 | head = prev; 20 | }else{ 21 | next = curr.next; 22 | curr.next = next.next; 23 | prev.next = next; 24 | next.next = curr; 25 | prev = next; 26 | } 27 | }else{ 28 | prev = curr; 29 | curr = curr.next; 30 | } 31 | } 32 | } 33 | return head; 34 | } 35 | 36 | private static int lengthLL(LinkedListNode head){ 37 | int count = 1; 38 | while(head.next != null){ 39 | head = head.next; 40 | count++; 41 | } 42 | return count; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Binary Search Trees:Find Path in BST: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Solution { 4 | 5 | /* Binary Tree Node class 6 | * 7 | * class BinaryTreeNode { 8 | T data; 9 | BinaryTreeNode left; 10 | BinaryTreeNode right; 11 | 12 | public BinaryTreeNode(T data) { 13 | this.data = data; 14 | } 15 | } 16 | */ 17 | 18 | public static ArrayList findPath(BinaryTreeNode root, int data){ 19 | /* Your class should be named Solution 20 | * Don't write main(). 21 | * Don't read input, it is passed as function argument. 22 | * Return output and don't print it. 23 | * Taking input and printing output is handled automatically. 24 | */ 25 | if(root==null) 26 | return null; 27 | if(root.data==data) 28 | { 29 | ArrayList output=new ArrayList<>(); 30 | output.add(root.data); 31 | return output; 32 | } 33 | if(data output=findPath(root.left,data); 36 | 37 | if(output!=null) 38 | { 39 | output.add(root.data); 40 | return output; 41 | } 42 | } 43 | ArrayList output2; 44 | if(data>root.data) 45 | { 46 | output2=findPath(root.right,data); 47 | 48 | if(output2!=null){ 49 | output2.add(root.data); 50 | return output2;}} 51 | 52 | 53 | return null; 54 | 55 | 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Graphs:Get Path - DFS: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.*; 3 | public class Solution { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | int V = s.nextInt(); 7 | int E = s.nextInt(); 8 | int edges[][]=new int[V][V]; 9 | for(int i=0;i ans=getPathDFS(edges,visited,V1,V2); 19 | if(ans!=null){ 20 | for(int elem:ans) 21 | { 22 | System.out.print(elem+" "); 23 | } 24 | } 25 | } 26 | public static ArrayList getPathDFS(int[][] edges,boolean[] visited,int V1,int V2){ 27 | if(V1==V2) 28 | { 29 | ArrayList ans=new ArrayList<>(); 30 | visited[V1]=true; 31 | ans.add(V1); 32 | return ans; 33 | } 34 | visited[V1]=true; 35 | for(int i=0;i arr=getPathDFS(edges,visited,i,V2); 40 | if(arr!=null) 41 | { 42 | arr.add(V1); 43 | 44 | return arr; 45 | } 46 | } 47 | } 48 | return null; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /DynamicArray: -------------------------------------------------------------------------------- 1 | package classes_and_objects; 2 | public class DynamicArray { 3 | int d[]; 4 | int nextIndex; 5 | DynamicArray(){ 6 | d=new int[5]; 7 | nextIndex=0; 8 | } 9 | public int size() { 10 | return nextIndex; 11 | } 12 | public boolean isEmpty() { 13 | return size()==0; 14 | } 15 | public void add(int i) { 16 | if(nextIndex==d.length) { 17 | restructure(); 18 | } 19 | d[nextIndex]=i; 20 | nextIndex++; 21 | } 22 | private void restructure() { 23 | int temp[]=d; 24 | d=new int[d.length*2]; 25 | for(int i=0;inextIndex) 32 | return; 33 | else if(index=nextIndex){ 41 | //error out 42 | return -1;} 43 | else 44 | return d[index]; 45 | } 46 | 47 | private int removeLast() { 48 | if (size() == 0) { 49 | // error out 50 | return -1; 51 | } 52 | int value = d[nextIndex - 1]; 53 | d[nextIndex - 1] = 0; 54 | nextIndex--; 55 | return value; 56 | } 57 | 58 | 59 | 60 | public static void main(String[] args) { 61 | DynamicArray d=new DynamicArray(); 62 | for(int i=0;i<100;i++) { 63 | d.add(i+10); 64 | } 65 | System.out.println(d.size()); 66 | 67 | d.set(4, 10); 68 | System.out.println(d.get(3)); 69 | System.out.println(d.get(4)); 70 | 71 | while (!d.isEmpty()) { 72 | System.out.println(d.removeLast()); 73 | System.out.println("size = " + d.size()); 74 | } 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /Graphs:All connected components: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Scanner; 3 | import java.util.Queue; 4 | // import java.io.*; 5 | import java.util.*; 6 | public class Solution{ 7 | public static void help(int edges[][],boolean visited[],ArrayList arr,int start){ 8 | visited[start]=true; 9 | arr.add(start); 10 | int n=edges.length; 11 | for(int j=0;j arrans= new ArrayList(); 23 | help(edges,visited,arrans,i); 24 | Collections.sort(arrans); 25 | for(int j=0;j=2) 21 | { 22 | int ch1=input.charAt(0)-'0'; 23 | int ch2=input.charAt(1)-'0'; 24 | int an3=(ch1*10)+ch2; 25 | 26 | if(an3>=10 && an3<=26) 27 | {char firsttwochar=(char)('a'+an3-1); 28 | smallans1=getCode(input.substring(2)); 29 | for(int i=0;i=arr[2*i+1]) 15 | // { 16 | // b=true; 17 | // } 18 | // else{ 19 | 20 | // b=false; 21 | // break; 22 | // } 23 | // } 24 | // else 25 | // break; 26 | // if(2*i+2=arr[2*i+2]){ 28 | // b=true; 29 | // } 30 | // else{ 31 | 32 | // b=false; 33 | // break; 34 | // }} 35 | // else 36 | // break; 37 | // if(b==false){ 38 | // break; 39 | // } 40 | // } 41 | // return b; 42 | // } 43 | // } 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | //or======= 52 | int n=arr.length; 53 | for(int i=0;i map=new HashMap<>(); 6 | for(int i=0;i1){ 21 | for(int j=0;j<(freq*(freq-1))/2;j++){ 22 | System.out.println(input[i]+" "+input[i]); 23 | 24 | } 25 | 26 | } 27 | map.put(input[i],0); 28 | } 29 | } 30 | else{ 31 | for(int i=0;i { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static void nodesAtDistanceK(BinaryTreeNode root, int node, int k) { 17 | // Write your code here 18 | int x = print(root,k,node); 19 | } 20 | 21 | public static int print(BinaryTreeNode root,int k,int elem){ 22 | if(root == null){ 23 | return -1; 24 | } 25 | 26 | if(root.data == elem){ 27 | printAtDepthK(root,k); 28 | return 0; 29 | } 30 | 31 | int ld = print(root.left,k,elem); 32 | 33 | int rd; 34 | if(ld == -1){ 35 | rd = print(root.right,k,elem); 36 | if(rd == -1){ 37 | return -1; 38 | }else if(rd + 1 == k){ 39 | System.out.println(root.data+" "); 40 | return k; 41 | }else{ 42 | printAtDepthK(root.left,k-rd-2); 43 | return rd+1; 44 | } 45 | }else if(ld + 1 == k){ 46 | System.out.println(root.data+" "); 47 | return k; 48 | }else{ 49 | printAtDepthK(root.right,k-ld-2); 50 | return ld+1; 51 | } 52 | 53 | } 54 | 55 | public static void printAtDepthK(BinaryTreeNode root,int depth){ 56 | if(root == null){ 57 | return; 58 | } 59 | 60 | if(depth == 0 && root != null){ 61 | System.out.println(root.data+" "); 62 | return; 63 | } 64 | 65 | printAtDepthK(root.left,depth-1); 66 | printAtDepthK(root.right,depth-1); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Graphs-2:Dijkstra's Algorithm: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Solution { 3 | public static void main(String[] args) { 4 | Scanner s = new Scanner(System.in); 5 | int V = s.nextInt(); 6 | int E = s.nextInt(); 7 | int[][] matrix=new int[V][V]; 8 | for(int i=0;idistance[mindistancevertex]+matrix[mindistancevertex][j]) 32 | { 33 | distance[j]=distance[mindistancevertex]+matrix[mindistancevertex][j]; 34 | } 35 | } 36 | } 37 | 38 | } 39 | 40 | for(int i=0;i0){ 22 | if(arr[parentindex]>arr[childindex]) 23 | { 24 | int temp=arr[parentindex]; 25 | arr[parentindex]=arr[childindex]; 26 | arr[childindex]=temp; 27 | childindex=parentindex; 28 | parentindex=(childindex-1)/2; 29 | 30 | } 31 | else 32 | return; 33 | } 34 | } 35 | 36 | public static int removeMin(int arr[],int heapsize){ 37 | int temp=arr[0]; 38 | arr[0]=arr[heapsize-1]; 39 | heapsize--; 40 | int lchild=1; 41 | int rchild=2; 42 | int parentindex=0; 43 | int minindex=parentindex; 44 | while(lchild { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | /* LinkedList Node Class 17 | * 18 | * 19 | class LinkedListNode { 20 | T data; 21 | LinkedListNode next; 22 | 23 | public LinkedListNode(T data) { 24 | this.data = data; 25 | } 26 | } 27 | */ 28 | 29 | public static LinkedListNode BSTToSortedLL(BinaryTreeNode root){ 30 | /* Your class should be named Solution 31 | * Don't write main(). 32 | * Don't read input, it is passed as function argument. 33 | * Return output and don't print it. 34 | * Taking input and printing output is handled automatically. 35 | */ 36 | Pair ans=helper(root); 37 | return ans.head;} 38 | public static Pair helper(BinaryTreeNode root){ 39 | if(root==null) 40 | { 41 | Pair output=new Pair(); 42 | output.head=null; 43 | output.tail=null; 44 | return output; 45 | } 46 | Pair lefttree=helper(root.left); 47 | LinkedListNode newNode=new LinkedListNode<>(root.data); 48 | Pair righttree=helper(root.right); 49 | Pair output=new Pair(); 50 | if(lefttree.head!=null) 51 | { 52 | output.head=lefttree.head; 53 | lefttree.tail.next=newNode; 54 | 55 | } 56 | else { 57 | output.head=newNode; 58 | } 59 | newNode.next=righttree.head; 60 | if(righttree.head==null) 61 | { 62 | output.tail=newNode; 63 | 64 | } 65 | else{ 66 | output.tail=righttree.tail; 67 | } 68 | return output; 69 | }} 70 | class Pair{ 71 | LinkedListNode head; 72 | LinkedListNode tail; 73 | } 74 | 75 | 76 | -------------------------------------------------------------------------------- /Tries and Huffman Coding:Search word in Trie: -------------------------------------------------------------------------------- 1 | class TrieNode{ 2 | 3 | char data; 4 | boolean isTerminating; 5 | TrieNode children[]; 6 | int childCount; 7 | 8 | public TrieNode(char data) { 9 | this.data = data; 10 | isTerminating = false; 11 | children = new TrieNode[26]; 12 | childCount = 0; 13 | } 14 | } 15 | 16 | 17 | public class Trie { 18 | 19 | private TrieNode root; 20 | public int count; 21 | public Trie() { 22 | root = new TrieNode('\0'); 23 | count = 0; 24 | } 25 | 26 | private boolean add(TrieNode root, String word){ 27 | if(word.length() == 0){ 28 | if (!root.isTerminating) { 29 | root.isTerminating = true; 30 | return true; 31 | } else { 32 | return false; 33 | } 34 | } 35 | int childIndex = word.charAt(0) - 'a'; 36 | TrieNode child = root.children[childIndex]; 37 | if(child == null){ 38 | child = new TrieNode(word.charAt(0)); 39 | root.children[childIndex] = child; 40 | root.childCount++; 41 | } 42 | return add(child, word.substring(1)); 43 | 44 | } 45 | 46 | public void add(String word){ 47 | if (add(root, word)) { 48 | this.count++; 49 | } 50 | } 51 | 52 | public boolean search(String word){ 53 | return search(root,word); 54 | } 55 | private boolean search(TrieNode root,String word){ 56 | if(word.length()==0) 57 | { 58 | if(root.isTerminating==true) 59 | return true; 60 | else 61 | return false; 62 | } 63 | boolean ans=false; 64 | int childIndex=word.charAt(0)-'a'; 65 | TrieNode child=root.children[childIndex]; 66 | // if(child==null) 67 | // return false; 68 | if(child!=null) 69 | ans=search(child,word.substring(1)); 70 | return ans; 71 | 72 | 73 | } 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /Recursion 2:Quick Sort Code: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static void quickSort(int[] input) { 3 | quickSort(input,0,input.length-1); 4 | 5 | } 6 | public static void quickSort(int[] input,int sI,int eI){ 7 | //base case 8 | if(sI>=eI) 9 | return; 10 | 11 | int pivotPos=partition(input,sI,eI); 12 | quickSort(input,sI,pivotPos-1); 13 | quickSort(input,pivotPos+1,eI); 14 | } 15 | public static int partition(int input[],int sI,int eI) 16 | { 17 | int pivot=input[sI]; 18 | int count=0; 19 | for(int i=sI+1;i<=eI;i++) 20 | { 21 | if(input[i]<=pivot) 22 | count++; 23 | } 24 | int pivotPos=sI+count; 25 | int temp=input[sI]; 26 | input[sI]=input[pivotPos]; 27 | input[pivotPos]=temp; 28 | int i=sI; 29 | int j=eI; 30 | while(ipivotPos) 31 | { 32 | if(input[i]<=input[pivotPos]) 33 | i++; 34 | else if(input[j]>input[pivotPos]) 35 | j--; 36 | else 37 | { 38 | int temp_=input[i]; 39 | input[i]=input[j]; 40 | input[j]=temp_; 41 | i++;j--; 42 | 43 | } 44 | } 45 | return pivotPos; 46 | } 47 | 48 | 49 | 50 | 51 | } 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /Time and Space Complexity Analysis:Triplet Sum: -------------------------------------------------------------------------------- 1 | public class TripletSum { 2 | public static void FindTriplet(int[] arr, int x){ 3 | for(int i=0;i ans=getPathBFS(edges,visited,V1,V2); 20 | if(ans!=null){ 21 | for(int elem:ans) 22 | { 23 | System.out.print(elem+" "); 24 | } 25 | } 26 | } 27 | public static ArrayList getPathBFS(int[][] edges,boolean[] visited,int V1,int V2){ 28 | if(V1==V2) 29 | { 30 | ArrayList ans=new ArrayList(); 31 | ans.add(V1); 32 | visited[V1]=true; 33 | return ans; 34 | } 35 | Queue q=new LinkedList(); 36 | HashMap h=new HashMap<>(); 37 | ArrayList ans=new ArrayList<>(); 38 | q.add(V1); 39 | visited[V1]=true; 40 | while(!q.isEmpty() ){ 41 | int first=q.remove(); 42 | for(int i=0;i mergeSort(LinkedListNode head) { 5 | if(head==null) 6 | return head; 7 | if(head.next==null) 8 | return head; 9 | LinkedListNode midNode=findmid(head); 10 | LinkedListNode h2=midNode.next; 11 | midNode.next=null; 12 | LinkedListNode part1=mergeSort(head); 13 | LinkedListNode part2=mergeSort(h2); 14 | LinkedListNode mergedList=mergeTwoList(part1,part2); 15 | return mergedList; 16 | 17 | } 18 | private static LinkedListNode findmid(LinkedListNode head) 19 | { 20 | if(head==null) 21 | return head; 22 | LinkedListNode slow=head,fast=head; 23 | while(fast.next!=null && fast.next.next!=null){ 24 | slow=slow.next; 25 | fast=fast.next.next; 26 | } 27 | return slow; 28 | } 29 | public static LinkedListNode mergeTwoList(LinkedListNode head1, LinkedListNode head2) { 30 | if(head1==null) 31 | return head2; 32 | if(head2==null) 33 | return head1; 34 | LinkedListNode t1=head1,t2=head2,tail=null,head=null; 35 | if(t1.data<=t2.data) 36 | { 37 | head=t1; 38 | tail=t1; 39 | t1=t1.next; 40 | } 41 | else 42 | { 43 | head=t2; 44 | tail=t2; 45 | t2=t2.next; 46 | } 47 | while(t1!=null &&t2!=null) 48 | { 49 | if(t1.data<=t2.data) 50 | { 51 | tail.next=t1; 52 | tail=t1; 53 | t1=t1.next; 54 | } 55 | else 56 | { 57 | tail.next=t2; 58 | tail=tail.next; 59 | t2=t2.next; 60 | } 61 | } 62 | if(t1==null) 63 | tail.next=t2; 64 | if(t2==null) 65 | tail.next=t1; 66 | return head; 67 | 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Hashmaps:Longest consecutive Sequence: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.ArrayList; 6 | public class Solution { 7 | public static ArrayList longestConsecutiveIncreasingSequence(int[] arr) { 8 | HashMap map = new HashMap<>(); 9 | ArrayList output = new ArrayList<>(); 10 | 11 | for(int i=0;i maxlength){ 37 | maxlength = length; 38 | start = starttemp; 39 | }else if(length == maxlength){ 40 | maxlength = length; 41 | //start = 10 starttemp = 4 42 | for(int j=0;j sortEvenOdd(LinkedListNode head) 4 | { 5 | LinkedListNode eh=null,et=null,oh=null,ot=null; 6 | while(head!=null){ 7 | if(head.data%2==0){ 8 | if(eh==null && et==null) 9 | { 10 | eh=head; 11 | et=head; 12 | 13 | } 14 | else{ 15 | et.next=head; 16 | et=head; 17 | 18 | } 19 | head=head.next; 20 | } 21 | else{ 22 | if(oh==null && ot==null) 23 | { 24 | oh=head; 25 | ot=head; 26 | } 27 | else{ 28 | ot.next=head; 29 | ot=head; 30 | } 31 | head=head.next; 32 | } 33 | } 34 | if(oh!=null){ 35 | ot.next=eh; 36 | } 37 | else{ 38 | return eh; 39 | } 40 | if(eh!=null){ 41 | et.next=null; 42 | } 43 | return oh; 44 | } 45 | } 46 | //or 47 | public class Solution 48 | { 49 | public static LinkedListNode sortEvenOdd(LinkedListNode head) 50 | { if(head==null) 51 | return head; 52 | if(head.next==null) 53 | return head; 54 | 55 | LinkedListNode smallHead=sortEvenOdd(head.next); 56 | LinkedListNode temp=smallHead; 57 | if(head.data%2==0) 58 | { if(temp.data%2==0) 59 | {head.next=temp; 60 | return head;} 61 | while(temp.next!=null && temp.next.data%2!=0) 62 | { 63 | temp=temp.next; 64 | } 65 | // if(temp.next==null){ 66 | // head.next=temp; 67 | // return head;} 68 | 69 | LinkedListNode t1=temp.next; 70 | temp.next=head; 71 | head.next=t1; 72 | return smallHead;} 73 | else 74 | { 75 | head.next=smallHead; 76 | 77 | return head;} 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Tries and Huffman Coding:Palindrome Pair: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.*; 3 | import java.lang.*; 4 | class TrieNode{ 5 | 6 | char data; 7 | boolean isTerminating; 8 | TrieNode children[]; 9 | int childCount; 10 | 11 | public TrieNode(char data) { 12 | this.data = data; 13 | isTerminating = false; 14 | children = new TrieNode[26]; 15 | childCount = 0; 16 | } 17 | } 18 | 19 | public class Trie { 20 | 21 | private TrieNode root; 22 | public int count; 23 | public Trie() { 24 | root = new TrieNode('\0'); 25 | } 26 | private void add(TrieNode root, String word){ 27 | if(word.length() == 0){ 28 | if (!root.isTerminating) { 29 | root.isTerminating = true; 30 | return; 31 | } 32 | else 33 | return; 34 | } 35 | int childIndex = word.charAt(0) - 'a'; 36 | TrieNode child = root.children[childIndex]; 37 | if(child == null){ 38 | child = new TrieNode(word.charAt(0)); 39 | root.children[childIndex] = child; 40 | root.childCount++; 41 | } 42 | add(child, word.substring(1)); 43 | } 44 | 45 | public void add(String word) 46 | { 47 | add(root,word); 48 | } 49 | 50 | public boolean findPalindromePair(ArrayList vect) 51 | { 52 | ArrayList s=new ArrayList<>(); 53 | for(int i=0;imaxWeight) 25 | // { 26 | // storage[i][maxWeight]=knapsack(weight,value,maxWeight,n-1,storage,i+1); 27 | // return storage[i][maxWeight]; 28 | // } 29 | // else{ 30 | // int op1=value[i]+knapsack(weight,value,maxWeight-weight[i],n-1,storage,i+1); 31 | // int op2=knapsack(weight,value,maxWeight,n-1,storage,i+1); 32 | // storage[i][maxWeight]=Math.max(op1,op2); 33 | // return storage[i][maxWeight]; 34 | // } 35 | 36 | // } 37 | 38 | // } 39 | 40 | 41 | /* Your class should be named Solution. 42 | * Don't write main() function. 43 | * Don't read input, it is passed as function argument. 44 | * Return output and don't print it. 45 | * Taking input and printing output is handled automatically. 46 | */ 47 | int storagePrev[] = new int[maxWeight+1]; 48 | int storageCurrent[] = new int [maxWeight+1]; 49 | for(int i=1;iw){ 52 | storageCurrent[w] = storagePrev[w]; 53 | } 54 | else { 55 | storageCurrent[w]= Math.max(storagePrev[w - weight[i-1]]+ value[i-1],storagePrev[w]); 56 | } 57 | } 58 | storagePrev = storageCurrent ; 59 | storageCurrent = new int[maxWeight+1]; 60 | 61 | } 62 | return storagePrev[maxWeight]; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /Graphs-2: Kruskal's Algorithm: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Arrays; 3 | class Edge implements Comparable{ 4 | int source; 5 | int destination; 6 | int weight; 7 | public int compareTo(Edge o){ 8 | return this.weight-o.weight; 9 | // if(this.weight>o.weight) 10 | // return 1; 11 | // else if(this.weight input, String pattern) { 45 | // for (int i = 0; i < input.size(); i++) { 46 | // String word = input.get(i); 47 | // for (int j = 0; j < word.length(); j++) { 48 | // add(word.substring(j)); 49 | // } 50 | // } 51 | // return search(pattern); 52 | // } 53 | public boolean patternMatching(ArrayList input, String pattern) { 54 | for (int i = 0; i < input.size(); i++) { 55 | String word = input.get(i); 56 | for (int j = 0; j < word.length(); j++) { 57 | add(word.substring(j)); }} 58 | // for(int i=0;i { 6 | // T data; 7 | // BinaryTreeNode left; 8 | // BinaryTreeNode right; 9 | 10 | // public BinaryTreeNode(T data) { 11 | // this.data = data; 12 | // } 13 | // } 14 | // */ 15 | 16 | public static void rootToLeafPathsSumToK(BinaryTreeNode root, int k) { 17 | // Write your code here 18 | helper(root,k,""); 19 | } 20 | private static void helper(BinaryTreeNode root,int k,String s){ 21 | if(root==null) 22 | return; 23 | if(root.left==null && root.right==null && root.data==k) 24 | { 25 | System.out.println(s+root.data); 26 | return; 27 | } 28 | s=s+root.data+" "; 29 | 30 | helper(root.left,k-root.data,s); 31 | helper(root.right,k-root.data,s); 32 | 33 | } 34 | } 35 | // public class Solution { 36 | 37 | // /* Binary Tree Node class 38 | // * 39 | // * class BinaryTreeNode { 40 | // T data; 41 | // BinaryTreeNode left; 42 | // BinaryTreeNode right; 43 | 44 | // public BinaryTreeNode(T data) { 45 | // this.data = data; 46 | // } 47 | // } 48 | // */ 49 | // public static void rootToLeafPathsSumToK(BinaryTreeNode root, int k,String ans) { 50 | // if(k==root.data){ 51 | // if(root.right==null&&root.left==null){ 52 | // System.out.println(ans+" "+root.data); 53 | // return; 54 | // }else{ 55 | // return; 56 | // } 57 | // } 58 | 59 | // if(root.left!=null){ 60 | // if(ans=="") 61 | // rootToLeafPathsSumToK(root.left ,k-root.data,ans+root.data); 62 | // else{ 63 | // rootToLeafPathsSumToK(root.left ,k-root.data,ans+" "+root.data); 64 | // } 65 | // } 66 | // if(root.right!=null){ 67 | // if(ans=="") 68 | // rootToLeafPathsSumToK(root.right ,k-root.data,ans+root.data); 69 | // else{ 70 | // rootToLeafPathsSumToK(root.right ,k-root.data,ans+" "+root.data); 71 | // } 72 | // } 73 | // } 74 | // public static void rootToLeafPathsSumToK(BinaryTreeNode root, int k) { 75 | // rootToLeafPathsSumToK(root,k,""); 76 | // } 77 | // } 78 | -------------------------------------------------------------------------------- /OOPS-4:Othello Move Function: -------------------------------------------------------------------------------- 1 | /******************* 2 | * Main function that we are using internally - 3 | 4 | final static int player1Symbol = 1; 5 | final static int player2Symbol = 2; 6 | 7 | public static void main(String[] args) { 8 | OthelloBoard b = new OthelloBoard(); 9 | int n = s.nextInt(); 10 | boolean p1Turn = true; 11 | while(n > 0) { 12 | int x = s.nextInt(); 13 | int y = s.nextInt(); 14 | boolean ans = false; 15 | if(p1Turn) { 16 | ans = b.move(player1Symbol, x, y); 17 | } 18 | else { 19 | ans = b.move(player2Symbol, x, y); 20 | } 21 | if(ans) { 22 | b.print(); 23 | p1Turn = !p1Turn; 24 | n--; 25 | } 26 | else { 27 | System.out.println(ans); 28 | } 29 | } 30 | } 31 | *****************/ 32 | public class OthelloBoard { 33 | 34 | private int board[][]; 35 | final static int player1Symbol = 1; 36 | final static int player2Symbol = 2; 37 | 38 | public OthelloBoard() { 39 | board = new int[8][8]; 40 | board[3][3] = player1Symbol; 41 | board[3][4] = player2Symbol; 42 | board[4][3] = player2Symbol; 43 | board[4][4] = player1Symbol; 44 | } 45 | 46 | public void print() { 47 | for(int i = 0; i < 8; i++) { 48 | for(int j = 0; j < 8; j++) { 49 | System.out.print(board[i][j] + " "); 50 | } 51 | System.out.println(); 52 | } 53 | } 54 | int[] xDir={-1,-1,0,1,1,1,0,-1}; 55 | int[] yDir={0,1,1,1,0,-1,-1,-1}; 56 | 57 | public boolean move(int symbol, int x, int y){ 58 | if(x < 0 || x >= 8 || y < 0 || y >= 8 || board[x][y] != 0){ 59 | return false; 60 | } 61 | boolean movePossible = false; 62 | for(int i = 0; i < xDir.length; i++){ 63 | int xStep = xDir[i]; 64 | int yStep = yDir[i]; 65 | int currentX = x + xStep; 66 | int currentY = y + yStep; 67 | int count = 0; // count of opponent's pieces encountered 68 | while(currentX >= 0 && currentX < 8 && currentY >= 0 && currentY < 8){ 69 | // Empty cell 70 | if(board[currentX][currentY] == 0){ 71 | break; 72 | }else if(board[currentX][currentY] != symbol){ 73 | currentX += xStep; 74 | currentY += yStep; 75 | count++; 76 | }else{ 77 | // conversion is possible 78 | if(count > 0){ 79 | movePossible = true; 80 | int convertX = currentX - xStep; 81 | int convertY = currentY - yStep; 82 | while(convertX != x || convertY != y){ 83 | board[convertX][convertY] = symbol; 84 | convertX = convertX - xStep; 85 | convertY = convertY - yStep; 86 | } 87 | } 88 | break; 89 | } 90 | } 91 | } 92 | if(movePossible){ 93 | board[x][y] =symbol; 94 | } 95 | return movePossible; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Tries and Huffman Coding:Auto complete: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TrieNode{ 3 | char data; 4 | boolean isTerminating; 5 | TrieNode children[]; 6 | int childCount; 7 | 8 | public TrieNode(char data) { 9 | this.data = data; 10 | isTerminating = false; 11 | children = new TrieNode[26]; 12 | childCount = 0; 13 | } 14 | } 15 | 16 | public class Trie { 17 | private TrieNode root; 18 | 19 | public Trie() { 20 | root = new TrieNode('\0'); 21 | } 22 | 23 | private void add(TrieNode root, String word){ 24 | if(word.length() == 0){ 25 | root.isTerminating = true; 26 | return; 27 | } 28 | int childIndex = word.charAt(0) - 'a'; 29 | TrieNode child = root.children[childIndex]; 30 | if(child == null){ 31 | child = new TrieNode(word.charAt(0)); 32 | root.children[childIndex] = child; 33 | root.childCount++; 34 | } 35 | add(child, word.substring(1)); 36 | } 37 | 38 | public void add(String word){ 39 | add(root, word); 40 | } 41 | 42 | public TrieNode findword(TrieNode root, String word) { 43 | if(word.length() == 0){ 44 | return root; 45 | } 46 | int childIndex = word.charAt(0) - 'a'; 47 | TrieNode child = root.children[childIndex]; 48 | if(child == null){ 49 | return null; 50 | } 51 | return findword(child, word.substring(1)); 52 | } 53 | 54 | public void allwords(TrieNode root,String word,String output){ 55 | if(root.childCount == 0) { 56 | if(output.length() > 0) { 57 | System.out.println(word + output); 58 | } 59 | return; 60 | } 61 | if(root.isTerminating == true) { 62 | System.out.println(word + output); 63 | } 64 | 65 | for(int i = 0; i < root.children.length; i++) { 66 | if(root.children[i] != null) { 67 | String ans = output + root.children[i].data; 68 | allwords(root.children[i],word,ans); 69 | } 70 | } 71 | } 72 | public void autoComplete(ArrayList input, String word){ 73 | // for(String w : input) { 74 | // add(w); 75 | // } 76 | int i=0; 77 | while(i { 8 | T data; 9 | BinaryTreeNode left; 10 | BinaryTreeNode right; 11 | 12 | public BinaryTreeNode(T data) { 13 | this.data = data; 14 | } 15 | } 16 | */ 17 | 18 | 19 | // public static void printNodesSumToS(BinaryTreeNode root, int s) { 20 | // printNodesSumToS(root ,root ,s); 21 | 22 | // } 23 | 24 | // public static void printNodesSumToS(BinaryTreeNode temp1 ,BinaryTreeNode temp2 ,int s){ 25 | // if(temp1 == null){ 26 | // return; 27 | // } 28 | // if(temp2 == null){ 29 | // return; 30 | // } 31 | 32 | // printNodesSumToS(temp1.left, temp2 ,s); 33 | // printNodesSumToS(temp1, temp2.right ,s); 34 | 35 | // int sum = temp1.data + temp2.data; 36 | 37 | // if(sum == s){ 38 | // System.out.println(temp1.data+" "+temp2.data); 39 | // printNodesSumToS(temp1.right ,temp2.left ,s); 40 | // //printNodesSumToS(temp2.left); 41 | // }else if(sum > s){ 42 | // printNodesSumToS(temp1 ,temp2.left ,s); 43 | // }else{ 44 | // printNodesSumToS(temp1.right ,temp2 ,s); 45 | // } 46 | 47 | 48 | // } 49 | 50 | 51 | public static void printNodesSumToS(BinaryTreeNode root, int sum) { 52 | 53 | Queue> pendingNodes = new Queue<>(); 54 | ArrayList list = new ArrayList<>(); 55 | pendingNodes.enqueue(root); 56 | while (!pendingNodes.isEmpty()) { 57 | BinaryTreeNode frontNode = null; 58 | int counter = pendingNodes.size(); 59 | for (int i = 0; i < counter; i++) { 60 | try { 61 | frontNode = pendingNodes.dequeue(); 62 | } catch (QueueEmptyException e) { 63 | e.printStackTrace(); 64 | } 65 | list.add(frontNode.data); 66 | if (frontNode.left != null) { 67 | pendingNodes.enqueue(frontNode.left); 68 | } 69 | if (frontNode.right != null) { 70 | pendingNodes.enqueue(frontNode.right); 71 | } 72 | } 73 | } 74 | for (int i = 0; i < list.size(); i++) { 75 | for (int j = 0; j != i && j < list.size(); j++) { 76 | if (list.get(i) + list.get(j) == sum) { 77 | if (list.get(i) < list.get(j)) { 78 | System.out.println(list.get(i) + " " + list.get(j)); 79 | } else { 80 | System.out.println(list.get(j) + " " + list.get(i)); 81 | } 82 | } 83 | } 84 | } 85 | 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /Priority Queues:Running median: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | 4 | public static void runningMedian(int arr[]) { 5 | PriorityQueue maxpq=new PriorityQueue<>(Collections.reverseOrder()); 6 | PriorityQueue minpq=new PriorityQueue<>(); 7 | int i=0; 8 | while(i1){ 42 | minpq.add(maxpq.remove()); 43 | max=maxpq.peek(); 44 | min=minpq.peek(); 45 | System.out.println((max+min)/2); 46 | }//same 47 | else if(minpq.size()-maxpq.size()>1){ 48 | maxpq.add(minpq.remove()); 49 | max=maxpq.peek(); 50 | min=minpq.peek(); 51 | System.out.println((max+min)/2); 52 | } // if difference is less than two mwans one 53 | else if(minpq.size()>maxpq.size()){ 54 | System.out.println(minpq.peek()); 55 | } 56 | else if(minpq.size()=e||s==e-1){ 4 | // return 0; 5 | // } 6 | // int min=Integer.MAX_VALUE; 7 | // for(int k=s+1;k<=e-1;k++) 8 | // { 9 | // int count=help(p,s,k)+help(p,k,e)+(p[s]*p[k]*p[e]); 10 | // if(countj) 59 | // dp[i][j]=0; 60 | // if(i==j-1) 61 | // dp[i][j]=0; 62 | // } 63 | // } 64 | // for(int i=0;i<=p.length;i++){ 65 | // for(int j=0;j<=p.length;j++){ 66 | // int min=Integer.MAX_VALUE; 67 | // if(dp[i][j]==0) 68 | // continue; 69 | // else{ 70 | // for(int k=i+1;k<=j-1;k++) 71 | // { 72 | // int op=dp[i][k]+dp[k][j]+(p[i]*p[k]*p[j]); 73 | // if(op=m || j>=n) 13 | // return Integer.MAX_VALUE; 14 | // int x=minCostPath( input, i, j+1); 15 | // int y=minCostPath( input, i+1, j); 16 | // int z=minCostPath( input, i+1, j+1); 17 | // return input[i][j]+Math.min(Math.min(x,y),z); 18 | 19 | 20 | // } 21 | // } 22 | 23 | 24 | 25 | //memoization/////// 26 | // public class Solution { 27 | 28 | // public static int minCostPath(int input[][]) { 29 | // int output[][]=new int[input.length][input[0].length]; 30 | // for(int i=0;i=m || j>=n) 48 | // { 49 | // return Integer.MAX_VALUE; 50 | // } 51 | // if(output[i][j]!=-1) 52 | // return output[i][j]; 53 | // int x=helper( output, i, j+1,input); 54 | // int y=helper( output, i+1, j,input); 55 | // int z=helper( output, i+1, j+1,input); 56 | // output[i][j]= input[i][j]+Math.min(Math.min(x,y),z); 57 | 58 | // return output[i][j]; 59 | 60 | 61 | // } 62 | // } 63 | 64 | ////////////////dp//////////////// 65 | public class Solution 66 | { 67 | public static int minCostPath(int input[][]) 68 | { 69 | int m=input.length; 70 | int n=input[0].length; 71 | int storage[][]=new int[m][n]; 72 | storage[m-1][n-1]=input[m-1][n-1]; 73 | for(int i=m-2;i>=0;i--) 74 | { 75 | storage[i][n-1]=input[i][n-1]+storage[i+1][n-1]; 76 | } 77 | for(int j=n-2;j>=0;j--) 78 | { 79 | storage[m-1][j]= storage[m-1][j+1]+input[m-1][j]; 80 | } 81 | for(int i=m-2;i>=0;i--) 82 | { 83 | for(int j=n-2;j>=0;j--) 84 | { 85 | storage[i][j]=input[i][j]+Math.min(storage[i+1][j+1],Math.min(storage[i][j+1],storage[i+1][j])); 86 | } 87 | } 88 | return storage[0][0]; 89 | 90 | 91 | 92 | 93 | 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /Priority Queues:Max Priority Queue: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | /************* 3 | * Following is the main function for your reference which we are using internally. 4 | 5 | public static void main(String[] args) { 6 | PriorityQueue pq = new PriorityQueue(); 7 | int choice = s.nextInt(); 8 | while(choice != -1) { 9 | switch(choice) { 10 | case 1 : // insert 11 | int element = s.nextInt(); 12 | pq.insert(element); 13 | break; 14 | case 2 : // getMax 15 | System.out.println(pq.getMax()); 16 | break; 17 | case 3 : // removeMax 18 | System.out.println(pq.removeMax()); 19 | break; 20 | case 4 : // size 21 | System.out.println(pq.getSize()); 22 | break; 23 | case 5 : // isEmpty 24 | System.out.println(pq.isEmpty()); 25 | default : 26 | return; 27 | } 28 | choice = s.nextInt(); 29 | } 30 | } 31 | ************/ 32 | 33 | public class PriorityQueue { 34 | ArrayList heap; 35 | public PriorityQueue(){ 36 | heap=new ArrayList<>(); 37 | } 38 | int getSize(){ 39 | return heap.size(); 40 | } 41 | boolean isEmpty(){ 42 | return heap.size()==0; 43 | } 44 | int getMax(){ 45 | if(isEmpty()) 46 | return Integer.MIN_VALUE; 47 | return heap.get(0); 48 | } 49 | void insert(int element){ 50 | heap.add(element); 51 | int childindex=heap.size()-1; 52 | int parentindex=(childindex-1)/2; 53 | //upheapify------ 54 | while(childindex>0){ 55 | if(heap.get(childindex)>heap.get(parentindex)) 56 | { 57 | int temp=heap.get(parentindex); 58 | heap.set(parentindex,heap.get(childindex)); 59 | heap.set(childindex,temp); 60 | childindex=parentindex; 61 | parentindex=(childindex-1)/2; 62 | } 63 | else 64 | return; 65 | } 66 | } 67 | int removeMax(){ 68 | if(isEmpty()) 69 | return Integer.MIN_VALUE; 70 | int lchildindex=1; 71 | int rchildindex=2; 72 | int parentindex=0; 73 | int maxindex=parentindex; 74 | int temp=heap.get(0); 75 | heap.set(0,heap.get(heap.size()-1)); 76 | heap.remove(heap.size()-1); 77 | while(lchildindexheap.get(parentindex)) 79 | maxindex=lchildindex; 80 | if(rchildindexheap.get(maxindex)) 81 | maxindex=rchildindex; 82 | if(maxindex==parentindex) 83 | break; 84 | else{ 85 | int temp1=heap.get(parentindex); 86 | heap.set(parentindex,heap.get(maxindex)); 87 | heap.set(maxindex,temp1); 88 | parentindex=maxindex; 89 | lchildindex=2*parentindex +1; 90 | rchildindex=2*parentindex +2; 91 | 92 | } 93 | } 94 | return temp; 95 | } 96 | 97 | 98 | } 99 | -------------------------------------------------------------------------------- /Tries and Huffman Coding:Count Words in Trie: -------------------------------------------------------------------------------- 1 | /*************8 2 | * Main function - 3 | 4 | public static void main(String[] args) { 5 | Trie t = new Trie(); 6 | int choice = s.nextInt(); 7 | 8 | while(choice != -1) { 9 | String word; 10 | switch(choice) { 11 | case 1 : // insert 12 | word = s.next(); 13 | t.add(word); 14 | break; 15 | case 2 : // search 16 | word = s.next(); 17 | System.out.println(t.search(word)); 18 | break; 19 | case 3 : 20 | word = s.next(); 21 | t.remove(word); 22 | break; 23 | case 4 : 24 | System.out.println(t.countWords()); 25 | break; 26 | default : 27 | return; 28 | } 29 | choice = s.nextInt(); 30 | } 31 | } 32 | *******************/ 33 | 34 | class TrieNode{ 35 | char data; 36 | boolean isTerminating; 37 | TrieNode children[]; 38 | int childCount; 39 | 40 | public TrieNode(char data) { 41 | this.data = data; 42 | isTerminating = false; 43 | children = new TrieNode[26]; 44 | childCount = 0; 45 | } 46 | } 47 | 48 | 49 | public class Trie { 50 | 51 | private TrieNode root; 52 | private int numWords; 53 | 54 | public Trie() { 55 | root = new TrieNode('\0'); 56 | numWords = 0; 57 | } 58 | 59 | public boolean search(String word){ 60 | return search(root, word); 61 | } 62 | 63 | private boolean search(TrieNode root, String word) { 64 | if(word.length() == 0){ 65 | return root.isTerminating; 66 | } 67 | int childIndex = word.charAt(0) - 'a'; 68 | TrieNode child = root.children[childIndex]; 69 | if(child == null){ 70 | return false; 71 | } 72 | return search(child, word.substring(1)); 73 | } 74 | 75 | 76 | public void remove(String word){ 77 | if(remove(root, word)) { 78 | numWords--; 79 | } 80 | } 81 | 82 | 83 | private boolean remove(TrieNode root, String word) { 84 | if(word.length() == 0){ 85 | if(root.isTerminating) { 86 | root.isTerminating = false; 87 | return true; 88 | } 89 | else { 90 | return false; 91 | } 92 | } 93 | int childIndex = word.charAt(0) - 'a'; 94 | TrieNode child = root.children[childIndex]; 95 | if(child == null){ 96 | return false; 97 | } 98 | boolean ans = remove(child, word.substring(1)); 99 | // We can remove child node only if it is non terminating and its number of children are 0 100 | 101 | if(!child.isTerminating && child.childCount == 0){ 102 | root.children[childIndex] = null; 103 | child = null; 104 | root.childCount--; 105 | } 106 | return ans; 107 | } 108 | 109 | private boolean add(TrieNode root, String word){ 110 | if(word.length() == 0){ 111 | if(root.isTerminating) { 112 | return false; 113 | } 114 | else { 115 | root.isTerminating = true; 116 | return true; 117 | } 118 | } 119 | int childIndex = word.charAt(0) - 'a'; 120 | TrieNode child = root.children[childIndex]; 121 | if(child == null){ 122 | child = new TrieNode(word.charAt(0)); 123 | root.children[childIndex] = child; 124 | root.childCount++; 125 | } 126 | return add(child, word.substring(1)); 127 | } 128 | 129 | public void add(String word){ 130 | if(add(root, word)) { 131 | numWords++; 132 | } 133 | } 134 | 135 | public int countWords() { 136 | return numWords; 137 | 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /Binary Search Trees:Check if a Binary Tree is BST: -------------------------------------------------------------------------------- 1 | // import java.util.*; 2 | // import java.lang.Math; 3 | public class Solution { 4 | 5 | // public static boolean isBST(BinaryTreeNode root) { 6 | 7 | 8 | // if(root==null) 9 | // return true; 10 | // if(root.left!=null && root.right!=null){ 11 | // if(root.data>root.left.data && root.data<=root.right.data) 12 | // return true; 13 | // if(root.data<=root.left.data && root.data>root.right.data) 14 | // return false; 15 | // } 16 | // boolean ans1=isBST(root.left); 17 | // boolean ans2=isBST(root.right); 18 | // return (ans1&& ans2); 19 | // } 20 | // } 21 | 22 | 23 | 24 | // true methods-------------------- 25 | // if(root==null) 26 | // return true; 27 | // int max=maximum(root.left); 28 | // int min=minimum(root.right); 29 | // if(root.data<=max || root.data>min) 30 | // return false; 31 | 32 | // boolean ans1=isBST(root.left); 33 | // boolean ans2=isBST(root.right); 34 | // return(ans1&& ans2); 35 | 36 | // } 37 | // public static int maximum(BinaryTreeNode root) 38 | // { 39 | // if(root==null) 40 | // return Integer.MIN_VALUE; 41 | // return Math.max(root.data,Math.max(maximum(root.left),maximum(root.right))); 42 | 43 | 44 | // } 45 | // public static int minimum(BinaryTreeNode root) 46 | // { 47 | // if(root==null) 48 | // return Integer.MAX_VALUE; 49 | // return Math.min(root.data,Math.min(minimum(root.left),minimum(root.right))); 50 | // } 51 | 52 | // } 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | // -----------with less time comp..--------------------- 61 | public static boolean isBST(BinaryTreeNode root) { 62 | Pair> output=isBST2(root); 63 | return output.first; 64 | } 65 | 66 | public static Pair> isBST2(BinaryTreeNode root) 67 | { 68 | if(root==null) 69 | { Pair output1=new Pair<>(Integer.MIN_VALUE,Integer.MAX_VALUE); 70 | Pair> output=new Pair<>(true,output1); 71 | return output; 72 | } 73 | Pair> leftOut=isBST2(root.left); 74 | Pair> rightOut=isBST2(root.right); 75 | int minimum=Math.min(root.data,Math.min(leftOut.second.second,rightOut.second.second)); 76 | int maximum=Math.max(root.data,Math.max(leftOut.second.first,rightOut.second.first)); 77 | boolean isBSTT=root.data>leftOut.second.first 78 | && root.data<=rightOut.second.second 79 | && leftOut.first 80 | && rightOut.first; 81 | Pair output1=new Pair<>(maximum,minimum); 82 | Pair> output=new Pair<>(isBSTT,output1); 83 | return output; 84 | 85 | 86 | 87 | } 88 | } 89 | class Pair { 90 | public T first; 91 | public U second; 92 | public Pair(T first,U second) 93 | { 94 | this.first=first; 95 | this.second=second; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /Priority Queues:Remove Min: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | /***************** 4 | * Main function - 5 | * 6 | public static void main(String[] args) { 7 | PQ pq = new PQ(); 8 | int choice = s.nextInt(); 9 | while(choice != -1) { 10 | switch(choice) { 11 | case 1 : // insert 12 | int element = s.nextInt(); 13 | pq.insert(element); 14 | break; 15 | case 2 : // getMin 16 | try { 17 | System.out.println(pq.getMin()); 18 | } catch (PriorityQueueException e) { 19 | return; 20 | } 21 | break; 22 | case 3 : // removeMin 23 | try { 24 | System.out.println(pq.removeMin()); 25 | } catch (PriorityQueueException e) { 26 | return; 27 | } 28 | break; 29 | case 4 : // size 30 | System.out.println(pq.size()); 31 | break; 32 | case 5 : // isEmpty 33 | System.out.println(pq.isEmpty()); 34 | default : 35 | return; 36 | } 37 | choice = s.nextInt(); 38 | } 39 | } 40 | *******************/ 41 | 42 | class PriorityQueueException extends Exception { 43 | 44 | } 45 | 46 | public class PQ { 47 | 48 | private ArrayList heap; 49 | 50 | public PQ() { 51 | heap = new ArrayList(); 52 | } 53 | 54 | boolean isEmpty(){ 55 | return heap.size() == 0; 56 | } 57 | 58 | int size(){ 59 | return heap.size(); 60 | } 61 | 62 | int getMin() throws PriorityQueueException{ 63 | if(isEmpty()){ 64 | // Throw an exception 65 | throw new PriorityQueueException(); 66 | } 67 | return heap.get(0); 68 | } 69 | 70 | void insert(int element){ 71 | heap.add(element); 72 | int childIndex = heap.size() - 1; 73 | int parentIndex = (childIndex - 1) / 2; 74 | 75 | while(childIndex > 0){ 76 | if(heap.get(childIndex) < heap.get(parentIndex)){ 77 | int temp = heap.get(childIndex); 78 | heap.set(childIndex, heap.get(parentIndex)); 79 | heap.set(parentIndex, temp); 80 | childIndex = parentIndex; 81 | parentIndex = (childIndex - 1) / 2; 82 | }else{ 83 | return; 84 | } 85 | } 86 | } 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | int removeMin() throws PriorityQueueException{ 101 | if(isEmpty()){ 102 | // Throw an exception 103 | throw new PriorityQueueException(); 104 | } 105 | int temp = heap.get(0); 106 | heap.set(0, heap.get(heap.size() - 1)); 107 | heap.remove(heap.size() - 1); 108 | int parentindex = 0; 109 | int minIndex = parentindex; 110 | int leftChildIndex = 1; 111 | int rightChildIndex = 2; 112 | 113 | while(leftChildIndex < heap.size()){ 114 | 115 | if(heap.get(leftChildIndex) < heap.get(minIndex)){ 116 | minIndex = leftChildIndex; 117 | } 118 | if(rightChildIndex < heap.size() && heap.get(rightChildIndex) < heap.get(minIndex)){ 119 | minIndex = rightChildIndex; 120 | } 121 | if(minIndex == parentindex){ 122 | break; 123 | }else{ 124 | int temp1 = heap.get(parentindex); 125 | heap.set(parentindex, heap.get(minIndex)); 126 | heap.set(minIndex, temp1); 127 | parentindex = minIndex; 128 | leftChildIndex = 2 * parentindex + 1; 129 | rightChildIndex = 2 * parentindex + 2; 130 | } 131 | } 132 | return temp; 133 | 134 | } 135 | 136 | } 137 | 138 | -------------------------------------------------------------------------------- /Polynomial class: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Polynomial { 3 | 4 | public int degree[]=new int[200]; 5 | /* This function sets coefficient for a particular degree value, if degree is not there in the polynomial 6 | * then corresponding term(with specified degree and value is added int the polynomial. If the degree 7 | * is already present in the polynomial then previous coefficient is replaced by 8 | * new coefficient value passed as function argument 9 | */ 10 | public void setCoefficient(int degree, int coeff){ 11 | this.degree[degree]=coeff; 12 | 13 | } 14 | 15 | // Prints all the terms(only terms with non zero coefficients are to be printed) in increasing order of degree. 16 | public void print(){ 17 | for(int i=0;i<200;i++) 18 | { 19 | if(degree[i]!=0) 20 | System.out.print(degree[i] + "x" + (i)+ " "); 21 | } 22 | } 23 | 24 | 25 | // Adds two polynomials and returns a new polynomial which has result 26 | public Polynomial add(Polynomial p){ 27 | for(int i=0;i<200;i++) 28 | { 29 | this.degree[i]=this.degree[i] + p.degree[i]; 30 | } 31 | return this; 32 | 33 | } 34 | 35 | // Subtracts two polynomials and returns a new polynomial which has result 36 | public Polynomial subtract(Polynomial p){ 37 | for(int i=0;i<200;i++) 38 | { 39 | this.degree[i]=this.degree[i]-p.degree[i]; 40 | } 41 | return this; 42 | } 43 | 44 | // Multiply two polynomials and returns a new polynomial which has result 45 | public Polynomial multiply(Polynomial p){ 46 | int x[]=new int[200]; 47 | for(int i=0;i<200;i++) 48 | { 49 | for(int j=0;j<200;j++) 50 | { 51 | int deg=(i) + (j); 52 | if(deg<200) 53 | { 54 | x[deg]+=this.degree[i]*p.degree[j]; 55 | } 56 | } 57 | } 58 | for(int i=0;i<200;i++) 59 | this.degree[i]=x[i]; 60 | return this; 61 | } 62 | 63 | 64 | public static void main(String[] args) { 65 | // TODO Auto-generated method stub 66 | Scanner s = new Scanner(System.in); 67 | int n = s.nextInt(); 68 | int degree1[] = new int[n]; 69 | for(int i = 0; i < n; i++){ 70 | degree1[i] = s.nextInt(); 71 | } 72 | int coeff1[] = new int[n]; 73 | for(int i = 0; i < n; i++){ 74 | coeff1[i] = s.nextInt(); 75 | } 76 | Polynomial first = new Polynomial(); 77 | for(int i = 0; i < n; i++){ 78 | first.setCoefficient(degree1[i],coeff1[i]); 79 | } 80 | n = s.nextInt(); 81 | int degree2[] = new int[n]; 82 | for(int i = 0; i < n; i++){ 83 | degree2[i] = s.nextInt(); 84 | } 85 | int coeff2[] = new int[n]; 86 | for(int i = 0; i < n; i++){ 87 | coeff2[i] = s.nextInt(); 88 | } 89 | Polynomial second = new Polynomial(); 90 | for(int i = 0; i < n; i++){ 91 | second.setCoefficient(degree2[i],coeff2[i]); 92 | } 93 | int choice = s.nextInt(); 94 | Polynomial result; 95 | switch(choice){ 96 | // Add 97 | case 1: 98 | result = first.add(second); 99 | result.print(); 100 | break; 101 | // Subtract 102 | case 2 : 103 | result = first.subtract(second); 104 | result.print(); 105 | break; 106 | // Multiply 107 | case 3 : 108 | result = first.multiply(second); 109 | result.print(); 110 | break; 111 | } 112 | 113 | } 114 | 115 | } 116 | 117 | -------------------------------------------------------------------------------- /Binary Search Trees:Pair sum BInary Tree: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class Solution { 3 | 4 | /* Binary Tree Node class 5 | * 6 | * class BinaryTreeNode { 7 | T data; 8 | BinaryTreeNode left; 9 | BinaryTreeNode right; 10 | 11 | public BinaryTreeNode(T data) { 12 | this.data = data; 13 | } 14 | } 15 | */ 16 | 17 | // public static void nodesSumToS(BinaryTreeNode root, int sum) { 18 | // // Write your code here 19 | // // final BinaryTreeNode a =root; 20 | // if(root==null) 21 | // return; 22 | // if(root.data root,int x){ 39 | // /* Your class should be named Solution 40 | // * Don't write main(). 41 | // * Don't read input, it is passed as function argument. 42 | // * Return output and don't print it. 43 | // * Taking input and printing output is handled automatically. 44 | // */ 45 | // if(root==null) 46 | // return false; 47 | // boolean ans=false; 48 | // if(root.data.equals(x)) 49 | // return true; 50 | // ans=isNodePresent(root.left,x); 51 | // if(ans==true) 52 | // return true; 53 | // ans=isNodePresent(root.right,x); 54 | // if (ans==true) 55 | // return true; 56 | // return ans;} 57 | 58 | public static void nodesSumToS(BinaryTreeNode root, int sum) { 59 | if(root==null) 60 | return; 61 | int[] arr=arrayInsertion(root); 62 | Arrays.sort(arr); 63 | int i=0; 64 | int j=arr.length-1; 65 | while(i root){ 78 | 79 | if(root==null){ 80 | int[] arr=new int[0]; 81 | return arr;} 82 | int firstData=root.data; 83 | 84 | int[] jrr= arrayInsertion(root.left); 85 | 86 | int[] krr= arrayInsertion(root.right); 87 | int[] finalArray=new int[1+jrr.length+krr.length]; 88 | int k=0; 89 | finalArray[k]=firstData; 90 | k++; 91 | for(int i=0;i root) 4 | // { 5 | // Pair,Pair> ans=helper(root);// integer=min, integer=max,isBst,height of highest subtree... 6 | // return ans.second.second; 7 | // } 8 | // private static Pair,Pair> helper(BinaryTreeNode root){ 9 | // if(root==null) 10 | // { Pair p1=new Pair<>(Integer.MAX_VALUE,Integer.MIN_VALUE); 11 | // Pair p2=new Pair<>(true,0); 12 | // Pair,Pair> ans=new Pair<>(p1,p2); 13 | // return ans; 14 | // } 15 | // Pair,Pair> l=helper(root.left); 16 | // Pair,Pair> r=helper(root.right); 17 | // Pair,Pair> ans; 18 | // if(l.second.first==true && r.second.first==true){ 19 | // if(root.data>l.first.second && root.data<=r.first.first){ 20 | // Pair p1=new Pair<>(l.first.first,r.first.second); 21 | // Pair p2=new Pair<>(true,1+Math.max(l.second.second,r.second.second)); 22 | // ans=new Pair<>(p1,p2); 23 | // } 24 | // else { 25 | // Pair p1=new Pair(l.first.first,r.first.second); 26 | // Pair p2=new Pair<>(false,Math.max(l.second.second,r.second.second)); 27 | // ans=new Pair<>(p1,p2); 28 | // }} 29 | // // else if(l.second.first==true) 30 | // // { 31 | // // Pair,Pair> ans=new Pair<>(l.first.first,r.first.second,false,Math.max(l.second.second,r.second.second)); 32 | // // } 33 | // // else if(r.second.second==true){ 34 | // // Pair,Pair> ans=new Pair<>(l.first.first,r.first.second,false,Math.max(l.second.second,r.second.second)); 35 | // // } 36 | // else{ 37 | // Pair p1=new Pair(l.first.first,r.first.second); 38 | // Pair p2=new Pair(false,Math.max(l.second.second,r.second.second)); 39 | // ans=new Pair<>(p1,p2); } 40 | // return ans; 41 | 42 | // } 43 | // } 44 | 45 | // class Pair{ 46 | // T first; 47 | // U second; 48 | // public Pair(T first,U second){ 49 | // this.first=first; 50 | // this.second=second; 51 | // } 52 | // } 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | class Pair{ 90 | int min; 91 | int max; 92 | boolean isBST; 93 | int height; 94 | } 95 | 96 | public class Solution { 97 | 98 | /* Binary Tree Node class 99 | * 100 | * class BinaryTreeNode { 101 | T data; 102 | BinaryTreeNode left; 103 | BinaryTreeNode right; 104 | 105 | public BinaryTreeNode(T data) { 106 | this.data = data; 107 | } 108 | } 109 | */ 110 | 111 | public static int largestBSTSubtree(BinaryTreeNode root) { 112 | 113 | Pair ans = largestBSThelper(root); 114 | return ans.height; 115 | } 116 | 117 | 118 | public static Pair largestBSThelper(BinaryTreeNode root){ 119 | if(root == null){ 120 | Pair output = new Pair(); 121 | output.max = Integer.MIN_VALUE; 122 | output.min = Integer.MAX_VALUE; 123 | output.isBST = true; 124 | output.height = 0; 125 | return output; 126 | } 127 | 128 | Pair left = largestBSThelper(root.left); 129 | Pair right = largestBSThelper(root.right); 130 | 131 | Pair output = new Pair(); 132 | 133 | int min = Math.min(root.data,Math.min(left.min,right.min)); 134 | int max = Math.max(root.data,Math.max(left.max,right.max)); 135 | 136 | output.min = min; 137 | output.max = max; 138 | 139 | output.isBST = left.max < root.data && right.min > root.data 140 | && left.isBST && right.isBST; 141 | 142 | if(output.isBST){ 143 | output.height = Math.max(left.height,right.height) + 1; 144 | }else{ 145 | output.height = Math.max(left.height,right.height); 146 | } 147 | 148 | return output; 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /Binary Search Trees:BST Class: -------------------------------------------------------------------------------- 1 | /*************** 2 | * BinaryTreeNode class already given - 3 | * 4 | class BinaryTreeNode { 5 | T data; 6 | BinaryTreeNode left; 7 | BinaryTreeNode right; 8 | 9 | public BinaryTreeNode(T data) { 10 | this.data = data; 11 | } 12 | } 13 | ***************/ 14 | 15 | /************** 16 | * Main function that we are using internally 17 | * 18 | public static void main(String[] args) { 19 | BinarySearchTree bst = new BinarySearchTree(); 20 | int choice, input; 21 | while(true) { 22 | choice = s.nextInt(); 23 | switch(choice) { 24 | case 1 : 25 | input = s.nextInt(); 26 | bst.insertData(input); 27 | break; 28 | case 2 : 29 | input = s.nextInt(); 30 | bst.deleteData(input); 31 | break; 32 | case 3 : 33 | input = s.nextInt(); 34 | System.out.println(bst.search(input)); 35 | break; 36 | default : 37 | bst.printTree(); 38 | return; 39 | } 40 | 41 | } 42 | *******************/ 43 | 44 | public class BinarySearchTree { 45 | private static BinaryTreeNode root; 46 | // ----search 47 | public static boolean search(int data){ 48 | return searchHelper(root,data); 49 | 50 | } 51 | private static boolean searchHelper(BinaryTreeNode root,int data){ 52 | if(root==null) 53 | return false; 54 | if(root.data==data) 55 | return true; 56 | else if(root.data>data) 57 | return searchHelper(root.left,data); 58 | else 59 | return searchHelper(root.right,data); 60 | 61 | } 62 | 63 | // ----insert 64 | public static void insertData(int data){ 65 | root=insertHelper(root,data); 66 | // return ; 67 | } 68 | private static BinaryTreeNode insertHelper(BinaryTreeNode root,int data) 69 | { 70 | if(root==null) 71 | { 72 | BinaryTreeNode node= new BinaryTreeNode<>(data); 73 | return node; 74 | } 75 | if(data>root.data) 76 | { 77 | BinaryTreeNode rightcall=insertHelper(root.right,data); 78 | root.right=rightcall; 79 | } 80 | else if(data leftcall=insertHelper(root.left,data); 83 | root.left=leftcall; 84 | } 85 | 86 | return root; 87 | } 88 | 89 | 90 | 91 | // -----printTree 92 | public static void printTree(){ 93 | printHelper(root); 94 | return; 95 | } 96 | private static void printHelper(BinaryTreeNode root) 97 | { 98 | if(root==null) 99 | return ; 100 | // String s=root.data+":"; 101 | System.out.print(root.data+":"); 102 | if(root.left!=null) 103 | // s=s+"L:"+root.left.data+","; 104 | System.out.print("L:"+root.left.data+","); 105 | if(root.right!=null){ 106 | // s=s+"R:"+root.right.data; 107 | System.out.print("R:"+root.right.data); 108 | } 109 | // System.out.println(s); 110 | System.out.println(); 111 | printHelper(root.left); 112 | printHelper(root.right); 113 | return; 114 | } 115 | 116 | 117 | // ------delete 118 | public static void deleteData(int data){ 119 | root= deleteHelper(root,data); 120 | // return; 121 | } 122 | private static BinaryTreeNode deleteHelper(BinaryTreeNode root,int data){ 123 | if(root==null) 124 | return null; 125 | if(root.data==data){ 126 | if(root.left!=null && root.right==null) 127 | return root.left; 128 | else if(root.left==null && root.right!=null) 129 | return root.right; 130 | else if(root.left==null && root.right==null) 131 | return null; 132 | else{ 133 | // int rootData=minimum(root.right); 134 | // BinaryTreeNode newNode= deleteHelper(root,rootData); 135 | 136 | BinaryTreeNode minNode = root.right; 137 | while (minNode.left != null) { 138 | minNode = minNode.left; 139 | } 140 | root.data = minNode.data; 141 | root.right = deleteHelper(root.right,minNode.data); 142 | return root; 143 | } 144 | 145 | } 146 | else if(root.data>data) 147 | {BinaryTreeNode leftt=deleteHelper(root.left,data); 148 | root.left=leftt;} 149 | else{ 150 | BinaryTreeNode rightt=deleteHelper(root.right,data); 151 | root.right=rightt; 152 | } 153 | 154 | return root; 155 | } 156 | 157 | } 158 | --------------------------------------------------------------------------------