├── 2D Arrays └── ring rotate.java ├── Binary Search Tree ├── Add node to BST.java ├── Lca of BST.java ├── Print in Range.java ├── Remove node in BST.java ├── Replace with sum of Larger.java ├── Size,Sum,Max,Min,find.java └── Target Sum Pair in BST.java ├── Binary tree ├── Diameter Of A Binary Tree.java ├── Find And Nodetorootpath In Binary Tree.java ├── Is Balanced Tree.java ├── Iterative Pre, Post And Inorder Traversals Of Binary Tree.java ├── Level order Traversal.java ├── Path To Leaf From Root In Range.java ├── Print Nodes K Distance Away.java ├── Print Single Child Nodes.java ├── Remove Leaves In Binary Tree.java ├── Size, Sum, Maximum And Height Of A Binary Tree.java ├── Tilt Of Binary Tree.java ├── Transform To Left-cloned Tree.java ├── Transform To Normal From Left-cloned Tree.java └── printKLevelsDown.java ├── Generic Tree ├── Are Trees Mirror in Shape.java ├── Are Trees Similar in Shape.java ├── Ceil and Floor in GT.java ├── Diameter in GT.java ├── Find in GT.java ├── GT Traversal (pre,post).java ├── Height of a GT.java ├── Is GT Symmetric.java ├── Kth Largest element in Tree.java ├── Level order Linewise Zigzag.java ├── Level order of GT.java ├── Levelorder Linewise GT.java ├── Linearize a GT.java ├── Lowest Common Ancestor.java ├── Maximum in a GT.java ├── Mirror a GT.java ├── Node to Root Path in Gt.java ├── Predecessor and Successor of an Element.java ├── Remove Leaves in GT.java ├── Size of GT.java ├── construction and display.java └── distance Between Two Nodes in A GT.java ├── Getting Started ├── Grading system.java └── Print Z.java ├── Graph ├── Breadth First Traversal (BFS).java ├── Get Connected Components of a Graph.java ├── Hamiltonian Path and Cycle.java ├── Has Path.java ├── Is Graph Bipartite.java ├── Is Graph Cycle.java ├── Is Graph connected.java ├── Multi solver graph.java ├── Number of Islands.java ├── Perfect Friends.java └── Print all Paths.java ├── HashMap ├── Get common elments1.java ├── Get common elments2.java ├── Highest Frequency Character.java ├── K Largest Elements.java ├── Longest Consecutive Sequence of elements.java └── Sort K-sorted Array.java ├── Level-02 ├── Bits Manipulation │ ├── 1310. XOR Queries of a Subarray.java │ ├── All Repeating Except One.java │ ├── All Repeating Except Two.java │ ├── All Repeating Three Times Except One.java │ ├── Basics of Bits Manipulation.java │ ├── Check divisibility by 3.java │ ├── Copy Set Bits in a Range.java │ ├── Count Set Bits In First N Natural Numbers.java │ ├── Flip Bits To Convert A to B.java │ ├── Is a Power of 2.java │ ├── Kernighans Algorithm.java │ ├── One Repeating and One Missing.java │ ├── Pepcoder and Bits.java │ ├── Print Binary and Reverse Bits.java │ ├── Print value of Rsb Mask.java │ ├── Reduce N to 1.java │ ├── Solve 7n By 8.java │ ├── Sum Of Bit Differences Of All Pairs.java │ ├── Triplets-1.java │ └── Xor Of Sum Of All Pairs.java ├── Dynamic Programming │ ├── Catalan Number │ │ ├── memoization.java │ │ ├── recursion.java │ │ └── tabulation.java │ ├── Count Of Valleys And Mountains │ │ └── tabulation.java │ ├── CountBrackets │ │ └── tabulation.java │ ├── Edit Distance │ │ ├── memoization.java │ │ ├── recursion.java │ │ └── tabulation.java │ ├── Fibonacci Number │ │ ├── memoization.java │ │ ├── recursion.java │ │ └── tabulation.java │ ├── KnapSack with Duplicate Items │ │ ├── memoization.java │ │ ├── recursion.java │ │ └── tabulation.java │ ├── Matrix Chain Multiplication │ │ ├── memoization.java │ │ ├── recursion.java │ │ └── tabulation.java │ ├── Minimum Insertion Steps to Make a String Palindrome │ │ └── tabulation.java │ ├── Palindromic Partitioning │ │ ├── memoization.java │ │ ├── recursion.java │ │ └── tabulation.java │ └── Unique BSTs │ │ └── memoization.java └── Recursion and Backtracking │ ├── Abbreviation Using Backtracking.java │ ├── All Palindromic Partitions.java │ ├── All Palindromic Permutations.java │ ├── Coin Change - Combinations - 1.java │ ├── Coin Change - Combinations - 2.java │ ├── Coin Change - Permutations - 1.java │ ├── Coin Change - Permutations - 2.java │ ├── Combinations-1.java │ ├── Combinations-2.java │ ├── Crossword Puzzle.java │ ├── Cryptarithmetic.java │ ├── Friends Pairing - 2.java │ ├── Josephus Problem.java │ ├── K Subsets With Equal Sum.java │ ├── K-partitions.java │ ├── Largest Number Possible After At Most K Swaps.java │ ├── Lexicographical Numbers.java │ ├── Magnets.java │ ├── Max Score.java │ ├── Nknights Combinations - 2d As 1d - Knight Chooses.java │ ├── Nqueens Combinations - 2d As 1d - Queen Chooses.java │ ├── Nqueens Permutations - 2d As 1d - Queen Chooses.java │ ├── Pattern Matching.java │ ├── Permutation-1.java │ ├── Permutation-2.java │ ├── Permutations - Words - 1.java │ ├── Permutations - Words - 2.java │ ├── Queens Combinations - 2d As 1d - Queen Chooses.java │ ├── Queens Combinations - 2d As 2d - Box Chooses(default).java │ ├── Queens Combinations - 2d As 2d - Queen Chooses(derived).java │ ├── Queens Permutations - 2d As 2d - Box Chooses(derived).java │ ├── Queens Permutations - 2d As 2d - Queen Chooses(default).java │ ├── Remove Invalid Parenthesis.java │ ├── Solve Sudoku.java │ ├── Tug Of War.java │ ├── Word Break - I.java │ ├── Words - K Length Words - 1.java │ ├── Words - K Length Words - 2.java │ ├── Words - K Length Words - 3.java │ ├── Words - K Length Words - 4.java │ ├── Words - K Selection - 1.java │ ├── Words - K Selection - 2.java │ ├── Words - K Selection - 3.java │ ├── Words - K Selection - 4.java │ ├── nqueen branch and bound.java │ └── nqueen using bits.java ├── LinkedList ├── Add at Index in LL.java ├── Display Reverse(recursive)-LL.java ├── Intersection Point of LL.java ├── Is a LL Palindrome.java ├── K Reverse in LL.java ├── Kth node from End of LL.java ├── LL to Queue Adapter.java ├── LL to Stack Adapter.java ├── Merge Sort a LL.java ├── Merge Two Sorted LL.java ├── Mid of LL.java ├── Odd Even LL.java ├── Remove Duplicates in a sorted LL.java ├── Remove First in LL.java ├── Reverse LL(pointer -recursive).java ├── Reverse a LL (data -iterative recursion).java ├── Reverse a LL (data iterative).java ├── Reverse a LL (pointer iterative).java ├── add First in LL.java ├── addLast.java ├── display a LL.java ├── get value in LL.java ├── remove at Index in LL.java └── remove last in LL.java ├── Patterns ├── Pattern1.java └── Pattern2.java ├── README.md ├── Recursion ├── Factorial.java ├── Print Increasing.java ├── Print decreasing.java ├── Recursion and Backtracking │ ├── Flood Fill.java │ └── N Queen.java ├── Recursion on the way up │ ├── Print Encodings.java │ ├── Print Maze Paths.java │ ├── Print Permutation.java │ └── Print Subsequence.java └── Recursion with ArrayList │ ├── Get KPC.java │ ├── Get Stair Paths.java │ └── Get Subsequence.java ├── Stack ├── Balanced Bracket.java ├── Celebrity Problem.java ├── Infix Conversion.java ├── Infix Evaluation.java ├── Postfix Evaluation and Conversion.java └── Sliding Window Maximum.java ├── String ├── Print all Palindromic Substring.java └── String compression.java └── Test -01 Solution ├── Hash Pattern 1.java ├── Inverse of a Number 1.java ├── Left Rotation.java ├── Partition an Array.java └── Pattern Alpha Numeric.java /Binary Search Tree/Add node to BST.java: -------------------------------------------------------------------------------- 1 | public static Node add(Node node, int data) { 2 | // write your code here 3 | if(node==null){ 4 | Node nn=new Node(data,null,null); 5 | return nn; 6 | } 7 | 8 | if(node.data>data){ 9 | node.left=add(node.left,data); 10 | }else if(node.datad1 && node.data>d2){ 5 | return lca(node.left,d1,d2); 6 | 7 | }else if(node.datanode.data && d2>node.data) { 11 | pir(node.right,d1,d2); 12 | }else{ 13 | pir(node.left,d1,d2); 14 | System.out.println(node.data); 15 | pir(node.right,d1,d2); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Binary Search Tree/Remove node in BST.java: -------------------------------------------------------------------------------- 1 | 2 | public static Node remove(Node node, int data) { 3 | // write your code here 4 | if(node==null){ 5 | return null; 6 | } 7 | 8 | if(node.data>data){ 9 | node.left=remove(node.left,data); 10 | }else if(node.datadata){ 53 | return find(node.left,data); 54 | }else { 55 | return find(node.right,data); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Binary Search Tree/Target Sum Pair in BST.java: -------------------------------------------------------------------------------- 1 | public static void targetSum(Node root,Node node,int target){ 2 | if(node==null){ 3 | return ; 4 | } 5 | 6 | targetSum(root,node.left,target); 7 | 8 | int remainingPart=target-node.data; 9 | if(node.data-remainingPart<0){ 10 | if(find(root,remainingPart)){ 11 | System.out.println(node.data+" "+remainingPart); 12 | } 13 | } 14 | 15 | 16 | targetSum(root,node.right,target); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Binary tree/Diameter Of A Binary Tree.java: -------------------------------------------------------------------------------- 1 | static int dia=0; 2 | public static int diameter1(Node node) { 3 | // write your code here 4 | if(node==null){ 5 | return -1; 6 | } 7 | 8 | int lh=diameter1(node.left); 9 | int rh=diameter1(node.right); 10 | 11 | dia=Math.max(dia,lh+rh+2); 12 | 13 | return Math.max(lh,rh)+1; 14 | } 15 | -------------------------------------------------------------------------------- /Binary tree/Find And Nodetorootpath In Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | public static boolean find(Node node, int data){ 3 | // write your code here 4 | 5 | if(node==null){ 6 | return false; 7 | } 8 | 9 | if(node.data==data){ 10 | return true; 11 | } 12 | 13 | boolean leftSide=find(node.left,data); 14 | if(leftSide==true){ 15 | return true; 16 | } 17 | 18 | boolean rightSide=find(node.right,data); 19 | if(rightSide==true){ 20 | return true; 21 | } 22 | 23 | return false; 24 | 25 | } 26 | 27 | public static ArrayList nodeToRootPath(Node node, int data){ 28 | // write your code here 29 | if(node==null){ 30 | return new ArrayList<>(); 31 | } 32 | 33 | if(node.data==data){ 34 | ArrayListbase=new ArrayList<>(); 35 | base.add(node.data); 36 | 37 | return base; 38 | } 39 | 40 | ArrayListleftSide=nodeToRootPath(node.left,data); 41 | if(leftSide.size()>0){ 42 | leftSide.add(node.data); 43 | 44 | return leftSide; 45 | } 46 | 47 | ArrayListrightSide=nodeToRootPath(node.right,data); 48 | if(rightSide.size()>0){ 49 | rightSide.add(node.data); 50 | 51 | return rightSide; 52 | } 53 | 54 | return new ArrayList<>(); 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Binary tree/Is Balanced Tree.java: -------------------------------------------------------------------------------- 1 | static boolean balance=true; 2 | 3 | public static int isBalance(Node node){ 4 | 5 | if(node==null) return -1; 6 | 7 | int lh=isBalance(node.left); 8 | int rh=isBalance(node.right); 9 | 10 | if(Math.abs(lh-rh)>1){ 11 | balance=false; 12 | } 13 | 14 | return Math.max(lh,rh)+1; 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Binary tree/Iterative Pre, Post And Inorder Traversals Of Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | public static void iterativePrePostInTraversal(Node node) { 3 | // write your code here 4 | Stackst=new Stack<>(); 5 | 6 | st.push(new Pair(node,0)); 7 | 8 | String pre=""; 9 | String in=""; 10 | String post=""; 11 | 12 | while(st.size()>0){ 13 | Pair tos=st.peek(); 14 | 15 | if(tos.state==0){ 16 | pre+=tos.node.data+" "; 17 | tos.state++; 18 | if(tos.node.left!=null){ 19 | st.push(new Pair(tos.node.left,0)); 20 | } 21 | 22 | }else if(tos.state==1){ 23 | in+=tos.node.data+" "; 24 | tos.state++; 25 | if(tos.node.right!=null){ 26 | st.push(new Pair(tos.node.right,0)); 27 | } 28 | 29 | }else { 30 | post+=tos.node.data+" "; 31 | st.pop(); 32 | } 33 | } 34 | 35 | System.out.println(pre); 36 | System.out.println(in); 37 | System.out.println(post); 38 | } 39 | -------------------------------------------------------------------------------- /Binary tree/Level order Traversal.java: -------------------------------------------------------------------------------- 1 | 2 | public static void levelOrder(Node node) { 3 | // write your code here 4 | 5 | Queueq=new ArrayDeque<>(); 6 | q.add(node); 7 | 8 | while(q.size()>0){ 9 | int sz=q.size(); 10 | while(sz>0){ 11 | node=q.remove(); 12 | System.out.print(node.data+" "); 13 | 14 | if(node.left!=null){ 15 | q.add(node.left); 16 | } 17 | 18 | if(node.right!=null){ 19 | q.add(node.right); 20 | } 21 | sz--; 22 | } 23 | 24 | System.out.println(); 25 | } 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Binary tree/Path To Leaf From Root In Range.java: -------------------------------------------------------------------------------- 1 | public static void pathToLeafFromRoot(Node node, String path, int sum, int lo, int hi){ 2 | // write your code here 3 | if(node==null) return ; 4 | 5 | if(node.left==null && node.right==null){ 6 | sum+=node.data; 7 | if(sum>=lo && sum<=hi){ 8 | System.out.println(path+node.data); 9 | } 10 | 11 | return; 12 | } 13 | 14 | pathToLeafFromRoot(node.left,path+node.data+" ",sum+node.data,lo,hi); 15 | pathToLeafFromRoot(node.right,path+node.data+" ",sum+node.data,lo,hi); 16 | } 17 | -------------------------------------------------------------------------------- /Binary tree/Print Nodes K Distance Away.java: -------------------------------------------------------------------------------- 1 | 2 | public static ArrayList nodeToRootPath(Node node, int data){ 3 | // write your code here 4 | if(node==null){ 5 | return new ArrayList<>(); 6 | } 7 | 8 | if(node.data==data){ 9 | ArrayListbase=new ArrayList<>(); 10 | base.add(node); 11 | 12 | return base; 13 | } 14 | 15 | ArrayListleftSide=nodeToRootPath(node.left,data); 16 | if(leftSide.size()>0){ 17 | leftSide.add(node); 18 | 19 | return leftSide; 20 | } 21 | 22 | ArrayListrightSide=nodeToRootPath(node.right,data); 23 | if(rightSide.size()>0){ 24 | rightSide.add(node); 25 | 26 | return rightSide; 27 | } 28 | 29 | return new ArrayList<>(); 30 | 31 | 32 | } 33 | 34 | public static void printKLevelsDown(Node node, int k,Node blocker){ 35 | // write your code here 36 | 37 | if(node==null || node==blocker){ 38 | return ; 39 | } 40 | 41 | if(k==0){ 42 | System.out.println(node.data); 43 | } 44 | 45 | 46 | printKLevelsDown(node.left,k-1,blocker); 47 | printKLevelsDown(node.right,k-1,blocker); 48 | } 49 | 50 | public static void printKNodesFar(Node node, int data, int k) { 51 | // write your code here 52 | ArrayListal=nodeToRootPath(node,data); 53 | 54 | for(int i=0;iif node is pointing to null 6 | if(node==null){ 7 | return 0; 8 | } 9 | 10 | // faith 11 | // leftside-> give the size of left side 12 | int leftside=size(node.left); 13 | 14 | // rightside ->give the size of right side 15 | int rightside=size(node.right); 16 | 17 | // final answer/ my work 18 | return leftside+rightside+1; 19 | 20 | } 21 | 22 | public static int sum(Node node) { 23 | // write your code here 24 | if(node==null){ 25 | return 0; 26 | } 27 | 28 | int leftsum=sum(node.left); 29 | int rightsum=sum(node.right); 30 | 31 | return leftsum+rightsum+node.data; 32 | } 33 | 34 | public static int max(Node node) { 35 | // write your code here 36 | 37 | if(node==null){ 38 | return Integer.MIN_VALUE; 39 | } 40 | 41 | int leftmax=max(node.left); 42 | int rightmax=max(node.right); 43 | int ans=Math.max(node.data,Math.max(leftmax,rightmax)); 44 | 45 | return ans; 46 | } 47 | 48 | public static int height(Node node) { 49 | // write your code here 50 | 51 | if(node==null){ 52 | return -1; 53 | } 54 | 55 | int leftHeight=height(node.left); 56 | int rightHeight=height(node.right); 57 | 58 | int myHeight=Math.max(leftHeight,rightHeight)+1; 59 | 60 | return myHeight; 61 | } 62 | -------------------------------------------------------------------------------- /Binary tree/Tilt Of Binary Tree.java: -------------------------------------------------------------------------------- 1 | static int tilt = 0; 2 | public static int tilt(Node node){ 3 | // write your code here to set the tilt data member 4 | 5 | if(node==null) return 0; 6 | 7 | int ls=tilt(node.left); 8 | int rs=tilt(node.right); 9 | 10 | tilt+=Math.abs(ls-rs); 11 | 12 | return ls+rs+node.data; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Binary tree/Transform To Left-cloned Tree.java: -------------------------------------------------------------------------------- 1 | public static void createLeftCloneTree(Node node){ 2 | // write your code here 3 | if(node==null){ 4 | return ; 5 | } 6 | 7 | createLeftCloneTree(node.left); 8 | createLeftCloneTree(node.right); 9 | 10 | Node clone=new Node(node.data,node.left,null); 11 | node.left=clone; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Binary tree/Transform To Normal From Left-cloned Tree.java: -------------------------------------------------------------------------------- 1 | public static void transBackFromLeftClonedTree(Node node){ 2 | // write your code here 3 | if(node==null) return ; 4 | 5 | transBackFromLeftClonedTree(node.left.left); 6 | transBackFromLeftClonedTree(node.right); 7 | 8 | node.left=node.left.left; 9 | } 10 | -------------------------------------------------------------------------------- /Binary tree/printKLevelsDown.java: -------------------------------------------------------------------------------- 1 | public static void printKLevelsDown(Node node, int k){ 2 | // write your code here 3 | 4 | if(node==null){ 5 | return ; 6 | } 7 | 8 | if(k==0){ 9 | System.out.println(node.data); 10 | } 11 | 12 | 13 | printKLevelsDown(node.left,k-1); 14 | printKLevelsDown(node.right,k-1); 15 | } 16 | -------------------------------------------------------------------------------- /Generic Tree/Are Trees Mirror in Shape.java: -------------------------------------------------------------------------------- 1 | 2 | public static boolean areMirror(Node n1, Node n2) { 3 | // write your code here 4 | if(n1.children.size()!=n2.children.size()) 5 | return false; 6 | 7 | 8 | for(int i=0;ifloor){ 5 | floor=node.data; 6 | } 7 | 8 | if(node.data>data && node.datamaxh){ 11 | secMaxH=maxh; 12 | maxh=ch; 13 | }else if(secMaxHc1=new Stack<>(); 4 | Stackc2=new Stack<>(); 5 | 6 | c1.push(node); 7 | 8 | int level=0; 9 | 10 | while(c1.size()>0){ 11 | 12 | node=c1.pop(); 13 | 14 | System.out.print(node.data+" "); 15 | 16 | if(level%2==0){ 17 | for(int i=0;i=0;i--){ 23 | Node child=node.children.get(i); 24 | c2.push(child); 25 | } 26 | } 27 | 28 | if(c1.size()==0){ 29 | c1=c2; 30 | c2=new Stack<>(); 31 | level++; 32 | System.out.println(); 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Generic Tree/Level order of GT.java: -------------------------------------------------------------------------------- 1 | 2 | public static void levelOrder(Node node){ 3 | // write your code here 4 | // Create Queue 5 | Queueq=new ArrayDeque<>(); 6 | // Add root to the queue 7 | q.add(node); 8 | 9 | 10 | // Run a loop until queue is not empty 11 | while(q.size()>0){ 12 | 13 | // Remove and Print 14 | Node nn=q.remove(); 15 | 16 | System.out.print(nn.data+ " "); 17 | 18 | // Adding children 19 | for(Node child:nn.children){ 20 | q.add(child); 21 | } 22 | 23 | } 24 | System.out.println("."); 25 | } 26 | -------------------------------------------------------------------------------- /Generic Tree/Levelorder Linewise GT.java: -------------------------------------------------------------------------------- 1 | public static void levelOrderLinewise(Node node){ 2 | // write your code here 3 | 4 | // Create Queue 5 | Queueq=new ArrayDeque<>(); 6 | // Add root to the queue 7 | q.add(node); 8 | 9 | 10 | // Run a loop until queue is not empty 11 | while(q.size()>0){ 12 | int sz=q.size(); 13 | while(sz-->0){ 14 | 15 | // Remove and Print 16 | Node nn=q.remove(); 17 | 18 | System.out.print(nn.data+ " "); 19 | 20 | // Adding children 21 | for(Node child:nn.children){ 22 | q.add(child); 23 | } 24 | } 25 | System.out.println(); 26 | 27 | } 28 | // System.out.println("."); 29 | } 30 | -------------------------------------------------------------------------------- /Generic Tree/Linearize a GT.java: -------------------------------------------------------------------------------- 1 | 2 | public static void linearize(Node node) { 3 | for (Node child : node.children) { 4 | linearize(child); 5 | } 6 | 7 | for (int i = node.children.size() - 2; i >= 0; i--) { 8 | Node ip1 = node.children.remove(i + 1); 9 | Node itail = getTail(node.children.get(i)); 10 | itail.children.add(ip1); 11 | } 12 | } 13 | 14 | private static Node getTail(Node node) { 15 | while (node.children.size() == 1) { 16 | node = node.children.get(0); 17 | } 18 | 19 | return node; 20 | } 21 | -------------------------------------------------------------------------------- /Generic Tree/Lowest Common Ancestor.java: -------------------------------------------------------------------------------- 1 | public static int lca(Node node, int d1, int d2) { 2 | // write your code here 3 | ArrayLista1=nodeToRootPath(node,d1); 4 | ArrayLista2=nodeToRootPath(node,d2); 5 | 6 | int i=a1.size()-1; 7 | int j=a2.size()-1; 8 | 9 | while(i>=0 && j>=0 && a1.get(i)==a2.get(j)){ 10 | i--; 11 | j--; 12 | } 13 | 14 | return a1.get(i+1); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Generic Tree/Maximum in a GT.java: -------------------------------------------------------------------------------- 1 | 2 | public static int max(Node node) { 3 | // write your code here 4 | int maximum=Integer.MIN_VALUE; 5 | 6 | for(Node child:node.children){ 7 | int cm=max(child); 8 | maximum=Math.max(maximum,cm); 9 | } 10 | maximum=Math.max(maximum,node.data); 11 | 12 | return maximum; 13 | } 14 | -------------------------------------------------------------------------------- /Generic Tree/Mirror a GT.java: -------------------------------------------------------------------------------- 1 | public static void mirror(Node node){ 2 | // write your code here 3 | 4 | // Faith 5 | for(Node child:node.children){ 6 | mirror(child); 7 | } 8 | 9 | // My work -> reverse the ArrayList 10 | 11 | int left=0; 12 | int right=node.children.size()-1; 13 | 14 | while(left nodeToRootPath(Node node, int data){ 3 | // write your code here 4 | if(node.data==data){ 5 | ArrayListbase=new ArrayList<>(); 6 | base.add(data); 7 | 8 | return base; 9 | } 10 | 11 | for(Node child:node.children){ 12 | ArrayListres=nodeToRootPath(child,data); 13 | if(res.size()>0){ 14 | res.add(node.data); 15 | return res; 16 | } 17 | } 18 | 19 | 20 | return new ArrayList<>(); 21 | 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Generic Tree/Predecessor and Successor of an Element.java: -------------------------------------------------------------------------------- 1 | 2 | static int state; 3 | static Node predecessor; 4 | static Node successor; 5 | public static void predecessorAndSuccessor(Node node, int data) { 6 | // write your code 7 | if(state==0){ 8 | if(node.data!=data){ 9 | predecessor=node; 10 | }else { 11 | state=1; 12 | } 13 | }else if(state==1){ 14 | successor=node; 15 | state=2; 16 | } 17 | 18 | 19 | for(Node child:node.children){ 20 | predecessorAndSuccessor(child,data); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Generic Tree/Remove Leaves in GT.java: -------------------------------------------------------------------------------- 1 | 2 | public static void removeLeaves(Node node) { 3 | // write your code here 4 | 5 | 6 | 7 | for(Node child:node.children){ 8 | removeLeaves(child); 9 | } 10 | 11 | for(int i=0;ichildren; 10 | 11 | Node(int data){ 12 | this.data=data; 13 | children=new ArrayList<>(); 14 | } 15 | } 16 | public static void display(Node node){ 17 | String str=node.data+" -> "; 18 | for(Node child:node.children){ 19 | str+=child.data+", "; 20 | } 21 | 22 | str+=" ."; 23 | 24 | System.out.println(str); 25 | 26 | for(Node child:node.children){ 27 | display(child); 28 | } 29 | 30 | // for(int i=0;ist=new Stack<>(); 38 | Node root=new Node(arr[0]); 39 | 40 | st.push(root); 41 | for(int i=1;ia1=nodeToRootPath(node,d1); 4 | ArrayLista2=nodeToRootPath(node,d2); 5 | 6 | int i=a1.size()-1; 7 | int j=a2.size()-1; 8 | 9 | while(i>=0 && j>=0 && a1.get(i)==a2.get(j)){ 10 | i--; 11 | j--; 12 | } 13 | 14 | i++; 15 | j++; 16 | 17 | return i+j; 18 | } 19 | -------------------------------------------------------------------------------- /Getting Started/Grading system.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main{ 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner scn = new Scanner(System.in); 8 | int marks = scn.nextInt(); 9 | 10 | 11 | if(marks > 90){ 12 | System.out.println("excellent"); 13 | } else if(marks > 80){ 14 | System.out.println("good"); 15 | } else if(marks > 70){ 16 | System.out.println("fair"); 17 | } else if(marks > 60){ 18 | System.out.println("meets expectations"); 19 | } else { 20 | System.out.println("below par"); 21 | } 22 | 23 | } 24 | } 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Getting Started/Print Z.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("*****"); 7 | System.out.println(" *"); 8 | System.out.println(" *"); 9 | System.out.println(" *"); 10 | System.out.println("*****"); 11 | } 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /Graph/Breadth First Traversal (BFS).java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static class Pair{ 7 | int vtx; 8 | String psf; 9 | 10 | public Pair(int vtx,String psf){ 11 | this.vtx=vtx; 12 | this.psf=psf; 13 | } 14 | } 15 | static class Edge { 16 | int src; 17 | int nbr; 18 | 19 | Edge(int src, int nbr) { 20 | this.src = src; 21 | this.nbr = nbr; 22 | } 23 | } 24 | 25 | public static void main(String[] args) throws Exception { 26 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 27 | 28 | int vtces = Integer.parseInt(br.readLine()); 29 | ArrayList[] graph = new ArrayList[vtces]; 30 | for (int i = 0; i < vtces; i++) { 31 | graph[i] = new ArrayList<>(); 32 | } 33 | 34 | int edges = Integer.parseInt(br.readLine()); 35 | for (int i = 0; i < edges; i++) { 36 | String[] parts = br.readLine().split(" "); 37 | int v1 = Integer.parseInt(parts[0]); 38 | int v2 = Integer.parseInt(parts[1]); 39 | graph[v1].add(new Edge(v1, v2)); 40 | graph[v2].add(new Edge(v2, v1)); 41 | } 42 | 43 | int src = Integer.parseInt(br.readLine()); 44 | 45 | 46 | Queue q=new ArrayDeque<>(); 47 | boolean visited[]=new boolean[vtces]; 48 | 49 | 50 | q.add(new Pair(src,src+"")); 51 | 52 | while(q.size()>0){ 53 | // Remove 54 | Pair rp=q.remove(); 55 | // check for visited 56 | if(visited[rp.vtx]==false){ 57 | // Mark and Print 58 | visited[rp.vtx]=true; 59 | 60 | System.out.println(rp.vtx +"@" +rp.psf); 61 | 62 | // Add unvisited nbrs 63 | for(Edge e:graph[rp.vtx]){ 64 | int nbr=e.nbr; 65 | if(visited[nbr]==false){ 66 | q.add(new Pair(nbr ,rp.psf+nbr)); 67 | } 68 | } 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Graph/Get Connected Components of a Graph.java: -------------------------------------------------------------------------------- 1 | 2 | public static void main(String[] args) throws Exception { 3 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 4 | 5 | int vtces = Integer.parseInt(br.readLine()); 6 | ArrayList[] graph = new ArrayList[vtces]; 7 | for (int i = 0; i < vtces; i++) { 8 | graph[i] = new ArrayList<>(); 9 | } 10 | 11 | int edges = Integer.parseInt(br.readLine()); 12 | for (int i = 0; i < edges; i++) { 13 | String[] parts = br.readLine().split(" "); 14 | int v1 = Integer.parseInt(parts[0]); 15 | int v2 = Integer.parseInt(parts[1]); 16 | int wt = Integer.parseInt(parts[2]); 17 | graph[v1].add(new Edge(v1, v2, wt)); 18 | graph[v2].add(new Edge(v2, v1, wt)); 19 | } 20 | 21 | ArrayList> comps = new ArrayList<>(); 22 | int src=0; 23 | boolean visited[]=new boolean [vtces]; 24 | for(int i=0;icomp=new ArrayList<>(); 27 | getComp(graph,i,visited,comp); 28 | 29 | comps.add(comp); 30 | 31 | } 32 | } 33 | // write your code here 34 | 35 | System.out.println(comps); 36 | } 37 | 38 | public static void getComp(ArrayListgraph[],int src,boolean [] visited,ArrayListcomp){ 39 | 40 | visited[src]=true; 41 | comp.add(src); 42 | for(Edge e:graph[src]){ 43 | int nbr=e.nbr; 44 | if(visited[nbr]==false){ 45 | getComp(graph,nbr,visited,comp); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Graph/Hamiltonian Path and Cycle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | static class Edge { 6 | int src; 7 | int nbr; 8 | int wt; 9 | 10 | Edge(int src, int nbr, int wt) { 11 | this.src = src; 12 | this.nbr = nbr; 13 | this.wt = wt; 14 | } 15 | } 16 | 17 | public static void main(String[] args) throws Exception { 18 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 19 | 20 | int vtces = Integer.parseInt(br.readLine()); 21 | ArrayList[] graph = new ArrayList[vtces]; 22 | for (int i = 0; i < vtces; i++) { 23 | graph[i] = new ArrayList<>(); 24 | } 25 | 26 | int edges = Integer.parseInt(br.readLine()); 27 | for (int i = 0; i < edges; i++) { 28 | String[] parts = br.readLine().split(" "); 29 | int v1 = Integer.parseInt(parts[0]); 30 | int v2 = Integer.parseInt(parts[1]); 31 | int wt = Integer.parseInt(parts[2]); 32 | graph[v1].add(new Edge(v1, v2, wt)); 33 | graph[v2].add(new Edge(v2, v1, wt)); 34 | } 35 | 36 | int src = Integer.parseInt(br.readLine()); 37 | 38 | // write all your codes here 39 | boolean visited[]=new boolean [vtces]; 40 | 41 | hpc(graph,src,src,visited,src+"",0); 42 | 43 | 44 | } 45 | 46 | 47 | public static void hpc(ArrayListgraph[],int src1,int src2,boolean [] visited,String asf, int vvsf ){ 48 | if(vvsf==graph.length-1){ 49 | System.out.print(asf); 50 | 51 | boolean hc=false; 52 | for(Edge e:graph[src2]){ 53 | int nbr=e.nbr; 54 | if(nbr==src1){ 55 | hc=true; 56 | break; 57 | } 58 | } 59 | 60 | if(hc==true){ 61 | System.out.println("*"); 62 | }else { 63 | System.out.println("."); 64 | } 65 | 66 | return ; 67 | } 68 | 69 | 70 | 71 | visited[src1]=true; 72 | 73 | for(Edge e:graph[src1]){ 74 | int nbr=e.nbr; 75 | if(visited[nbr]==false){ 76 | hpc(graph,nbr,src2,visited,asf+nbr,vvsf+1); 77 | } 78 | } 79 | 80 | visited[src1]=false; 81 | 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /Graph/Has Path.java: -------------------------------------------------------------------------------- 1 | public static void main(String[] args) throws Exception { 2 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 3 | 4 | int vtces = Integer.parseInt(br.readLine()); 5 | ArrayList[] graph = new ArrayList[vtces]; 6 | for(int i = 0; i < vtces; i++){ 7 | graph[i] = new ArrayList<>(); 8 | } 9 | 10 | int edges = Integer.parseInt(br.readLine()); 11 | for(int i = 0; i < edges; i++){ 12 | 13 | String[] parts = br.readLine().split(" "); 14 | int v1 = Integer.parseInt(parts[0]); 15 | int v2 = Integer.parseInt(parts[1]); 16 | int wt = Integer.parseInt(parts[2]); 17 | graph[v1].add(new Edge(v1, v2, wt)); 18 | graph[v2].add(new Edge(v2, v1, wt)); 19 | } 20 | 21 | int src = Integer.parseInt(br.readLine()); 22 | int dest = Integer.parseInt(br.readLine()); 23 | 24 | boolean visited[]=new boolean[vtces]; 25 | System.out.println(hasPath(graph,src,dest,visited)); 26 | 27 | // write your code here 28 | } 29 | 30 | public static boolean hasPath(ArrayList[]graph,int src,int dest,boolean []visited){ 31 | 32 | if(src==dest){ 33 | return true; 34 | } 35 | 36 | visited[src]=true; 37 | for(Edge e:graph[src]){ 38 | int nbr=e.nbr; 39 | if(visited[nbr]==false){ 40 | boolean ntod= hasPath(graph,nbr,dest,visited); 41 | if(ntod==true){ 42 | return true; 43 | } 44 | } 45 | 46 | } 47 | 48 | return false; 49 | } 50 | -------------------------------------------------------------------------------- /Graph/Is Graph Bipartite.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | static class Pair{ 7 | int vtx; 8 | int level; 9 | 10 | Pair(int vtx,int level){ 11 | this.vtx=vtx; 12 | this.level=level; 13 | } 14 | } 15 | 16 | static class Edge { 17 | int src; 18 | int nbr; 19 | int wt; 20 | 21 | Edge(int src, int nbr, int wt) { 22 | this.src = src; 23 | this.nbr = nbr; 24 | this.wt = wt; 25 | } 26 | } 27 | 28 | public static void main(String[] args) throws Exception { 29 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 30 | 31 | int vtces = Integer.parseInt(br.readLine()); 32 | ArrayList[] graph = new ArrayList[vtces]; 33 | for (int i = 0; i < vtces; i++) { 34 | graph[i] = new ArrayList<>(); 35 | } 36 | 37 | int edges = Integer.parseInt(br.readLine()); 38 | for (int i = 0; i < edges; i++) { 39 | String[] parts = br.readLine().split(" "); 40 | int v1 = Integer.parseInt(parts[0]); 41 | int v2 = Integer.parseInt(parts[1]); 42 | int wt = Integer.parseInt(parts[2]); 43 | graph[v1].add(new Edge(v1, v2, wt)); 44 | graph[v2].add(new Edge(v2, v1, wt)); 45 | } 46 | 47 | // write your code here 48 | 49 | 50 | int []visited=new int [vtces]; 51 | Arrays.fill(visited,-1); 52 | 53 | 54 | for(int i=0;i[]graph,int []visited,int src){ 72 | 73 | Queueq=new ArrayDeque<>(); 74 | q.add(new Pair(src,0)); 75 | 76 | while(q.size()>0){ 77 | Pair rp=q.remove(); 78 | if(visited[rp.vtx]!=-1){ 79 | if(rp.level!=visited[rp.vtx]){ 80 | return false; 81 | } 82 | 83 | }else { 84 | visited[rp.vtx]=rp.level; 85 | } 86 | 87 | for(Edge e:graph[rp.vtx]){ 88 | int nbr=e.nbr; 89 | if(visited[nbr]==-1){ 90 | q.add(new Pair(nbr,rp.level+1)); 91 | } 92 | } 93 | 94 | 95 | } 96 | 97 | return true; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Graph/Is Graph Cycle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | static class Edge { 6 | int src; 7 | int nbr; 8 | int wt; 9 | 10 | Edge(int src, int nbr, int wt) { 11 | this.src = src; 12 | this.nbr = nbr; 13 | this.wt = wt; 14 | } 15 | } 16 | 17 | public static void main(String[] args) throws Exception { 18 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 19 | 20 | int vtces = Integer.parseInt(br.readLine()); 21 | ArrayList[] graph = new ArrayList[vtces]; 22 | for (int i = 0; i < vtces; i++) { 23 | graph[i] = new ArrayList<>(); 24 | } 25 | 26 | int edges = Integer.parseInt(br.readLine()); 27 | for (int i = 0; i < edges; i++) { 28 | String[] parts = br.readLine().split(" "); 29 | int v1 = Integer.parseInt(parts[0]); 30 | int v2 = Integer.parseInt(parts[1]); 31 | int wt = Integer.parseInt(parts[2]); 32 | graph[v1].add(new Edge(v1, v2, wt)); 33 | graph[v2].add(new Edge(v2, v1, wt)); 34 | } 35 | 36 | // write your code here 37 | int src=0; 38 | 39 | boolean visited[]=new boolean[vtces]; 40 | 41 | for(int i=0;i[] graph,int src,boolean visited[]){ 56 | 57 | Queueq=new ArrayDeque<>(); 58 | q.add(src); 59 | 60 | while(q.size()>0){ 61 | int vtx=q.remove(); 62 | 63 | if(visited[vtx]==false){ 64 | visited[vtx]=true; 65 | 66 | for(Edge e:graph[vtx]){ 67 | int nbr=e.nbr; 68 | if(visited[nbr]==false){ 69 | q.add(nbr); 70 | } 71 | } 72 | }else{ 73 | return true; 74 | } 75 | } 76 | 77 | 78 | return false; 79 | 80 | 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Graph/Is Graph connected.java: -------------------------------------------------------------------------------- 1 | public static void main(String[] args) throws Exception { 2 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 3 | 4 | int vtces = Integer.parseInt(br.readLine()); 5 | ArrayList[] graph = new ArrayList[vtces]; 6 | for (int i = 0; i < vtces; i++) { 7 | graph[i] = new ArrayList<>(); 8 | } 9 | 10 | int edges = Integer.parseInt(br.readLine()); 11 | for (int i = 0; i < edges; i++) { 12 | String[] parts = br.readLine().split(" "); 13 | int v1 = Integer.parseInt(parts[0]); 14 | int v2 = Integer.parseInt(parts[1]); 15 | int wt = Integer.parseInt(parts[2]); 16 | graph[v1].add(new Edge(v1, v2, wt)); 17 | graph[v2].add(new Edge(v2, v1, wt)); 18 | } 19 | int count=0; 20 | boolean[] visited=new boolean[vtces]; 21 | // write your code here 22 | for(int i=0;i[]graph,int src,boolean []visited){ 36 | 37 | visited[src]=true; 38 | for(Edge e:graph[src]){ 39 | int nbr=e.nbr; 40 | if(visited[nbr]==false){ 41 | getComponents(graph,nbr,visited); 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Graph/Multi solver graph.java: -------------------------------------------------------------------------------- 1 | public static void multisolver(ArrayList[] graph, int src, int dest, boolean[] visited, int criteria, int k, String psf, int wsf) { 2 | 3 | if(src==dest){ 4 | 5 | // For shortest path 6 | if(wsflpathwt){ 13 | lpathwt=wsf; 14 | lpath=psf; 15 | } 16 | 17 | // Ceil path 18 | if(wsf>criteria && wsffpathwt){ 25 | fpathwt=wsf; 26 | fpath=psf; 27 | } 28 | 29 | if(pq.size()=arr.length ||j>=arr[0].length ||visited[i][j]==true ||arr[i][j]==1){ 37 | return ; 38 | } 39 | 40 | visited[i][j]=true; 41 | getComp(arr,i,j+1,visited); 42 | getComp(arr,i,j-1,visited); 43 | getComp(arr,i+1,j,visited); 44 | getComp(arr,i-1,j,visited); 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Graph/Perfect Friends.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | static class Edge { 6 | int src; 7 | int nbr; 8 | // int wt; 9 | 10 | Edge(int src, int nbr) { 11 | this.src = src; 12 | this.nbr = nbr; 13 | // this.wt = wt; 14 | } 15 | } 16 | 17 | 18 | public static void main(String[] args) throws Exception { 19 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 20 | 21 | int n = Integer.parseInt(br.readLine()); 22 | int k = Integer.parseInt(br.readLine()); 23 | 24 | // write your code here 25 | ArrayList[] graph = new ArrayList[n]; 26 | for (int i = 0; i < n; i++) { 27 | graph[i] = new ArrayList<>(); 28 | } 29 | 30 | // int edges = Integer.parseInt(br.readLine()); 31 | for (int i = 0; i < k; i++) { 32 | String[] parts = br.readLine().split(" "); 33 | int v1 = Integer.parseInt(parts[0]); 34 | int v2 = Integer.parseInt(parts[1]); 35 | // int wt = Integer.parseInt(parts[2]); 36 | graph[v1].add(new Edge(v1, v2)); 37 | graph[v2].add(new Edge(v2, v1)); 38 | } 39 | 40 | ArrayList> comps = new ArrayList<>(); 41 | boolean[]visited=new boolean[n]; 42 | 43 | for(int i=0;icomp=new ArrayList<>(); 46 | getComponents(graph,i,visited,comp); 47 | comps.add(comp); 48 | } 49 | } 50 | 51 | int ans=0; 52 | 53 | for(int i=0;i[] graph,int src,boolean [] visited,ArrayListcomp){ 64 | visited[src]=true; 65 | comp.add(src); 66 | for(Edge e:graph[src]){ 67 | int nbr=e.nbr; 68 | if(visited[nbr]==false){ 69 | getComponents(graph,nbr,visited,comp); 70 | } 71 | } 72 | 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /Graph/Print all Paths.java: -------------------------------------------------------------------------------- 1 | 2 | public static void allPaths(ArrayListgraph[],int src,int dest,boolean []visited,String psf){ 3 | 4 | if(src==dest){ 5 | System.out.println(psf); 6 | return ; 7 | } 8 | 9 | 10 | visited[src]=true; 11 | 12 | for(Edge e:graph[src]){ 13 | int nbr=e.nbr; 14 | if(visited[nbr]==false){ 15 | allPaths(graph,nbr,dest,visited,psf+nbr); 16 | } 17 | } 18 | 19 | visited[src]=false; 20 | } 21 | -------------------------------------------------------------------------------- /HashMap/Get common elments1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main{ 5 | 6 | public static void main(String[] args) throws Exception { 7 | // write your code here 8 | Scanner scn=new Scanner(System.in); 9 | int n1=scn.nextInt(); 10 | int a1[]=new int[n1]; 11 | 12 | for(int i=0;i store only unique keys 24 | HashSetset=new HashSet<>(); 25 | 26 | // add all a1 array unique values in set 27 | for(int i=0;imap=new HashMap<>(); 28 | 29 | for(int i=0;imap=new HashMap<>(); 13 | 14 | int maxfreq=0; 15 | char maxFreqCharacter='a'; 16 | 17 | for(int i=0;imaxfreq){ 28 | maxfreq=map.get(c); 29 | maxFreqCharacter=c; 30 | } 31 | } 32 | 33 | System.out.println(maxFreqCharacter); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /HashMap/K Largest Elements.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws Exception { 7 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | int n = Integer.parseInt(br.readLine()); 9 | int[] arr = new int[n]; 10 | 11 | for (int i = 0; i < n; i++) { 12 | arr[i] = Integer.parseInt(br.readLine()); 13 | } 14 | 15 | int k = Integer.parseInt(br.readLine()); 16 | 17 | 18 | PriorityQueuepq=new PriorityQueue<>(); 19 | 20 | for(int i=0;ipq.peek()){ 27 | pq.remove(); 28 | pq.add(arr[i]); 29 | } 30 | } 31 | 32 | while(pq.size()>0){ 33 | System.out.println(pq.remove()); 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /HashMap/Longest Consecutive Sequence of elements.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main{ 5 | 6 | public static void main(String[] args) throws Exception { 7 | // write your code here 8 | Scanner scn=new Scanner(System.in); 9 | HashMapmap=new HashMap<>(); 10 | 11 | int n=scn.nextInt(); 12 | 13 | int []arr=new int [n]; 14 | 15 | // Consider all elements as a Sp 16 | for(int i=0;imaxlength){ 42 | maxlength=len; 43 | sp=arr[i]; 44 | } 45 | } 46 | } 47 | 48 | for(int i=0;ipq=new PriorityQueue<>(); 18 | 19 | 20 | for(int i=0;i<=k;i++){ 21 | pq.add(arr[i]); 22 | } 23 | 24 | 25 | for(int i=k+1;i0){ 32 | System.out.println(pq.remove()); 33 | } 34 | 35 | 36 | 37 | // write your code here 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Level-02/Bits Manipulation/1310. XOR Queries of a Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] xorQueries(int[] arr, int[][] queries) { 3 | int n=arr.length; 4 | int prefix[]=new int[n]; 5 | int size=queries.length; 6 | 7 | int answer[]=new int[size]; 8 | 9 | prefix[0]=arr[0]; 10 | 11 | // Making prefix Array 12 | for(int i=1;i " + y); 44 | System.out.println("Repeating Number -> " + x); 45 | break; 46 | } 47 | 48 | if(arr[i] == y){ 49 | System.out.println("Missing Number -> " + x); 50 | System.out.println("Repeating Number -> " + y); 51 | break; 52 | } 53 | } 54 | 55 | 56 | 57 | } 58 | 59 | } 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /Level-02/Bits Manipulation/Pepcoder and Bits.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | public static long ncr(long n, long r){ 6 | if(n < r){ 7 | return 0L; 8 | } 9 | 10 | long res = 1L; 11 | 12 | for(long i = 0L; i < r; i++){ 13 | res = res * (n - i); 14 | res = res / (i + 1); 15 | } 16 | 17 | return res; 18 | } 19 | 20 | public static long solution(long n) { 21 | int count=csb(n); 22 | long ans=0; 23 | for(int i=63;i>=0;i--){ 24 | long mask=1L<0){ 27 | ans+=ncr(i,count); 28 | count--; 29 | } 30 | 31 | } 32 | 33 | return ans; 34 | 35 | } 36 | 37 | public static int csb(long n){ 38 | int res = 0; 39 | 40 | while(n > 0){ 41 | long rsb = n & -n; 42 | n -= rsb; 43 | res++; 44 | } 45 | 46 | return res; 47 | } 48 | 49 | public static void main(String[] args) { 50 | Scanner scn = new Scanner(System.in); 51 | long n = scn.nextLong(); 52 | int k = csb(n); 53 | System.out.println(solution(n)); 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Level-02/Bits Manipulation/Print Binary and Reverse Bits.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args){ 7 | Scanner scn = new Scanner(System.in); 8 | int n = scn.nextInt(); 9 | boolean flag=false; 10 | int reverseAns=0; 11 | int j=0; 12 | //write your code here 13 | for(int i=31;i>=0;i--){ 14 | int mask=1<> 1; 18 | } 19 | else { 20 | if(N == 3) { 21 | count += 2; 22 | break; 23 | } 24 | N = (N & 2) == 2 ? N + 1 : N - 1; 25 | } 26 | count ++; 27 | } 28 | return count; 29 | } 30 | 31 | 32 | } 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Level-02/Bits Manipulation/Solve 7n By 8.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args){ 7 | Scanner scn = new Scanner(System.in); 8 | int n = scn.nextInt(); 9 | //write your code here 10 | 11 | int ans=((n<<3)-n)>>3; 12 | 13 | System.out.println(ans); 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Level-02/Bits Manipulation/Sum Of Bit Differences Of All Pairs.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static long solution(int[] arr){ 7 | //write your code here 8 | long ans=0; 9 | 10 | for(int i=0;i<32;i++){ 11 | long count1=0; 12 | long count0=0; 13 | 14 | for(int j=0;j=j) return 0; 9 | 10 | if(dp[i][j]!=-1){ 11 | return dp[i][j]; 12 | } 13 | 14 | int ans=Integer.MAX_VALUE; 15 | 16 | for(int k=i;ksubAns){ 20 | ans=subAns; 21 | } 22 | 23 | } 24 | 25 | return dp[i][j]= ans; 26 | } 27 | 28 | 29 | static int matrixMultiplication(int N, int arr[]) 30 | { 31 | // code here 32 | int dp[][]=new int[N+1][N+1]; 33 | for(int a[]:dp){ 34 | Arrays.fill(a,-1); 35 | } 36 | 37 | return helper(arr,1,N-1,dp); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Level-02/Dynamic Programming/Matrix Chain Multiplication/recursion.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //User function Template for Java 4 | 5 | class Solution{ 6 | 7 | static int helper(int arr[],int i,int j){ 8 | if(i>=j) return 0; 9 | 10 | int ans=Integer.MAX_VALUE; 11 | 12 | for(int k=i;ksubAns){ 16 | ans=subAns; 17 | } 18 | 19 | } 20 | 21 | return ans; 22 | } 23 | 24 | 25 | static int matrixMultiplication(int N, int arr[]) 26 | { 27 | // code here 28 | return helper(arr,1,N-1); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Level-02/Dynamic Programming/Matrix Chain Multiplication/tabulation.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //User function Template for Java 4 | 5 | class Solution{ 6 | static int matrixMultiplication(int N, int arr[]) 7 | { 8 | 9 | int[][]dp = new int[N-1][N-1]; 10 | 11 | for(int g = 0; g < dp.length ; g++){ 12 | 13 | for(int i = 0 , j= g ; j < dp.length; i++ , j++){ 14 | 15 | if(g == 0) 16 | dp[i][j] = 0; 17 | else if(g == 1) 18 | dp[i][j] = arr[j-1]*arr[j] * arr[j+1]; 19 | else{ 20 | int min = Integer.MAX_VALUE; 21 | for(int k1 = 1 , k2 = g ; k1 <= g && k2 >= 1 ; k1++,k2--){ 22 | int left = dp[i][j-k2]; // arr[i] * arr[j-k2+1]; 23 | int right = dp[i+k1][j]; // arr[i+k1] * arr[j+1]; 24 | int mul = arr[i] * arr[i+k1] * arr[j+1]; 25 | 26 | min = Math.min(min , left + right +mul); 27 | } 28 | 29 | dp[i][j] = min; 30 | } 31 | 32 | 33 | } 34 | 35 | } 36 | 37 | 38 | return dp[0][dp[0].length-1]; 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Level-02/Dynamic Programming/Minimum Insertion Steps to Make a String Palindrome/tabulation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minInsertions(String s) { 3 | int n=s.length(); 4 | 5 | int dp[][]=new int[n+1][n+1]; 6 | 7 | String reverse=""; 8 | for(int i=n-1;i>=0;i--){ 9 | reverse+=s.charAt(i); 10 | } 11 | 12 | 13 | for(int i=1;i<=n;i++){ 14 | for(int j=1;j<=n;j++){ 15 | if(s.charAt(i-1)==reverse.charAt(j-1)){ 16 | dp[i][j]=dp[i-1][j-1]+1; 17 | }else{ 18 | dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]); 19 | } 20 | } 21 | } 22 | 23 | return n-dp[n][n]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Level-02/Dynamic Programming/Palindromic Partitioning/memoization.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //User function Template for Java 4 | 5 | class Solution{ 6 | static boolean isPalindrome(String str,int left,int right){ 7 | 8 | while(left=j){ 22 | return dp[i][j]= 0; 23 | } 24 | 25 | if(dp[i][j]!=-1){ 26 | return dp[i][j]; 27 | } 28 | 29 | if(isPalindrome(str,i,j)==true){ 30 | return dp[i][j]=0; 31 | } 32 | 33 | 34 | int ans=Integer.MAX_VALUE; 35 | 36 | for(int k=i;k=j){ 22 | return 0; 23 | } 24 | 25 | if(isPalindrome(str,i,j)==true){ 26 | return 0; 27 | } 28 | 29 | int ans=Integer.MAX_VALUE; 30 | 31 | for(int k=i;k0){ 10 | System.out.println(asf+count); 11 | }else { 12 | System.out.println(asf); 13 | } 14 | 15 | return ; 16 | } 17 | 18 | 19 | //YES 20 | char ch=str.charAt(idx); 21 | if(count>0){ 22 | solution(str,asf+count+ch,0,idx+1); 23 | }else { 24 | solution(str,asf+ch,0,idx+1); 25 | } 26 | 27 | // solution(str,asf+(count>0?count:"")+ch,0,idx+1); 28 | 29 | solution(str,asf,count+1,idx+1); 30 | 31 | } 32 | public static void main(String[] args) { 33 | Scanner scn = new Scanner(System.in); 34 | String str = scn.nextLine(); 35 | solution(str,"",0,0); 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/All Palindromic Partitions.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | public static boolean isPalindrome(String str){ 6 | int left=0; 7 | int right=str.length()-1; 8 | 9 | while(left fmap = new HashMap<>(); 10 | for (int i = 0; i < str.length(); i++) { 11 | char ch = str.charAt(i); 12 | fmap.put(ch, fmap.getOrDefault(ch, 0) + 1); 13 | } 14 | int ofc = 0; 15 | Character oddchar = null; 16 | int length = 0; 17 | for (int i = 0; i < 26; i++) { 18 | char ch = (char) ('a' + i); 19 | if (fmap.containsKey(ch)) { 20 | int freq = fmap.get(ch); 21 | if (freq % 2 != 0) { 22 | oddchar = ch; 23 | ofc++; 24 | } 25 | if (ofc > 1) { 26 | System.out.println("-1"); 27 | return; 28 | } 29 | fmap.put(ch, freq / 2); 30 | length += (freq / 2); 31 | } 32 | } 33 | generatepw(1, length, fmap, oddchar, ""); 34 | 35 | } 36 | 37 | public static void generatepw(int cs, int ts, HashMap fmap, Character oddc, String asf) { 38 | if (cs == ts + 1) { 39 | System.out.println(asf + (oddc == null ? "" : oddc) + reverse(asf)); 40 | return; 41 | } 42 | 43 | for (char ch : fmap.keySet()) { 44 | if (fmap.get(ch) > 0) { 45 | fmap.put(ch, fmap.get(ch) - 1); 46 | generatepw(cs + 1, ts, fmap,oddc, asf + ch); 47 | fmap.put(ch, fmap.get(ch) + 1); 48 | } 49 | } 50 | } 51 | 52 | public static String reverse(String str) { 53 | StringBuilder ans = new StringBuilder(); 54 | for(int i = str.length() - 1; i >= 0 ; i--) { 55 | ans.append(str.charAt(i)); 56 | } 57 | return ans.toString(); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Coin Change - Combinations - 1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void coinChange(int i, int[] coins, int amtsf, int tamt, String asf){ 7 | // write your code here 8 | 9 | if(i==coins.length){ 10 | if(amtsf==tamt){ 11 | System.out.println(asf+"."); 12 | } 13 | return ; 14 | } 15 | 16 | //Yes 17 | 18 | coinChange(i+1,coins,amtsf+coins[i],tamt,asf+coins[i]+"-"); 19 | //No 20 | coinChange(i+1,coins,amtsf,tamt,asf); 21 | 22 | 23 | } 24 | public static void main(String[] args) throws Exception { 25 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 26 | int n = Integer.parseInt(br.readLine()); 27 | int[] coins = new int[n]; 28 | for (int i = 0; i < n; i++) { 29 | coins[i] = Integer.parseInt(br.readLine()); 30 | } 31 | int amt = Integer.parseInt(br.readLine()); 32 | 33 | coinChange(0, coins, 0, amt, ""); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Coin Change - Combinations - 2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void coinChange(int i, int[] coins, int amtsf, int tamt, String asf) { 7 | // write your code here 8 | 9 | if(amtsf>tamt){ 10 | return; 11 | } 12 | 13 | if(i==coins.length){ 14 | if(amtsf==tamt){ 15 | System.out.println(asf+"."); 16 | } 17 | return ; 18 | } 19 | 20 | // YES 21 | coinChange(i,coins,amtsf+coins[i],tamt,asf+coins[i]+"-"); 22 | // NO 23 | coinChange(i+1,coins,amtsf,tamt,asf); 24 | } 25 | 26 | public static void main(String[] args) throws Exception { 27 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 28 | int n = Integer.parseInt(br.readLine()); 29 | int[] coins = new int[n]; 30 | for (int i = 0; i < n; i++) { 31 | coins[i] = Integer.parseInt(br.readLine()); 32 | } 33 | int amt = Integer.parseInt(br.readLine()); 34 | coinChange(0, coins, 0, amt, ""); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Coin Change - Permutations - 1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void coinChange(int[] coins, int amtsf, int tamt, String asf, boolean[] used){ 7 | // write your code here 8 | 9 | if(amtsf==tamt){ 10 | System.out.println(asf+"."); 11 | return; 12 | } 13 | 14 | for(int i=0;itamt){ 10 | return; 11 | } 12 | 13 | if(amtsf==tamt){ 14 | System.out.println(asf+"."); 15 | return ; 16 | } 17 | 18 | 19 | for(int i=0;itb){ 9 | if(ssf==ts){ 10 | System.out.println(asf); 11 | } 12 | return ; 13 | } 14 | 15 | 16 | // Consider an element 17 | combinations(cb+1,tb,ssf+1,ts,asf+"i"); 18 | 19 | // Not consider an element 20 | combinations(cb+1,tb,ssf,ts,asf+"-"); 21 | } 22 | 23 | public static void main(String[] args) throws Exception { 24 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 25 | int nboxes = Integer.parseInt(br.readLine()); 26 | int ritems = Integer.parseInt(br.readLine()); 27 | combinations(1, nboxes, 0, ritems, ""); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Combinations-2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void combinations(int[] boxes, int ci, int ti, int lb){ 7 | // write your code here 8 | if(ci>ti){ 9 | for(int i=0;i charIntMap = new HashMap<>(); 13 | String unique = ""; 14 | for (int i = 0; i < s1.length(); i++) { 15 | if (!charIntMap.containsKey(s1.charAt(i))) { 16 | charIntMap.put(s1.charAt(i), -1); 17 | unique += s1.charAt(i); 18 | } 19 | } 20 | 21 | for (int i = 0; i < s2.length(); i++) { 22 | if (!charIntMap.containsKey(s2.charAt(i))) { 23 | charIntMap.put(s2.charAt(i), -1); 24 | unique += s2.charAt(i); 25 | } 26 | } 27 | 28 | for (int i = 0; i < s3.length(); i++) { 29 | if (!charIntMap.containsKey(s3.charAt(i))) { 30 | charIntMap.put(s3.charAt(i), -1); 31 | unique += s3.charAt(i); 32 | } 33 | } 34 | 35 | boolean[] usedNumbers = new boolean[10]; 36 | solution(unique, 0, charIntMap, usedNumbers, s1, s2, s3); 37 | } 38 | 39 | public static int getValue(String s,HashMapmap){ 40 | 41 | int ans=0; 42 | int power=1; 43 | for(int i=s.length()-1;i>=0;i--){ 44 | char ch=s.charAt(i); 45 | int mapping=map.get(ch); 46 | ans+=(mapping *power); 47 | power*=10; 48 | } 49 | 50 | return ans; 51 | 52 | } 53 | public static void solution(String unique, int idx, 54 | HashMap map, boolean[] usedNumbers, 55 | String s1, String s2, String s3) { 56 | // write your code here 57 | 58 | if(idx==unique.length()){ 59 | 60 | if((getValue(s1,map)+getValue(s2,map))==getValue(s3,map)){ 61 | for(int i=0;i<26;i++){ 62 | char ch=(char)(i+'a'); 63 | if(map.containsKey(ch)==true){ 64 | System.out.print(ch+"-"+map.get(ch)+" "); 65 | } 66 | } 67 | 68 | System.out.println(); 69 | } 70 | return ; 71 | } 72 | 73 | 74 | char ch=unique.charAt(idx); 75 | 76 | for(int i=0;i<=9;i++){ 77 | if(usedNumbers[i]==false){ 78 | usedNumbers[i]=true; 79 | map.put(ch,i); 80 | solution(unique,idx+1,map,usedNumbers,s1,s2,s3); 81 | usedNumbers[i]=false; 82 | map.remove(ch); 83 | } 84 | } 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Friends Pairing - 2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | static int counter = 1; 6 | 7 | public static void solution(int i, int n, boolean[] used, String asf) { 8 | // write your code here 9 | 10 | if(i==n){ 11 | System.out.println(counter+"."+asf); 12 | counter++; 13 | return ; 14 | } 15 | 16 | if(used[i]==true){ 17 | solution(i+1,n,used,asf); 18 | }else{ 19 | // Single 20 | used[i]=true; 21 | solution(i+1,n,used,asf+"("+(i+1)+") "); 22 | 23 | // Pair 24 | for(int j=0;j n || sum % k != 0) { 27 | System.out.println("-1"); 28 | return; 29 | } 30 | int[] subsetSum = new int[k]; 31 | ArrayList> ans = new ArrayList<>(); 32 | for(int i = 0; i < k; i++) { 33 | ans.add(new ArrayList<>()); 34 | } 35 | solution(arr,0,n,k,subsetSum,0,ans); 36 | } 37 | 38 | public static void solution(int[] arr, int vidx,int n , int k,int[] subsetSum,int ssssf, ArrayList> ans) { 39 | if(vidx == arr.length) { 40 | if(ssssf == k) { 41 | int isum = subsetSum[0]; 42 | boolean flag = true; 43 | for(int i = 1 ;i < subsetSum.length; i++) { 44 | if(subsetSum[i] == isum) { 45 | continue; 46 | }else { 47 | flag = false; 48 | break; 49 | } 50 | } 51 | if(flag == true) { 52 | for(ArrayList a : ans) { 53 | System.out.print(a + " "); 54 | } 55 | System.out.println(); 56 | } 57 | } 58 | return; 59 | } 60 | 61 | for(int j = 0 ; j < ans.size(); j++) { 62 | if(ans.get(j).size() == 0) { 63 | ans.get(j).add(arr[vidx]); 64 | subsetSum[j] += arr[vidx]; 65 | solution(arr,vidx + 1,n,k,subsetSum,ssssf + 1,ans); 66 | ans.get(j).remove(ans.get(j).size() - 1); 67 | subsetSum[j] -= arr[vidx]; 68 | break; 69 | }else { 70 | ans.get(j).add(arr[vidx]); 71 | subsetSum[j] += arr[vidx]; 72 | solution(arr,vidx + 1,n,k,subsetSum,ssssf,ans); 73 | ans.get(j).remove(ans.get(j).size() - 1); 74 | subsetSum[j] -= arr[vidx]; 75 | } 76 | } 77 | } 78 | 79 | } 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/K-partitions.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | Scanner scn = new Scanner(System.in); 8 | int n = scn.nextInt(); 9 | int k = scn.nextInt(); 10 | ArrayList> ans = new ArrayList<>(); 11 | for(int i = 0; i < k; i++) { 12 | ans.add(new ArrayList<>()); 13 | } 14 | solution(1, n, k, 0, ans); 15 | 16 | } 17 | 18 | static int counter = 1; 19 | public static void solution(int i, int n, int k, int rssf, ArrayList> ans) { 20 | if (i == n + 1) { 21 | if (rssf == k) { 22 | System.out.print(counter + ". "); 23 | counter++; 24 | for(ArrayList a : ans) { 25 | System.out.print(a + " "); 26 | } 27 | System.out.println(); 28 | } 29 | return; 30 | } 31 | 32 | for(int j = 0 ; j < ans.size(); j++) { 33 | if(ans.get(j).size() == 0) { 34 | ans.get(j).add(i); 35 | solution(i + 1,n,k,rssf + 1,ans); 36 | ans.get(j).remove(ans.get(j).size() - 1); 37 | break; 38 | }else { 39 | ans.get(j).add(i); 40 | solution(i + 1, n, k, rssf, ans); 41 | ans.get(j).remove(ans.get(j).size() - 1); 42 | } 43 | } 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Largest Number Possible After At Most K Swaps.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | public static String swap(String str,int i,int j){ 6 | 7 | char chi=str.charAt(i); 8 | char chj=str.charAt(j); 9 | 10 | String left=str.substring(0,i); 11 | String mid=str.substring(i+1,j); 12 | String right=str.substring(j+1); 13 | 14 | 15 | return left+chj+mid+chi+right; 16 | 17 | } 18 | static String max; 19 | public static void findMaximum(String str, int k) { 20 | //write your code here 21 | 22 | if(Integer.parseInt(str)>Integer.parseInt(max)){ 23 | max=str; 24 | } 25 | 26 | if(k==0){ 27 | return; 28 | } 29 | 30 | 31 | for(int i=0;i n){ 15 | return; 16 | } 17 | else{ 18 | System.out.println(cur); 19 | for(int i = 0;i < 10;i++){ 20 | dfs(10 * cur + i, n); 21 | } 22 | } 23 | } 24 | } 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Max Score.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static int solution(String[] words, int[] farr, int[] score, int idx) { 7 | //write your code here 8 | if(idx==words.length){ 9 | return 0; 10 | } 11 | 12 | // NO 13 | int ans1=solution(words,farr,score,idx+1); 14 | 15 | // YES 16 | int ans2=0; 17 | 18 | boolean isWordPossible=true; 19 | int scoreOfCurrentWord=0; 20 | 21 | for(int i=0;i= 0 && j - 2 >= 0 && chess[i - 1][j - 2]){ 8 | return false; 9 | } 10 | 11 | if(i - 2 >= 0 && j - 1 >= 0 && chess[i - 2][j - 1]){ 12 | return false; 13 | } 14 | 15 | if(i - 2 >= 0 && j + 1 < chess.length && chess[i - 2][j + 1]){ 16 | return false; 17 | } 18 | 19 | if(i - 1 >= 0 && j + 2 < chess.length && chess[i - 1][j + 2]){ 20 | return false; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | public static void nknights(int kpsf, int tk, boolean[][] chess, int lcno) { 27 | if (kpsf == tk) { 28 | for (int row = 0; row < chess.length; row++) { 29 | for (int col = 0; col < chess.length; col++) { 30 | System.out.print(chess[row][col] ? "k\t" : "-\t"); 31 | } 32 | System.out.println(); 33 | } 34 | System.out.println(); 35 | return; 36 | } 37 | 38 | for (int i = lcno + 1; i < chess.length * chess.length; i++) { 39 | int row = i / chess.length; 40 | int col = i % chess.length; 41 | 42 | if (chess[row][col] == false && IsKnightSafe(chess, row, col)) { 43 | chess[row][col] = true; 44 | nknights(kpsf + 1, tk, chess, row * chess.length + col); 45 | chess[row][col] = false; 46 | } 47 | } 48 | } 49 | 50 | public static void main(String[] args) throws Exception { 51 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 52 | int n = Integer.parseInt(br.readLine()); 53 | boolean[][] chess = new boolean[n][n]; 54 | 55 | nknights(0, n, chess, -1); 56 | } 57 | } 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Nqueens Combinations - 2d As 1d - Queen Chooses.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static boolean IsQueenSafe(boolean[][] chess, int row, int col) { 7 | // vertical 8 | for (int i = row, j = col; i >= 0; i--) { 9 | if(chess[i][j]){ 10 | return false; 11 | } 12 | } 13 | 14 | // horizontal 15 | for (int i = row, j = col; j >= 0; j--) { 16 | if(chess[i][j]){ 17 | return false; 18 | } 19 | } 20 | 21 | // diagonal 22 | for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { 23 | if(chess[i][j]){ 24 | return false; 25 | } 26 | } 27 | 28 | // anti-diagonal 29 | for (int i = row, j = col; i >= 0 && j < chess.length; i--, j++) { 30 | if(chess[i][j]){ 31 | return false; 32 | } 33 | } 34 | 35 | return true; 36 | } 37 | 38 | public static void nqueens(int qpsf, int tq, boolean[][] chess, int lcno) { 39 | if (qpsf == tq) { 40 | for (int row = 0; row < chess.length; row++) { 41 | for (int col = 0; col < chess.length; col++) { 42 | System.out.print(chess[row][col] ? "q\t" : "-\t"); 43 | } 44 | System.out.println(); 45 | } 46 | System.out.println(); 47 | return; 48 | } 49 | 50 | for (int i = lcno + 1; i < chess.length * chess.length; i++) { 51 | int row = i / chess.length; 52 | int col = i % chess.length; 53 | 54 | if (chess[row][col] == false && IsQueenSafe(chess, row, col)) { 55 | chess[row][col] = true; 56 | nqueens(qpsf + 1, tq, chess, row * chess.length + col); 57 | chess[row][col] = false; 58 | } 59 | } 60 | } 61 | 62 | public static void main(String[] args) throws Exception { 63 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 64 | int n = Integer.parseInt(br.readLine()); 65 | boolean[][] chess = new boolean[n][n]; 66 | 67 | nqueens(0, n, chess, -1); 68 | } 69 | } 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Nqueens Permutations - 2d As 1d - Queen Chooses.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static boolean IsQueenSafe(int[][] chess, int row, int col) { 7 | // vertical 8 | for (int i = row, j = col; i >= 0; i--) { 9 | if(chess[i][j] > 0){ 10 | return false; 11 | } 12 | } 13 | 14 | for (int i = row, j = col; i < chess.length; i++) { 15 | if(chess[i][j] > 0){ 16 | return false; 17 | } 18 | } 19 | 20 | // horizontal 21 | for (int i = row, j = col; j >= 0; j--) { 22 | if(chess[i][j] > 0){ 23 | return false; 24 | } 25 | } 26 | 27 | for (int i = row, j = col; j < chess.length; j++) { 28 | if(chess[i][j] > 0){ 29 | return false; 30 | } 31 | } 32 | 33 | // diagonal 34 | for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { 35 | if(chess[i][j] > 0){ 36 | return false; 37 | } 38 | } 39 | 40 | for (int i = row, j = col; i < chess.length && j < chess.length; i++, j++) { 41 | if(chess[i][j] > 0){ 42 | return false; 43 | } 44 | } 45 | 46 | // anti-diagonal 47 | for (int i = row, j = col; i >= 0 && j < chess.length; i--, j++) { 48 | if(chess[i][j] > 0){ 49 | return false; 50 | } 51 | } 52 | 53 | for (int i = row, j = col; i < chess.length && j >= 0; i++, j--) { 54 | if(chess[i][j] > 0){ 55 | return false; 56 | } 57 | } 58 | 59 | return true; 60 | } 61 | 62 | public static void nqueens(int qpsf, int tq, int[][] chess) { 63 | if (qpsf == tq) { 64 | for (int row = 0; row < chess.length; row++) { 65 | for (int col = 0; col < chess.length; col++) { 66 | System.out.print(chess[row][col] > 0 ? "q"+ chess[row][col] + "\t" : "-\t"); 67 | } 68 | System.out.println(); 69 | } 70 | System.out.println(); 71 | return; 72 | } 73 | 74 | for (int i = 0; i < chess.length * chess.length; i++) { 75 | int row = i / chess.length; 76 | int col = i % chess.length; 77 | 78 | if (chess[row][col] == 0 && IsQueenSafe(chess, row, col)) { 79 | chess[row][col] = qpsf + 1; 80 | nqueens(qpsf + 1, tq, chess); 81 | chess[row][col] = 0; 82 | } 83 | } 84 | } 85 | 86 | public static void main(String[] args) throws Exception { 87 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 88 | int n = Integer.parseInt(br.readLine()); 89 | int[][] chess = new int[n][n]; 90 | 91 | nqueens(0, n, chess); 92 | } 93 | } 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Pattern Matching.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | Scanner scn = new Scanner(System.in); 8 | String str = scn.next(); 9 | String pattern = scn.next(); 10 | HashMap map = new HashMap<>(); 11 | solution(str,pattern,map,pattern); 12 | } 13 | 14 | public static void solution(String str, String pattern, HashMap map, String op){ 15 | if(pattern.length() == 0){ 16 | if(str.length() == 0){ 17 | boolean[] arr = new boolean[26]; 18 | for(int i = 0 ; i < op.length(); i++) { 19 | char ch = op.charAt(i); 20 | if(arr[ch - 'a'] == false) { 21 | arr[ch - 'a'] = true; 22 | System.out.print(ch + " -> " + map.get(ch) + ", "); 23 | } 24 | } 25 | System.out.println("."); 26 | } 27 | return; 28 | } 29 | 30 | char chp = pattern.charAt(0); 31 | String rop = pattern.substring(1); 32 | 33 | if(!map.containsKey(chp)){ 34 | //if character is coming for the first time 35 | for(int i = 0 ; i < str.length(); i++){ 36 | String fh = str.substring(0, i + 1); 37 | String ros = str.substring(i + 1); 38 | 39 | map.put(chp, fh); 40 | solution(ros,rop,map,op); 41 | map.remove(chp); 42 | } 43 | }else{ 44 | //if character has already appeared 45 | String prevmatching = map.get(chp); 46 | String nextsubstring = str.length() >= prevmatching.length() ? str.substring(0, prevmatching.length()) : "-1"; 47 | if(prevmatching.equals(nextsubstring)){ 48 | String ros = str.substring(prevmatching.length()); 49 | solution(ros, rop, map,op); 50 | } 51 | } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Permutation-1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void permutations(int[] boxes, int ci, int ti){ 7 | // write your code here 8 | 9 | if(ci>ti){ 10 | for(int i=0;itb){ 9 | if(ssf==ts){ 10 | System.out.println(asf); 11 | } 12 | return ; 13 | } 14 | 15 | 16 | // YES call -> multiple choices 17 | for(int i=0;i fmap, String asf) { 7 | if(cs > ts){ 8 | System.out.println(asf); 9 | return; 10 | } 11 | 12 | for (char ch : fmap.keySet()) { 13 | if (fmap.get(ch) > 0) { 14 | fmap.put(ch, fmap.get(ch) - 1); 15 | generateWords(cs + 1, ts, fmap, asf + ch); 16 | fmap.put(ch, fmap.get(ch) + 1); 17 | } 18 | } 19 | } 20 | 21 | public static void main(String[] args) throws Exception { 22 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 23 | String str = br.readLine(); 24 | 25 | HashMap fmap = new HashMap<>(); 26 | for(char ch: str.toCharArray()){ 27 | if(fmap.containsKey(ch)){ 28 | fmap.put(ch, fmap.get(ch) + 1); 29 | } else { 30 | fmap.put(ch, 1); 31 | } 32 | } 33 | 34 | generateWords(1, str.length(), fmap, ""); 35 | } 36 | 37 | } 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Permutations - Words - 2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void generateWords(int cc, String str, Character[] spots, 7 | HashMap lastOccurence) { 8 | if(cc == str.length()){ 9 | for(char ch: spots){ 10 | System.out.print(ch); 11 | } 12 | System.out.println(); 13 | return; 14 | } 15 | 16 | char ch = str.charAt(cc); 17 | int lo = lastOccurence.get(ch); 18 | for(int i = lo + 1; i < spots.length; i++){ 19 | if(spots[i] == null){ 20 | spots[i] = ch; 21 | lastOccurence.put(ch, i); 22 | generateWords(cc + 1, str, spots, lastOccurence); 23 | lastOccurence.put(ch, lo); 24 | spots[i] = null; 25 | } 26 | } 27 | } 28 | 29 | public static void main(String[] args) throws Exception { 30 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 31 | String str = br.readLine(); 32 | 33 | Character[] spots = new Character[str.length()]; 34 | HashMap lastOccurence = new HashMap<>(); 35 | for(char ch: str.toCharArray()){ 36 | lastOccurence.put(ch, -1); 37 | } 38 | 39 | generateWords(0, str, spots, lastOccurence); 40 | } 41 | 42 | } 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Queens Combinations - 2d As 1d - Queen Chooses.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void queensCombinations(int qpsf, int tq, boolean[][] chess, int lcno) { 7 | // write your code here 8 | 9 | if(qpsf==tq){ 10 | for(int i=0;imulitple calls 25 | for(int i=0;i ans) { 7 | //write your code here 8 | 9 | 10 | if(minRemoval==0){ 11 | if(getMin(str)==0) // balanced brackets 12 | { 13 | if(ans.contains(str)==false){ 14 | System.out.println(str); 15 | ans.add(str); 16 | } 17 | } 18 | return ; 19 | } 20 | 21 | for(int i=0;ist=new Stack<>(); 33 | 34 | for(int i=0;i0 && st.peek()=='('){ 40 | st.pop(); 41 | }else { 42 | st.push(ch); 43 | } 44 | } 45 | } 46 | return st.size(); 47 | } 48 | public static void main(String[] args) { 49 | Scanner scn = new Scanner(System.in); 50 | String str = scn.next(); 51 | solution(str, getMin(str),new HashSet<>()); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Solve Sudoku.java: -------------------------------------------------------------------------------- 1 | // import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | public static void display(int[][] board){ 6 | for(int i = 0; i < board.length; i++){ 7 | for(int j = 0; j < board[0].length; j++){ 8 | System.out.print(board[i][j] + " "); 9 | } 10 | System.out.println(); 11 | } 12 | } 13 | 14 | 15 | public static boolean isoptionValid(int [][]board,int i,int j,int val){ 16 | // Row 17 | for(int k=0;k<9;k++){ 18 | if(board[i][k]==val){ 19 | return false; 20 | } 21 | } 22 | 23 | // Col 24 | 25 | for(int k=0;k<9;k++){ 26 | if(board[k][j]==val){ 27 | return false; 28 | } 29 | } 30 | 31 | 32 | // 3*3 grid 33 | 34 | i=i/3*3; 35 | j=j/3*3; 36 | 37 | 38 | for(int k=0;k<3;k++){ 39 | for(int l=0;l<3;l++){ 40 | if(board[k+i][l+j]==val){ 41 | return false; 42 | } 43 | } 44 | } 45 | 46 | return true; 47 | 48 | } 49 | public static void solveSudoku(int[][] board, int i, int j) { 50 | // write yopur code here 51 | if(j==9){ 52 | j=0; 53 | i++; 54 | } 55 | 56 | if(i==9){ // Base case 57 | display(board); 58 | return; 59 | } 60 | 61 | 62 | if(board[i][j]!=0){ 63 | solveSudoku(board,i,j+1); 64 | }else{ 65 | for(int val=1;val<=9;val++){ 66 | if(isoptionValid(board,i,j,val)==true){ 67 | board[i][j]=val; 68 | solveSudoku(board,i,j+1); 69 | board[i][j]=0; 70 | } 71 | } 72 | } 73 | 74 | } 75 | 76 | public static void main(String[] args) throws Exception { 77 | Scanner scn = new Scanner(System.in); 78 | int[][] arr = new int[9][9]; 79 | for (int i = 0; i < 9; i++) { 80 | for (int j = 0; j < 9; j++) { 81 | arr[i][j] = scn.nextInt(); 82 | } 83 | } 84 | 85 | solveSudoku(arr, 0, 0); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Tug Of War.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | Scanner scn = new Scanner(System.in); 8 | int[] arr = new int[scn.nextInt()]; 9 | for (int i = 0; i < arr.length; i++) { 10 | arr[i] = scn.nextInt(); 11 | } 12 | solve(arr, 0, new ArrayList<>(), new ArrayList<>(), 0, 0); 13 | System.out.println(ans); 14 | } 15 | 16 | static int mindiff = Integer.MAX_VALUE; 17 | static String ans = ""; 18 | 19 | public static void solve(int[] arr, int vidx, ArrayList set1, ArrayList set2, int soset1, 20 | int soset2) { 21 | //write your code hereset 22 | if(vidx==arr.length){ 23 | int diff=Math.abs(soset1-soset2); 24 | if(diff dict = new HashSet<>(); 10 | for(int i = 0 ; i < n; i++){ 11 | dict.add(scn.next()); 12 | } 13 | String sentence = scn.next(); 14 | wordBreak(sentence,"", dict); 15 | } 16 | 17 | public static void wordBreak(String str, String ans, HashSet dict){ 18 | // write your code here 19 | 20 | if(str.length()==0){ 21 | System.out.println(ans); 22 | } 23 | 24 | for(int i=0;i unique = new HashSet<>(); 14 | String ustr = ""; 15 | for (char ch : str.toCharArray()) { 16 | if (unique.contains(ch) == false) { 17 | unique.add(ch); 18 | ustr += ch; 19 | } 20 | } 21 | 22 | boolean used[]= new boolean [ustr.length()]; 23 | 24 | words1(ustr,0,new Character[k],0,k); 25 | 26 | } 27 | 28 | 29 | public static void words1(String ustr,int cc,Character[]spots,int ssf,int ts){ 30 | 31 | if(cc==ustr.length()){ 32 | if(ssf==ts){ 33 | for(int i=0;i unique = new HashSet<>(); 14 | String ustr = ""; 15 | for (char ch : str.toCharArray()) { 16 | if (unique.contains(ch) == false) { 17 | unique.add(ch); 18 | ustr += ch; 19 | } 20 | } 21 | 22 | boolean used[]= new boolean [ustr.length()]; 23 | 24 | words1(ustr,0,k,used,""); 25 | 26 | } 27 | 28 | 29 | public static void words1(String ustr,int cs,int ts,boolean []used,String asf){ 30 | 31 | if(cs==ts){ 32 | System.out.println(asf); 33 | return ; 34 | } 35 | 36 | 37 | for(int i=0;i lastOccurence) { 8 | if (cc == str.length()) { 9 | if (ssf == ts) { 10 | for (char ch : spots) { 11 | System.out.print(ch); 12 | } 13 | System.out.println(); 14 | } 15 | return; 16 | } 17 | 18 | char ch = str.charAt(cc); 19 | int lo = lastOccurence.get(ch); 20 | for (int i = lo + 1; i < spots.length; i++) { 21 | if (spots[i] == null) { 22 | spots[i] = ch; 23 | lastOccurence.put(ch, i); 24 | generateWords(cc + 1, str, ssf + 1, ts, spots, lastOccurence); 25 | lastOccurence.put(ch, lo); 26 | spots[i] = null; 27 | } 28 | } 29 | if (lastOccurence.get(ch) == -1) { 30 | generateWords(cc + 1, str, ssf + 0, ts, spots, lastOccurence); 31 | } 32 | } 33 | 34 | public static void main(String[] args) throws Exception { 35 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 36 | String str = br.readLine(); 37 | int k = Integer.parseInt(br.readLine()); 38 | 39 | Character[] spots = new Character[k]; 40 | HashMap lastOccurence = new HashMap<>(); 41 | for (char ch : str.toCharArray()) { 42 | lastOccurence.put(ch, -1); 43 | } 44 | 45 | generateWords(0, str, 0, k, spots, lastOccurence); 46 | } 47 | 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Words - K Length Words - 4.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void generateWords(int cs, int ts, String ustr, HashMap unique, String asf) { 7 | if (cs > ts) { 8 | System.out.println(asf); 9 | return; 10 | } 11 | 12 | for (int i = 0; i < ustr.length(); i++) { 13 | char ch = ustr.charAt(i); 14 | 15 | if (unique.get(ch) > 0) { 16 | unique.put(ch, unique.get(ch) - 1); 17 | generateWords(cs + 1, ts, ustr, unique, asf + ch); 18 | unique.put(ch, unique.get(ch) + 1); 19 | } 20 | } 21 | } 22 | 23 | public static void main(String[] args) throws Exception { 24 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 25 | String str = br.readLine(); 26 | int k = Integer.parseInt(br.readLine()); 27 | 28 | HashMap unique = new HashMap<>(); 29 | String ustr = ""; 30 | for (char ch : str.toCharArray()) { 31 | if (unique.containsKey(ch) == false) { 32 | unique.put(ch, 1); 33 | ustr += ch; 34 | } else { 35 | unique.put(ch, unique.get(ch) + 1); 36 | } 37 | } 38 | 39 | generateWords(1, k, ustr, unique, ""); 40 | } 41 | 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Words - K Selection - 1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | 7 | public static void main(String[] args) throws Exception { 8 | Scanner scn = new Scanner(System.in); 9 | String str = scn.nextLine(); 10 | int k = scn.nextInt(); 11 | 12 | HashSet unique = new HashSet<>(); 13 | String ustr = ""; 14 | for (char ch : str.toCharArray()) { 15 | if (unique.contains(ch) == false) { 16 | unique.add(ch); 17 | ustr += ch; 18 | } 19 | } 20 | 21 | combination(0, ustr, 0, k, ""); 22 | } 23 | 24 | 25 | public static void combination(int i, String ustr, int ssf, int ts, String asf ) { 26 | 27 | if(i==ustr.length()){ 28 | if(ssf==ts){ 29 | System.out.println(asf); 30 | } 31 | return ; 32 | } 33 | 34 | char ch=ustr.charAt(i); 35 | combination(i+1,ustr,ssf+1,ts,asf+ch); 36 | combination(i+1,ustr,ssf,ts,asf); 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/Words - K Selection - 2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args){ 7 | Scanner scn=new Scanner(System.in); 8 | 9 | String str=scn.next(); 10 | 11 | int k=scn.nextInt(); 12 | 13 | HashSet unique = new HashSet<>(); 14 | String ustr = ""; 15 | for (char ch : str.toCharArray()) { 16 | if (unique.contains(ch) == false) { 17 | unique.add(ch); 18 | ustr += ch; 19 | } 20 | } 21 | 22 | selection2(ustr,0,k,"",-1); 23 | 24 | } 25 | 26 | public static void selection2(String ustr,int cs,int ts,String asf,int lcu){ 27 | 28 | if(cs==ts){ 29 | System.out.println(asf); 30 | return ; 31 | } 32 | 33 | for(int i=lcu+1;i unique = new HashMap<>(); 13 | String ustr = ""; 14 | for (char ch : str.toCharArray()) { 15 | if (unique.containsKey(ch) == false) { 16 | unique.put(ch, 1); 17 | ustr += ch; 18 | } else { 19 | unique.put(ch, unique.get(ch) + 1); 20 | } 21 | } 22 | 23 | selection3(ustr,unique,0,0,k,""); 24 | 25 | } 26 | 27 | public static void selection3(String ustr,HashMapunique,int cc,int ssf,int ts,String asf){ 28 | 29 | if(ssf>ts) return; 30 | 31 | if(cc==ustr.length()){ 32 | if(ssf==ts){ 33 | System.out.println(asf); 34 | } 35 | 36 | return ; 37 | } 38 | 39 | 40 | char ch=ustr.charAt(cc); 41 | int freq=unique.get(ch); 42 | 43 | // Yes 44 | for(int i=freq;i>=0;i--){ 45 | String substr=""; 46 | 47 | for(int j=0;j unique = new HashMap<>(); 14 | String ustr = ""; 15 | for (char ch : str.toCharArray()) { 16 | if (unique.containsKey(ch) == false) { 17 | unique.put(ch, 1); 18 | ustr += ch; 19 | } else { 20 | unique.put(ch, unique.get(ch) + 1); 21 | } 22 | } 23 | 24 | selection4(ustr,unique,0,k,"",0); 25 | 26 | 27 | } 28 | 29 | 30 | public static void selection4(String ustr,HashMapmap,int cs,int ts,String asf,int lcu){ 31 | 32 | if(cs==ts){ 33 | System.out.println(asf); 34 | return ; 35 | } 36 | 37 | 38 | for(int i=lcu;i0){ 42 | map.put(ch,map.get(ch)-1); 43 | selection4(ustr,map,cs+1,ts,asf+ch,i); 44 | map.put(ch,map.get(ch)+1); 45 | } 46 | } 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Level-02/Recursion and Backtracking/nqueen branch and bound.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Scanner scn = new Scanner(System.in); 8 | int n = scn.nextInt(); 9 | boolean[][] board = new boolean[n][n]; 10 | //write your code here 11 | boolean col[]=new boolean[n]; 12 | boolean d1[]=new boolean[2*n-1]; 13 | boolean d2[]=new boolean[2*n-1]; 14 | 15 | nqueens(board,col,d1,d2,0,""); 16 | 17 | } 18 | 19 | public static void nqueens(boolean [][]board,boolean []col,boolean []d1,boolean []d2,int i,String asf){ 20 | int n=board.length; 21 | if(i==board.length){ 22 | System.out.println(asf+"."); 23 | return; 24 | } 25 | 26 | for(int j=0;jsize){ 4 | System.out.println("Invalid arguments"); 5 | }else if(idx==0){ 6 | addFirst(val); 7 | }else if(idx==size){ 8 | addLast(val); 9 | }else{ 10 | Node temp=head; 11 | for(int i=1;i<=idx-1;i++){ 12 | temp=temp.next; 13 | } 14 | 15 | Node nn=new Node(); 16 | nn.data=val; 17 | 18 | // IMPORTANT STEP 19 | nn.next=temp.next; 20 | temp.next=nn; 21 | size++; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LinkedList/Display Reverse(recursive)-LL.java: -------------------------------------------------------------------------------- 1 | private void displayReverseHelper(Node node){ 2 | // write your code here 3 | if(node==null){ 4 | return ; 5 | } 6 | 7 | 8 | displayReverseHelper(node.next); 9 | System.out.print(node.data+" "); 10 | 11 | } 12 | 13 | public void displayReverse(){ 14 | displayReverseHelper(head); 15 | System.out.println(); 16 | } 17 | -------------------------------------------------------------------------------- /LinkedList/Intersection Point of LL.java: -------------------------------------------------------------------------------- 1 | public static int findIntersection(LinkedList one, LinkedList two) { 2 | Node on = one.head; 3 | Node tn = two.head; 4 | 5 | if (one.size > two.size) { 6 | for (int i = 0; i < one.size - two.size; i++) { 7 | on = on.next; 8 | } 9 | } else { 10 | for (int i = 0; i < two.size - one.size; i++) { 11 | tn = tn.next; 12 | } 13 | } 14 | 15 | while (on != tn) { 16 | on = on.next; 17 | tn = tn.next; 18 | } 19 | 20 | return on.data; 21 | } 22 | -------------------------------------------------------------------------------- /LinkedList/Is a LL Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | private boolean IsPalindromeHelper(Node right){ 3 | if(right == null){ 4 | return true; 5 | } 6 | boolean rres = IsPalindromeHelper(right.next); 7 | if(rres == false){ 8 | return false; 9 | } else if(pleft.data != right.data){ 10 | return false; 11 | } else { 12 | pleft = pleft.next; 13 | return true; 14 | } 15 | } 16 | 17 | Node pleft; 18 | public boolean IsPalindrome(){ 19 | pleft = head; 20 | return IsPalindromeHelper(head); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LinkedList/K Reverse in LL.java: -------------------------------------------------------------------------------- 1 | public void kReverse(int k) { 2 | // write your code here 3 | LinkedList ans=new LinkedList(); 4 | LinkedList l1=new LinkedList(); // as a helper 5 | 6 | while(size()>0){ 7 | if(size()>=k){ 8 | for(int i=1;i<=k;i++){ 9 | l1.addFirst(getFirst()); 10 | removeFirst(); 11 | } 12 | }else { 13 | while(size()>0){ 14 | l1.addLast(getFirst()); 15 | removeFirst(); 16 | } 17 | } 18 | if(ans.size()==0){ 19 | ans=l1; 20 | }else { 21 | ans.tail.next=l1.head; 22 | ans.tail=l1.tail; 23 | ans.size+=l1.size; 24 | } 25 | l1=new LinkedList(); 26 | } 27 | head=ans.head; 28 | tail=ans.tail; 29 | size=ans.size; 30 | } 31 | -------------------------------------------------------------------------------- /LinkedList/Kth node from End of LL.java: -------------------------------------------------------------------------------- 1 | public int kthFromLast(int k){ 2 | // write your code here 3 | Node slow=head; 4 | Node fast=head; 5 | 6 | for(int i=1;i<=k;i++){ 7 | fast=fast.next; 8 | } 9 | 10 | while(fast!=tail){ 11 | fast=fast.next; 12 | slow=slow.next; 13 | } 14 | 15 | return slow.data; 16 | } 17 | -------------------------------------------------------------------------------- /LinkedList/LL to Queue Adapter.java: -------------------------------------------------------------------------------- 1 | 2 | public static class LLToQueueAdapter { 3 | LinkedList list; 4 | 5 | public LLToQueueAdapter() { 6 | list = new LinkedList<>(); 7 | } 8 | 9 | int size() { 10 | return list.size(); 11 | } 12 | 13 | void add(int val) { 14 | list.addLast(val); 15 | } 16 | 17 | int remove() { 18 | if(size() == 0){ 19 | System.out.println("Queue underflow"); 20 | return -1; 21 | } else { 22 | return list.removeFirst(); 23 | } 24 | } 25 | 26 | int peek() { 27 | if(size() == 0){ 28 | System.out.println("Queue underflow"); 29 | return -1; 30 | } else { 31 | return list.getFirst(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LinkedList/LL to Stack Adapter.java: -------------------------------------------------------------------------------- 1 | public static class LLToStackAdapter { 2 | LinkedList list; 3 | 4 | public LLToStackAdapter() { 5 | list = new LinkedList<>(); 6 | } 7 | 8 | 9 | int size() { 10 | return list.size(); 11 | } 12 | 13 | void push(int val) { 14 | list.addFirst(val); 15 | } 16 | 17 | int pop() { 18 | if(size() == 0){ 19 | System.out.println("Stack underflow"); 20 | return -1; 21 | } else { 22 | int val = list.getFirst(); 23 | list.removeFirst(); 24 | return val; 25 | } 26 | } 27 | 28 | int top() { 29 | if(size() == 0){ 30 | System.out.println("Stack underflow"); 31 | return -1; 32 | } else { 33 | int val = list.getFirst(); 34 | return val; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LinkedList/Merge Sort a LL.java: -------------------------------------------------------------------------------- 1 | public static LinkedList mergeTwoSortedLists(LinkedList l1, LinkedList l2) { 2 | LinkedList ml = new LinkedList(); 3 | 4 | Node one = l1.head; 5 | Node two = l2.head; 6 | while (one != null && two != null) { 7 | if (one.data < two.data) { 8 | ml.addLast(one.data); 9 | one = one.next; 10 | } else { 11 | ml.addLast(two.data); 12 | two = two.next; 13 | } 14 | } 15 | 16 | while (one != null) { 17 | ml.addLast(one.data); 18 | one = one.next; 19 | } 20 | 21 | while (two != null) { 22 | ml.addLast(two.data); 23 | two = two.next; 24 | } 25 | 26 | return ml; 27 | } 28 | 29 | public static Node getMidNode(Node head ,Node tail){ 30 | Node fast=head; 31 | Node slow=head; 32 | 33 | while(fast!=tail && fast.next!=tail){ 34 | fast=fast.next.next; 35 | slow=slow.next; 36 | } 37 | 38 | return slow; 39 | } 40 | 41 | public static LinkedList mergeSort(Node head, Node tail){ 42 | // write your code here 43 | if(head==tail){ 44 | LinkedList base=new LinkedList (); 45 | base.addLast(head.data); 46 | return base; 47 | } 48 | 49 | 50 | Node mid=getMidNode(head,tail); 51 | 52 | LinkedList fsh=mergeSort(head,mid); 53 | LinkedList ssh=mergeSort(mid.next,tail); 54 | 55 | LinkedList ans =mergeTwoSortedLists(fsh,ssh); 56 | 57 | return ans; 58 | } 59 | -------------------------------------------------------------------------------- /LinkedList/Merge Two Sorted LL.java: -------------------------------------------------------------------------------- 1 | public static LinkedList mergeTwoSortedLists(LinkedList l1, LinkedList l2) { 2 | // write your code hered 3 | LinkedList ans=new LinkedList(); 4 | 5 | Node t1=l1.head; 6 | Node t2=l2.head; 7 | 8 | while(t1!=null &&t2!=null){ 9 | 10 | if(t1.data 0){ 6 | int val = getFirst(); 7 | removeFirst(); 8 | 9 | if(val % 2 == 0){ 10 | even.addLast(val); 11 | } else { 12 | odd.addLast(val); 13 | } 14 | } 15 | 16 | if(odd.size > 0 && even.size > 0){ 17 | odd.tail.next = even.head; 18 | 19 | head = odd.head; 20 | tail = even.tail; 21 | size = odd.size + even.size; 22 | } else if(odd.size > 0){ 23 | head = odd.head; 24 | tail = odd.tail; 25 | size = odd.size; 26 | } else if(even.size > 0){ 27 | head = even.head; 28 | tail = even.tail; 29 | size = even.size; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LinkedList/Remove Duplicates in a sorted LL.java: -------------------------------------------------------------------------------- 1 | public void removeDuplicates(){ 2 | // write your code here 3 | 4 | if(head==null || head.next==null) return ; 5 | 6 | Node prev=head; 7 | Node curr=head.next; 8 | int count=1; 9 | while(curr!=null){ 10 | 11 | if(prev.data!=curr.data){ 12 | prev.next=curr; 13 | prev=curr; 14 | count++; 15 | } 16 | 17 | curr=curr.next; 18 | tail=prev; 19 | tail.next=null; 20 | size=count; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LinkedList/Remove First in LL.java: -------------------------------------------------------------------------------- 1 | public void removeFirst(){ 2 | // write your code here 3 | if(size==0){ 4 | System.out.println("List is empty"); 5 | }else if(size==1){ 6 | head=tail=null; 7 | size--; 8 | }else { 9 | head=head.next; 10 | size--; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LinkedList/Reverse LL(pointer -recursive).java: -------------------------------------------------------------------------------- 1 | private void reversePRHelper(Node node){ 2 | // write your code here 3 | if(node==tail){ 4 | return ; 5 | } 6 | 7 | reversePRHelper(node.next); 8 | node.next.next=node; 9 | 10 | } 11 | 12 | public void reversePR(){ 13 | // write your code here 14 | reversePRHelper(head); 15 | 16 | // Swap head and tail 17 | Node temp=head; 18 | head=tail; 19 | tail=temp; 20 | 21 | // Update the first node 22 | tail.next=null; 23 | } 24 | -------------------------------------------------------------------------------- /LinkedList/Reverse a LL (data -iterative recursion).java: -------------------------------------------------------------------------------- 1 | Node left; 2 | private void reversePRHelper(Node right,int counter){ 3 | 4 | if(right==null){ 5 | return ; 6 | } 7 | 8 | reversePRHelper(right.next,counter+1); 9 | if(counter>=size/2){ 10 | int temp=left.data; 11 | left.data=right.data; 12 | right.data=temp; 13 | 14 | left=left.next; 15 | } 16 | 17 | 18 | } 19 | 20 | public void reversePR(){ 21 | 22 | left=head; 23 | reversePRHelper(head,0); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /LinkedList/Reverse a LL (data iterative).java: -------------------------------------------------------------------------------- 1 | public Node getNode(int idx){ 2 | Node temp=head; 3 | for(int i=0;i=size){ 23 | System.out.println("Invalid arguments"); 24 | return -1; 25 | }else if(size==0){ 26 | System.out.println("List is empty"); 27 | return -1; 28 | }else if(idx==0){ 29 | return getFirst(); 30 | }else if(idx==size-1){ 31 | return getLast(); 32 | }else{ 33 | Node temp=head; 34 | for(int i=1;i<=idx;i++){ 35 | temp=temp.next; 36 | } 37 | 38 | return temp.data; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /LinkedList/remove at Index in LL.java: -------------------------------------------------------------------------------- 1 | public void removeAt(int idx) { 2 | // write your code here 3 | if(idx<0 || idx>=size){ 4 | System.out.println("Invalid arguments"); 5 | }else if(idx==0){ 6 | removeFirst(); 7 | }else if(idx==size-1){ 8 | removeLast(); 9 | }else { 10 | Node temp=head; 11 | for(int i=1;i<=idx-1;i++){ 12 | temp=temp.next; 13 | } 14 | 15 | temp.next=temp.next.next; 16 | size--; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LinkedList/remove last in LL.java: -------------------------------------------------------------------------------- 1 | public void removeLast(){ 2 | // write your code here 3 | if(size==0){ 4 | System.out.println("List is empty"); 5 | }else if(size==1){ 6 | head=tail=null; 7 | size=0; 8 | }else { 9 | Node temp=head; 10 | 11 | for(int i=1;i3 16 | if(n==0) { 17 | return ; 18 | } 19 | 20 | // My work ->2 21 | System.out.println(n); 22 | 23 | // faith ->1 24 | printDecreasing(n-1); 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Recursion/Recursion and Backtracking/Flood Fill.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | Scanner scn = new Scanner(System.in); 8 | int n = scn.nextInt(); 9 | int m = scn.nextInt(); 10 | int[][] arr = new int[n][m]; 11 | for (int i = 0; i < n; i++) { 12 | for (int j = 0; j < m; j++) { 13 | arr[i][j] = scn.nextInt(); 14 | } 15 | } 16 | 17 | boolean visited[][]=new boolean[n][m]; 18 | floodfill(arr, 0, 0, "",visited); 19 | } 20 | 21 | 22 | 23 | // asf -> answer so far 24 | public static void floodfill(int[][] maze, int sr, int sc, String asf,boolean [][]visited) { 25 | // Negative Base Case 26 | if(sr<0 || sc<0 || sr>=maze.length || sc>=maze[0].length || maze[sr][sc]==1 || visited[sr][sc]==true){ 27 | return ; 28 | } 29 | // Positive base case 30 | if(sr==maze.length-1 && sc==maze[0].length-1){ 31 | System.out.println(asf); 32 | return ; 33 | } 34 | visited[sr][sc]=true; 35 | floodfill(maze,sr-1,sc,asf+"t",visited); 36 | floodfill(maze,sr,sc-1,asf+"l",visited); 37 | floodfill(maze,sr+1,sc,asf+"d",visited); 38 | floodfill(maze,sr,sc+1,asf+"r",visited); 39 | visited[sr][sc]=false; 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Recursion/Recursion and Backtracking/N Queen.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Scanner scn=new Scanner(System.in); 8 | int n=scn.nextInt(); 9 | boolean [][]chess=new boolean [n][n]; 10 | printNQueens(chess,"",0); 11 | 12 | 13 | } 14 | 15 | public static void printNQueens(boolean[][] chess, String asf, int row) { 16 | //Base Case 17 | if(row==chess.length){ 18 | System.out.println(asf+"."); 19 | return; 20 | } 21 | 22 | for(int col=0;col=0 && j=0;i--){ 46 | if(chess[i][col]==true){ 47 | return false; 48 | } 49 | } 50 | 51 | // diagonal d3 52 | for(int i=row-1,j=col-1;i>=0 && j>=0 ;i--,j--){ 53 | if(chess[i][j]==true){ 54 | return false; 55 | } 56 | } 57 | 58 | return true; 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Recursion/Recursion on the way up/Print Encodings.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Scanner scn=new Scanner(System.in); 8 | String str=scn.nextLine(); 9 | printEncodings(str,""); 10 | 11 | } 12 | 13 | public static void printEncodings(String str,String asf) { 14 | 15 | 16 | // Step-08 17 | if(str.length()==0){ 18 | System.out.println(asf); 19 | return ; 20 | } 21 | 22 | // Step-01 23 | String ch0=str.substring(0,1); 24 | // Step-02 25 | String ros=str.substring(1); 26 | // Step-03 27 | if(ch0.equals("0")) return ; 28 | 29 | printEncodings(ros,asf+(char)(Integer.parseInt(ch0)-1+'a')); 30 | 31 | // Step-04 32 | if(str.length()>=2){ 33 | // Step-05 34 | String ch01=str.substring(0,2); 35 | 36 | //step-06 37 | String ros2=str.substring(2); 38 | 39 | //step -07 40 | if(Integer.parseInt(ch01)<=26){ 41 | printEncodings(ros2,asf+(char)(Integer.parseInt(ch01)-1+'a')); 42 | } 43 | 44 | 45 | } 46 | 47 | 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Recursion/Recursion on the way up/Print Maze Paths.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Scanner scn=new Scanner(System.in); 8 | int n=scn.nextInt(); 9 | int m=scn.nextInt(); 10 | 11 | printMazePaths(0,0,n-1,m-1,""); 12 | 13 | } 14 | 15 | // sr - source row 16 | // sc - source column 17 | // dr - destination row 18 | // dc - destination column 19 | public static void printMazePaths(int sr, int sc, int dr, int dc, String asf) { 20 | 21 | // Negative Base Case 22 | if(sr>dr || sc>dc){ 23 | return ; 24 | } 25 | 26 | // Positive Base Case 27 | if(sr==dr && sc==dc){ 28 | System.out.println(asf); 29 | return ; 30 | } 31 | 32 | 33 | printMazePaths(sr,sc+1,dr,dc,asf+"h"); 34 | printMazePaths(sr+1,sc,dr,dc,asf+"v"); 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Recursion/Recursion on the way up/Print Permutation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Scanner scn=new Scanner(System.in); 8 | 9 | String str=scn.nextLine(); 10 | printPermutations(str,""); 11 | 12 | } 13 | 14 | public static void printPermutations(String str, String asf) { 15 | 16 | // Base Case -> When string is Empty 17 | if(str.length()==0){ 18 | System.out.println(asf); 19 | return ; 20 | } 21 | 22 | for(int i=0;i ans = getKPC(str); 11 | System.out.println(ans); 12 | 13 | } 14 | 15 | static String[]arr={".;","abc","def","ghi","jkl","mno","pqrs","tu","vwx","yz"}; 16 | 17 | public static ArrayList getKPC(String str) { 18 | 19 | if(str.length()==0){ 20 | ArrayListbase=new ArrayList<>(); 21 | base.add(""); 22 | return base; 23 | } 24 | 25 | char ch=str.charAt(0); 26 | String ros=str.substring(1); 27 | ArrayListrr=getKPC(ros); 28 | String code=arr[ch-'0']; 29 | ArrayListmyAns=new ArrayList<>(); 30 | 31 | for(int i=0;ians=getStairPaths(n); 10 | 11 | System.out.println(ans); 12 | 13 | 14 | } 15 | 16 | public static ArrayList getStairPaths(int n) { 17 | 18 | //Positive Base Case 19 | if(n==0){ 20 | ArrayListbase1=new ArrayList<>(); 21 | base1.add(""); 22 | return base1; 23 | } 24 | 25 | // Negative Base Case 26 | if(n<0){ 27 | ArrayList base2 = new ArrayList<>(); 28 | return base2; 29 | } 30 | 31 | // Faith -01 for 1 step 32 | ArrayListrr1=getStairPaths(n-1); 33 | // Faith -02 for 2 steps 34 | ArrayListrr2=getStairPaths(n-2); 35 | // Faith -03 for 3 steps 36 | ArrayListrr3=getStairPaths(n-3); 37 | 38 | // My Work 39 | ArrayListmyAns=new ArrayList<>(); 40 | 41 | for(int i=0;i ans = gss(str); 10 | 11 | System.out.println(ans); 12 | 13 | } 14 | 15 | public static ArrayList gss(String str) { 16 | if(str.length()==0){ 17 | ArrayList base = new ArrayList<>(); 18 | base.add(""); 19 | return base; 20 | } 21 | 22 | char ch=str.charAt(0); 23 | String ros=str.substring(1); 24 | 25 | // Faith 26 | ArrayListrr=gss(ros); 27 | 28 | // My work 29 | 30 | ArrayList myans = new ArrayList<>(); 31 | // 1) Exclude 32 | 33 | for(String rstr:rr){ 34 | myans.add(rstr); 35 | 36 | } 37 | 38 | // 2) Include 39 | for(int i=0;ist,char bracket){ 6 | // Less Opening bracket 7 | if(st.size()==0) 8 | return false; 9 | else if(st.peek()!=bracket) { 10 | return false; 11 | }else { 12 | st.pop(); 13 | return true; 14 | } 15 | } 16 | 17 | public static void main(String[] args) throws Exception { 18 | 19 | Scanner scn=new Scanner(System.in); 20 | 21 | String exp=scn.nextLine(); 22 | 23 | Stackst=new Stack<>(); 24 | 25 | for(int i=0;ist=new Stack<>(); 28 | 29 | for(int i=0;i=2){ 34 | int a=st.pop(); 35 | int b=st.pop(); 36 | 37 | if(arr[a][b]==1){ 38 | // a know b->a is not a celebrity 39 | st.push(b); 40 | }else{ 41 | // a does not know b->b is not a celebrity 42 | st.push(a); 43 | 44 | } 45 | } 46 | 47 | 48 | int potential_answer=st.pop(); 49 | // // For row 50 | // for(int i =0;ist1=new Stack<>(); // Prefix 13 | Stackst2=new Stack<>();// Operators 14 | Stackst3=new Stack<>();// Postfix 15 | 16 | for(int i=0;i='a' && ch<='z'){ 21 | st1.push(ch+""); 22 | st3.push(ch+""); 23 | 24 | }else if(ch=='('){ 25 | st2.push(ch); 26 | }else if(ch=='+' || ch=='-' || ch=='*' ||ch=='/'){ 27 | while(st2.size()>0 && precedence(st2.peek())>=precedence(ch)){ 28 | String op2=st1.pop(); 29 | String op1=st1.pop(); 30 | char optr1=st2.peek(); 31 | st1.push(optr1+op1+op2); 32 | 33 | String opp2=st3.pop(); 34 | String opp1=st3.pop(); 35 | char optr2=st2.pop(); 36 | st3.push(opp1+opp2+optr2); 37 | 38 | } 39 | st2.push(ch); 40 | }else if(ch==')'){ 41 | while(st2.peek()!='('){ 42 | String op2=st1.pop(); 43 | String op1=st1.pop(); 44 | char optr1=st2.peek(); 45 | st1.push(optr1+op1+op2); 46 | 47 | String opp2=st3.pop(); 48 | String opp1=st3.pop(); 49 | char optr2=st2.pop(); 50 | st3.push(opp1+opp2+optr2); 51 | } 52 | st2.pop(); 53 | 54 | }else { 55 | // do nothing 56 | } 57 | } 58 | 59 | while(st2.size()>0){ 60 | String op2=st1.pop(); 61 | String op1=st1.pop(); 62 | char optr1=st2.peek(); 63 | st1.push(optr1+op1+op2); 64 | 65 | String opp2=st3.pop(); 66 | String opp1=st3.pop(); 67 | char optr2=st2.pop(); 68 | st3.push(opp1+opp2+optr2); 69 | } 70 | 71 | System.out.println(st3.pop()); 72 | System.out.println(st1.pop()); 73 | } 74 | 75 | public static int precedence(char ch){ 76 | 77 | if(ch=='+' || ch=='-'){ 78 | return 1; 79 | } 80 | else if(ch=='*' || ch=='/'){ 81 | return 2; 82 | } 83 | else { 84 | return 0; 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /Stack/Infix Evaluation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main{ 5 | 6 | 7 | public static void main(String[] args) throws Exception { 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | String exp = br.readLine(); 10 | 11 | // code 12 | 13 | Stackst1=new Stack<>();// operands 14 | Stackst2=new Stack<>();// operator 15 | 16 | for(int i=0;i='0' && ch<='9'){ 20 | st1.push(ch-'0'); 21 | }else if(ch=='('){ 22 | st2.push(ch); 23 | }else if(ch=='+' || ch=='-' || ch=='*' ||ch=='/'){ 24 | while(st2.size()>0 && precedence(st2.peek())>=precedence(ch)){ 25 | char operator=st2.pop(); 26 | int op2=st1.pop(); 27 | int op1=st1.pop(); 28 | 29 | int result=solve(op1,op2,operator); 30 | st1.push(result); 31 | } 32 | st2.push(ch); 33 | 34 | }else if(ch==')'){ 35 | while(st2.peek()!='('){ 36 | char operator=st2.pop(); 37 | int op2=st1.pop(); 38 | int op1=st1.pop(); 39 | 40 | int result=solve(op1,op2,operator); 41 | st1.push(result); 42 | } 43 | st2.pop(); 44 | 45 | }else{ 46 | //do nothing 47 | } 48 | } 49 | while(st2.size()!=0){ 50 | char operator=st2.pop(); 51 | int op2=st1.pop(); 52 | int op1=st1.pop(); 53 | 54 | int result=solve(op1,op2,operator); 55 | st1.push(result); 56 | 57 | } 58 | System.out.println(st1.peek()); 59 | 60 | 61 | } 62 | public static int solve(int op1,int op2,char operator){ 63 | if(operator=='+'){ 64 | return op1+op2; 65 | }else if(operator=='-'){ 66 | return op1-op2; 67 | }else if(operator=='*'){ 68 | return op1*op2; 69 | }else { 70 | return op1/op2; 71 | } 72 | } 73 | 74 | public static int precedence(char ch){ 75 | 76 | if(ch=='+' || ch=='-'){ 77 | return 1; 78 | } 79 | else if(ch=='*' || ch=='/'){ 80 | return 2; 81 | } 82 | else { 83 | return 0; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Stack/Postfix Evaluation and Conversion.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main{ 5 | 6 | 7 | public static void main(String[] args) throws Exception { 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | String exp = br.readLine(); 10 | 11 | // code 12 | 13 | Stackst1=new Stack<>(); 14 | Stackst2=new Stack<>(); 15 | Stackst3=new Stack<>(); 16 | 17 | 18 | for(int i=0;i='0' && ch<='9'){ 22 | st1.push(ch-'0'); 23 | st2.push(ch+""); 24 | st3.push(ch+""); 25 | }else{ 26 | 27 | //Evaluation 28 | int op2=st1.pop(); 29 | int op1=st1.pop(); 30 | int ans=solve(op1,op2,ch); 31 | st1.push(ans); 32 | 33 | // Infix 34 | String opp2=st2.pop(); 35 | String opp1=st2.pop(); 36 | 37 | st2.push('('+opp1+ch+opp2+')'); 38 | 39 | 40 | // Prefix 41 | String oppp2=st3.pop(); 42 | String oppp1=st3.pop(); 43 | 44 | st3.push(ch+oppp1+oppp2); 45 | 46 | } 47 | } 48 | 49 | System.out.println(st1.pop()); 50 | System.out.println(st2.pop()); 51 | System.out.println(st3.pop()); 52 | 53 | } 54 | 55 | public static int solve(int op1,int op2,char operator){ 56 | if(operator=='+'){ 57 | return op1+op2; 58 | }else if(operator=='-'){ 59 | return op1-op2; 60 | }else if(operator=='*'){ 61 | return op1*op2; 62 | }else { 63 | return op1/op2; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Stack/Sliding Window Maximum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main{ 5 | 6 | 7 | public static void main(String[] args) throws Exception { 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | 10 | int n = Integer.parseInt(br.readLine()); 11 | int[] a = new int[n]; 12 | for(int i = 0; i < n; i++){ 13 | a[i] = Integer.parseInt(br.readLine()); 14 | } 15 | int k = Integer.parseInt(br.readLine()); 16 | 17 | // code 18 | 19 | Dequedq=new ArrayDeque<>(); 20 | 21 | // first k elements 22 | for(int i=0;i0 && a[dq.getLast()]0 && a[dq.getLast()]1){ 32 | comp2+=count; 33 | } 34 | 35 | comp2+=str.charAt(i); 36 | count=1; 37 | } 38 | 39 | } 40 | 41 | if(count>1) { 42 | comp2+=count; 43 | } 44 | 45 | return comp2; 46 | } 47 | public static void main(String[] args) { 48 | Scanner scn = new Scanner(System.in); 49 | String str = scn.next(); 50 | System.out.println(compression1(str)); 51 | System.out.println(compression2(str)); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Test -01 Solution/Hash Pattern 1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | Scanner scn = new Scanner(System.in); 6 | int n = scn.nextInt(); 7 | 8 | int N=2*n-1; 9 | 10 | 11 | for(int i=0; i0){ 9 | temp=temp/10; 10 | totaldig++; 11 | } 12 | int ans=0; 13 | int p=totaldig; 14 | while(n>0){ 15 | int dig=n%10; 16 | n=n/10; 17 | ans+=p*Math.pow(10,totaldig-dig); 18 | p--; 19 | } 20 | System.out.println(ans); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Test -01 Solution/Left Rotation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main{ 5 | public static void display(int[] a){ 6 | 7 | for(int i=0;ipivot){ 44 | result[start++]=arr[i]; 45 | } 46 | } 47 | 48 | 49 | 50 | return result; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Test -01 Solution/Pattern Alpha Numeric.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | Scanner scn=new Scanner(System.in); 8 | int n=scn.nextInt(); 9 | int count=0; 10 | char ch='A'; 11 | for(int i=1;i<=n;i++){ 12 | for(int j=1;j<=i;j++){ 13 | char c=(char)(65+count); 14 | System.out.print(c +"\t"+ ++count+"\t"); 15 | } 16 | System.out.println(); 17 | } 18 | 19 | } 20 | } 21 | --------------------------------------------------------------------------------