├── 2dArrays[InClass] ├── DiagonalSum.java └── MaxSumColumn.java ├── 2dArrays[PostClass] ├── BooleanMatrixProblem.java ├── GoodCells.java └── RowMaxOnes.java ├── ArrayList[Inclass] └── ArrayList.java ├── BST[InClass] ├── DeletionInBST.java ├── InsertionIBST.java └── MinimumInBST.java ├── BST[PostClass] ├── IsBST.java ├── LCAofBST.java └── NodesAbsMinDiff.java ├── BinarySearch ├── FoodFest.java ├── MinimumElementOnSortedArray.java ├── PowerOfThree.java └── TheGabbaTest.java ├── BinaryTrees[Practice] ├── InorderTraversal.java ├── MinDepth.java ├── PathSum.java ├── PostOrderTraversal.java ├── PreOrderTraversal.java └── SameTree.java ├── BitManipulation[Inclass] ├── BitRotation.java ├── RightMostDifferent.java └── TwoBits.java ├── BitManipulation[Postclass] ├── BitCount.java ├── BitDifference.java └── FixingTheMiddle.java ├── CircularLinkedList[InClass] ├── CheckCLL.java └── InsertionInCLL.java ├── Combinatorics[InClass] ├── CombinationsAllPair.java └── Pascals.java ├── Combinatorics[PostClass] ├── NumberSubsequences.java └── SimpleColours.java ├── DP[InClass] ├── MinNumberOfCoins.java └── SticklerThief.java ├── DP[PostClass] ├── IncreasingSubsequences.java ├── LongestIncreasingSubsequence.java └── StepsToReachInTop.java ├── Dequeue[Inclass] ├── MaximumofAllSize.java └── SumOfMinimumAndMaximum.java ├── Dequeue[Postclass] └── CircularRotation.java ├── DoubleLinkedList[InClass] ├── InsertNodeHead.java └── InsertNodeKthPosition.java ├── DoubleLinkedList[PostClass] ├── DeleteElement.java └── ReverseElement.java ├── FundementalsInJava[InClass] ├── FahrenheitToCelsius.java ├── Operators.java ├── SimpleInterest.java └── StartCoding.java ├── HeapSort[Inclass] ├── MaxInQueue.java └── MinimumRopeCost.java ├── HeapSort[PostClass] ├── MaxDistinctBooks.java ├── MaxProdKIntegers.java └── SequenceFinder.java ├── Heaps[InClass] ├── Chocolates.java └── FindMedian.java ├── Heaps[Postclass] ├── AnotherArrayOperation.java ├── InterviewQuestions.java └── KthLargest.java ├── IntroductionArray[Inclass] ├── MaxAndMin.java └── Negative.java ├── IntroductionArray[PostClass] ├── MaxNumbers.java ├── OddSum.java └── SeasonOfLove.java ├── IntroductionToArrayContd[Inclass] ├── ReplaceElement.java └── SumAndMean.java ├── IntroductionToArrayContd[PostClass] ├── AlternateSumProduct.java └── IncreasingArray.java ├── IntroductionToLoopAndControls[InClass] ├── Armstrong.java ├── MaxInteger.java └── Palindrome.java ├── IntroductionToLoopAndControls[PostClass] ├── FizzBuzz.java ├── Pattern.java └── StudentGrades.java ├── JavaCollections[Inclass] ├── CountDuplicates.java └── FindPairsWithGivenSum.java ├── JavaCollections[PostClass] ├── CountDistincElements.java ├── MaxSubarraySum.java └── PartiesAndSeats.java ├── LinkedList-II[Inclass] ├── MergeSortedLL.java └── PalindromeList.java ├── LinkedList-II[PostClass] ├── DeleteMiddle.java └── ReverseLinkedList.java ├── LinkedList[InClass] └── LinkedListInsertion[InClass].java ├── LinkedList[PostClass] ├── DeleteKthEnd.java ├── IntersectionLinkedList.java └── PrintLinkedList.java ├── MathModular[Arithmetic][Inclass] ├── ModularExponential.java └── Tribonocci.java ├── MathModular[Arithmetic][Postclass] ├── NumberGame.java └── RaisedPowerP.java ├── Maths[GCD] ├── GCD.java └── MSpecialGCD.java ├── Maths[GCD][Postclass] ├── GoodTeamLeader.java └── SpecialNumbers.java ├── Maths[PrimalityTesting] ├── CheckIfPrime.java ├── ExactlyThreeDivisors.java └── NumberOfPrimes.java ├── MergeSortAndJavaFunds[Inclass] ├── DragonSlayer.java ├── InversionCount.java └── QueensAttack.java ├── MergeSort[Inclass] └── ImplementingMergeSort.java ├── Queue[InClass] ├── GenerateBinaryNumbers.java ├── OperationsInQueue.java └── QueueArrayImplementation.java ├── Queue[PostClass] ├── MaximumKSubarray.java └── ReverseKelements.java ├── README.md ├── RecursionContd[InClass] ├── Fibonacci.java └── Welcome.java ├── RecursionContd[PostClass] ├── ComputePower.java ├── MultiplyByRecursion.java └── Printdigits.java ├── Recursion[Inclass] ├── Factorial.java ├── PowerFunction.java └── TowerOfHanoi.java ├── Recursion[Postclass] ├── CandyCrush.java └── SumOfDigits.java ├── SimpleSorting[InClass] ├── BubbleSort.java └── SelectionSort.java ├── SimpleSorting[PostClass] └── BubbleSort.java ├── Stack[InClass] ├── HeightProblem.java ├── StackArrayImplementation.java └── StackOperationClass.java ├── Stack[PostClass] ├── GreaterIsBetter.java ├── NearestSmallestElement.java └── StockSpanProblem.java ├── StringsManipulation ├── Anagram.java ├── MaxHammingDistance.java └── Reverse.java ├── Strings[InClass] ├── BeautifulString.java ├── IsPalindrome.java ├── Permutation.java ├── RemoveDuplicates.java ├── StringLength.java └── Substring.java ├── Trees[Inclass] ├── HeighOfBinaryTree.java └── LevelOrderTraversal.java └── Trees[PostClass] ├── CounSubtreesWithSum.java ├── MirrorOfBinaryTree.java └── RightViewOfBinaryTree.java /2dArrays[InClass]/DiagonalSum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | int matrix[][] = new int[n][n]; 11 | for(int i = 0; i < n; i++){ 12 | for(int j = 0; j < n; j++){ 13 | matrix[i][j] = sc.nextInt(); 14 | } 15 | } 16 | /* 17 | 1 2 3 18 | 4 5 6 19 | 7 8 9 20 | 21 | primeDiagonal = 6, secondDiagonal = 8 22 | i = 1, j = 1 23 | 24 | */ 25 | 26 | int primeDiagonal = 0, secondDiagonal = 0; 27 | for(int i = 0; i < n; i++){ 28 | for(int j = 0; j < n; j++){ 29 | if(i == j){ 30 | primeDiagonal += matrix[i][j]; 31 | } 32 | if(i+j == n - 1){ 33 | secondDiagonal += matrix[i][j]; 34 | } 35 | } 36 | } 37 | System.out.println(primeDiagonal + " " +secondDiagonal); 38 | } 39 | } -------------------------------------------------------------------------------- /2dArrays[InClass]/MaxSumColumn.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int m = sc.nextInt(); 10 | int n = sc.nextInt(); 11 | int matrix[][] = new int[m][n]; 12 | 13 | for(int i = 0; i < m; i++){ 14 | for(int j = 0; j < n; j++){ 15 | matrix[i][j] = sc.nextInt(); 16 | } 17 | } 18 | /* 19 | 20 | 1 2 3 21 | 4 5 6 22 | 7 8 9 23 | 24 | j = 0, i = 2, maximum_column = -2^31 25 | sum_column = 1 + 4 + 7 = 12, maximum_column = 12 26 | 27 | j = 1, i = 0, maximum_column = -2^31 28 | sum_column = 2 + 5 + 8 = 15, maximum_column = 15 29 | */ 30 | 31 | int maximum_column = Integer.MIN_VALUE; 32 | for(int j = 0; j < n; j++){ 33 | int sum_column = 0; 34 | for(int i = 0; i < m; i++){ 35 | sum_column += matrix[i][j]; 36 | } 37 | maximum_column = Math.max(maximum_column, sum_column); 38 | } 39 | System.out.println(maximum_column); 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /2dArrays[PostClass]/BooleanMatrixProblem.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | 7 | class Main { 8 | 9 | static int MAX = 1000; 10 | static int a[][] = new int[MAX][MAX]; 11 | 12 | public static void main (String[] args) throws IOException{ 13 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 14 | int t = Integer.parseInt(br.readLine()); 15 | while(t-- > 0){ 16 | String str[] = br.readLine().trim().split(" "); 17 | int n = Integer.parseInt(str[0]); 18 | int m = Integer.parseInt(str[1]); 19 | boolean b[] = new boolean[n]; 20 | for(int i=0;i j){ 24 | ans = i; 25 | count = j; 26 | } 27 | } 28 | } 29 | } 30 | System.out.println(ans); 31 | } 32 | } -------------------------------------------------------------------------------- /ArrayList[Inclass]/ArrayList.java: -------------------------------------------------------------------------------- 1 | // Function to insert element into list 2 | public static void insert(ArrayList list, int x) 3 | { 4 | list.add(x); 5 | } 6 | 7 | // Function to sort list in Increasing order 8 | public static void IncOrder(ArrayList list) 9 | { 10 | Collections.sort(list); //[1,2,3] 11 | } 12 | 13 | // Function to search element in the lise 14 | // val : element to be searched 15 | public static void Search(ArrayList list, int val) 16 | { 17 | for(int i = 0; i < list.size(); i++){ 18 | if(list.get(i) == val){ 19 | System.out.print(i +" "); 20 | return; 21 | } 22 | } 23 | System.out.print("-1 "); 24 | } 25 | 26 | // Function to sort list in decreasing order 27 | public static void DecOrder(ArrayList list) 28 | { 29 | //decreasing order 30 | Collections.sort(list, Collections.reverseOrder()); 31 | } -------------------------------------------------------------------------------- /BST[InClass]/DeletionInBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Information about the class 3 | class Node{ 4 | int data; 5 | Node left; 6 | Node right; 7 | Node(int data){ 8 | this.data = data; 9 | left=null; 10 | right=null; 11 | } 12 | } 13 | */ 14 | 15 | public static Node findLeftMost(Node node){ 16 | while(node.left != null){ 17 | node = node.left; 18 | } 19 | return node; 20 | } 21 | 22 | 23 | public static Node deleteInBST(Node root, int value) 24 | { 25 | if(root == null){ 26 | return null; 27 | } 28 | if(root.data > value){ 29 | root.left = deleteInBST(root.left, value); 30 | } 31 | else if(root.data < value){ 32 | root.right = deleteInBST(root.right, value); 33 | } 34 | else{ 35 | // root.data == value 36 | /* 37 | 1. if root has 2 children 38 | 2. if root has 1 child 39 | 3. if root has no child 40 | */ 41 | if(root.left != null && root.right != null){ 42 | //2 children case 43 | //find sucessor 44 | Node successor = findLeftMost(root.right); 45 | root.data = successor.data; 46 | root.right = deleteInBST(root.right, successor.data); 47 | } 48 | else if(root.left != null){ 49 | //1 child case --> Left child 50 | root = root.left; 51 | } 52 | else if(root.right != null){ 53 | //1 child case --> Right Child 54 | root = root.right; 55 | } 56 | else{ 57 | //no child 58 | root = null; 59 | } 60 | } 61 | return root; 62 | } -------------------------------------------------------------------------------- /BST[InClass]/InsertionIBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Information about the Node class 3 | class Node 4 | { 5 | int data; 6 | Node left, right; 7 | 8 | public Node(int d) 9 | { 10 | data = d; 11 | left = right = null; 12 | } 13 | } 14 | 15 | 16 | | 1 | -> | 6 | 17 | 18 | 19 | */ 20 | static Node insertInBST(Node root,int key) 21 | { 22 | if(root == null){ 23 | return new Node(key); 24 | } 25 | if(key > root.data){ 26 | root.right = insertInBST(root.right, key); 27 | } 28 | else if(key < root.data){ 29 | root.left = insertInBST(root.left, key); 30 | } 31 | return root; 32 | } -------------------------------------------------------------------------------- /BST[InClass]/MinimumInBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Information about the class Node 3 | class Node{ 4 | int data; 5 | Node left; 6 | Node right; 7 | Node(int data){ 8 | this.data = data; 9 | left=null; 10 | right=null; 11 | } 12 | } 13 | */ 14 | static int minValue(Node node) 15 | { 16 | if(node == null){ 17 | return -1; 18 | } 19 | 20 | while(node.left != null){ 21 | node = node.left; 22 | } 23 | 24 | return node.data; 25 | } -------------------------------------------------------------------------------- /BST[PostClass]/IsBST.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | 7 | class Node{ 8 | int data; 9 | Node left; 10 | Node right; 11 | Node(int data){ 12 | this.data = data; 13 | left = null; 14 | right = null; 15 | } 16 | } 17 | 18 | class Main { 19 | 20 | public static boolean isBST(Node tree, int min, int max){ 21 | if(tree == null) 22 | return true; 23 | if(tree.data < min || tree.data > max) 24 | return false; 25 | return isBST(tree.left, min, tree.data - 1) && isBST(tree.right, tree.data + 1, max); 26 | } 27 | 28 | public static void main (String[] args) { 29 | Scanner sc = new Scanner(System.in); 30 | int n = sc.nextInt(); 31 | Node[] tree = new Node[n]; 32 | for(int i = 0; i < n; i++){ 33 | int value = sc.nextInt(); 34 | tree[i] = new Node(value); 35 | } 36 | int root = sc.nextInt(); 37 | for(int i = 0; i < n; i++){ 38 | int left = sc.nextInt(); 39 | int right = sc.nextInt(); 40 | if(left != 0) 41 | tree[i].left = tree[left - 1]; 42 | if(right != 0) 43 | tree[i].right = tree[right - 1]; 44 | } 45 | 46 | if(isBST(tree[root-1], Integer.MIN_VALUE, Integer.MAX_VALUE)){ 47 | System.out.println("YES"); 48 | } 49 | else{ 50 | System.out.println("NO"); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /BST[PostClass]/LCAofBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Information about the class Node 3 | class Node{ 4 | int data; 5 | Node left; 6 | Node right; 7 | Node(int data){ 8 | this.data = data; 9 | left=null; 10 | right=null; 11 | } 12 | } 13 | */ 14 | 15 | static Node LCA(Node node, int n1, int n2) { 16 | if (node == null) { 17 | return null; 18 | } 19 | 20 | // If both n1 and n2 are smaller than root, then LCA lies in left 21 | if (node.data > n1 && node.data > n2) { 22 | return LCA(node.left, n1, n2); 23 | } 24 | 25 | // If both n1 and n2 are greater than root, then LCA lies in right 26 | if (node.data < n1 && node.data < n2) { 27 | return LCA(node.right, n1, n2); 28 | } 29 | 30 | return node; 31 | } -------------------------------------------------------------------------------- /BST[PostClass]/NodesAbsMinDiff.java: -------------------------------------------------------------------------------- 1 | /* 2 | // Information about the class Node 3 | class Node{ 4 | int data; 5 | Node left; 6 | Node right; 7 | 8 | Node(int data){ 9 | this.data = data; 10 | left=null; 11 | right=null; 12 | 13 | } 14 | } 15 | */ 16 | static Integer prev = null, minDiff = Integer.MAX_VALUE; 17 | public static int absMinDist(Node root) { 18 | prev = null; 19 | minDiff = Integer.MAX_VALUE; 20 | bst(root); 21 | return minDiff; 22 | } 23 | 24 | public static void bst(Node root) { 25 | if(root==null) return; 26 | bst(root.left); 27 | if(prev!=null) { 28 | minDiff = Math.min(root.data-prev, minDiff); 29 | } 30 | prev= root.data; 31 | bst(root.right); 32 | } -------------------------------------------------------------------------------- /BinarySearch/FoodFest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | /* 9 | 4 10 10 | 1 2 3 4 11 | 12 | Sol = 6 13 | 14 | 6/1 = 6 15 | 6/2 = 3 16 | 6/3 = 2 17 | 6/4 = 1 18 | -------- 19 | 12 20 | 21 | Sol = 5 22 | 5/1 = 5 23 | 5/2 = 2 24 | 5/3 = 1 25 | 5/4 = 1 26 | -------- 27 | 9 28 | 29 | p = 10 30 | [1,2,3,4] 31 | low = 1, high = min*p = 10, 1<=sol<=10, p = 10dishes 32 | while(low <= high) 33 | (1mins, 10mins, 5mins), dishes_mid=5+2+1+1=9, low = mid + 1 = 6mins 34 | (6mins, 10mins, 8mins), dishes_mid=8+4+2+2=16, sol = 8mins, high = mid - 1 = 7mins 35 | (6mins, 7mins, 6mins), dishes_mid=6+3+2+1=12, sol = 6mins, high = mid - 1 = 6mins 36 | (6mins, 6mins, 6mins), dishes_mid=6+3+2+1=12, sol = 6mins, high = mid - 1 = 5mins 37 | (6mins, 5mins) low > high! 38 | 39 | */ 40 | 41 | 42 | public static long calculateDishes(long arr[], int n, long mid){ 43 | long dishes_mid = 0; 44 | for(int i = 0; i < n; i++){ 45 | dishes_mid += (mid / arr[i]); 46 | } 47 | return dishes_mid; 48 | } 49 | 50 | public static void main (String[] args) { 51 | Scanner sc = new Scanner(System.in); 52 | int n = sc.nextInt(); 53 | long p = sc.nextLong(); 54 | long arr[] = new long[n]; 55 | long low = 1, high = Long.MAX_VALUE; 56 | for(int i = 0; i < n; i++){ 57 | arr[i] = sc.nextLong(); 58 | if(high > arr[i]){ 59 | high = arr[i]; //We will get min time of all people 60 | } 61 | } 62 | high = high * p; //Max amount of time taken. 63 | long sol = high; 64 | while(low <= high){ 65 | long mid = low + (high - low) / 2; 66 | long dishes_mid = calculateDishes(arr, n, mid); 67 | if(dishes_mid < p){ 68 | low = mid + 1; 69 | } 70 | else{ 71 | sol = mid; 72 | high = mid - 1; 73 | } 74 | } 75 | System.out.println(sol); 76 | 77 | } 78 | } -------------------------------------------------------------------------------- /BinarySearch/MinimumElementOnSortedArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | 5 | class Main{ 6 | 7 | public static void binSearchSmallest(int a[], int n){ 8 | //5 1 2 3 4 9 | int left = 0, right = n-1;//left = 0, right = 1 10 | while(left <= right){ 11 | int mid = left + (right - left) / 2; //mid = 0 12 | if(a[left] < a[right]){ 13 | System.out.println(a[left]); 14 | break; 15 | } 16 | if(a[left] <= a[mid]){ 17 | left = mid + 1; //left = 1 18 | } 19 | else{ 20 | right = mid; //right = 1 21 | } 22 | if(a[left] == a[right]){ 23 | System.out.println(a[left]);// 1 24 | break; 25 | } 26 | } 27 | } 28 | public static void main (String[] args) { 29 | Scanner s = new Scanner(System.in); 30 | int t = s.nextInt(); 31 | for(int j=0;j 10^18// log(10^18)(base3) = 40; 9 | static int size = 40; 10 | static long p[] = new long[size]; 11 | static long sum[] = new long[size]; 12 | 13 | public static long solve(long n){ 14 | if(n <= 0){ 15 | return 0; 16 | } 17 | long ans = 0; 18 | for(int i = 0; i < size; i++){ 19 | if(sum[i] >= n){ 20 | ans = p[i] + solve(n - p[i]); 21 | break; 22 | } 23 | } 24 | return ans; 25 | } 26 | 27 | public static void main (String[] args) { 28 | Scanner sc = new Scanner(System.in); 29 | p[0] = 1; 30 | sum[0] = 1; 31 | for(int i = 1; i < size; i++){ 32 | p[i] = 3*p[i-1]; 33 | sum[i] = sum[i-1] + p[i]; 34 | } 35 | int t = sc.nextInt(); 36 | while(t-- > 0){ 37 | long n = sc.nextLong(); 38 | System.out.println(solve(n)); 39 | } 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /BinarySearch/TheGabbaTest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | /** 9 | 4 10 4 2 => 3 10 | N = 4 (Total number of player) 11 | M = 10 (Total Magic pills) 12 | X = 4 (Number of pills neeeded to make a player fit) 13 | Y = 2 (Number of pills we get if we retire a player) 14 | 15 | 10 / 4 => 2 players, 2 pills is left, 16 | 1 player are left, 2 more pills 17 | 3 players at maximum 18 | 19 | 0, 1, 2, 3, 4 20 | left = 0, right = 4 21 | mid = 4 / 2 = 2 22 | 23 | if X*mid <= M + (n-mid)*y => true, I can treat mid people 24 | //How many people will be left => n-mid 25 | solution = mid; 26 | left = mid + 1; 27 | else 28 | right = mid - 1; 29 | 30 | 31 | 32 | **/ 33 | public static void main (String[] args) { 34 | Scanner sc = new Scanner(System.in); 35 | long n = sc.nextLong(); 36 | long m = sc.nextLong(); 37 | long x = sc.nextLong(); 38 | long y = sc.nextLong(); 39 | 40 | long left = 0, right = n;//(4, 3) 41 | long sol = 0; 42 | //4 10 4 2 43 | while(left <= right){ 44 | long mid = left + (right - left) / 2; //mid = 4 45 | /* 46 | How many pills do we need? x * mid = 16 47 | How many do we have initially? m = 10 48 | How many pills can we get if we treat mid people? 49 | (n-mid)*y = 0*2 = 0 50 | */ 51 | if(x*mid <= m + (n - mid)*y){ 52 | sol = mid; //solution mid, 3 53 | left = mid + 1;//left = 4 54 | } 55 | else{ 56 | right = mid - 1; //right = 3 57 | } 58 | } 59 | System.out.println(sol); //3 60 | } 61 | } -------------------------------------------------------------------------------- /BinaryTrees[Practice]/InorderTraversal.java: -------------------------------------------------------------------------------- 1 | 2 | // https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | 21 | //[1, 3, 2] 22 | 23 | public void inorder(TreeNode current, List result){ 24 | if(current == null){ 25 | return; 26 | } 27 | inorder(current.left, result); //left 28 | result.add(current.val); 29 | inorder(current.right, result); //right 30 | } 31 | 32 | public List inorderTraversal(TreeNode root) { 33 | List result = new ArrayList<>(); 34 | inorder(root, result); 35 | return result; 36 | } 37 | } -------------------------------------------------------------------------------- /BinaryTrees[Practice]/MinDepth.java: -------------------------------------------------------------------------------- 1 | 2 | //https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/ 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode() {} 10 | * TreeNode(int val) { this.val = val; } 11 | * TreeNode(int val, TreeNode left, TreeNode right) { 12 | * this.val = val; 13 | * this.left = left; 14 | * this.right = right; 15 | * } 16 | * } 17 | */ 18 | class Solution { 19 | public int minDepth(TreeNode root) { 20 | if(root == null){ 21 | return 0; 22 | } 23 | 24 | int hleft = minDepth(root.left); 25 | int hright = minDepth(root.right); 26 | 27 | if(hleft == 0 || hright == 0){ 28 | return 1 + Math.max(hleft, hright); 29 | } 30 | return 1 + Math.min(hleft, hright); 31 | } 32 | } -------------------------------------------------------------------------------- /BinaryTrees[Practice]/PathSum.java: -------------------------------------------------------------------------------- 1 | 2 | // https://leetcode.com/problems/path-sum/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | public boolean hasPathSum(TreeNode root, int targetSum) { 21 | if(root == null){ 22 | return false; 23 | } 24 | 25 | if(root.left == null && root.right == null && root.val == targetSum){ 26 | return true; 27 | } 28 | 29 | boolean hasPathLeft = hasPathSum(root.left, targetSum - root.val); 30 | boolean hasPathRight = hasPathSum(root.right, targetSum - root.val); 31 | 32 | return hasPathLeft || hasPathRight; 33 | } 34 | } -------------------------------------------------------------------------------- /BinaryTrees[Practice]/PostOrderTraversal.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-postorder-traversal/submissions/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode() {} 10 | * TreeNode(int val) { this.val = val; } 11 | * TreeNode(int val, TreeNode left, TreeNode right) { 12 | * this.val = val; 13 | * this.left = left; 14 | * this.right = right; 15 | * } 16 | * } 17 | */ 18 | class Solution { 19 | 20 | public void postOrder(TreeNode current, List result){ 21 | if(current == null){ 22 | return; 23 | } 24 | postOrder(current.left, result); //left 25 | postOrder(current.right, result); //right 26 | result.add(current.val); 27 | } 28 | 29 | public List postorderTraversal(TreeNode root) { 30 | List result = new ArrayList<>(); 31 | postOrder(root, result); 32 | return result; 33 | } 34 | } -------------------------------------------------------------------------------- /BinaryTrees[Practice]/PreOrderTraversal.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/ 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode() {} 12 | * TreeNode(int val) { this.val = val; } 13 | * TreeNode(int val, TreeNode left, TreeNode right) { 14 | * this.val = val; 15 | * this.left = left; 16 | * this.right = right; 17 | * } 18 | * } 19 | */ 20 | class Solution { 21 | 22 | public void preOrder(TreeNode current, List result){ 23 | if(current == null){ 24 | return; 25 | } 26 | result.add(current.val); 27 | preOrder(current.left, result); //left 28 | preOrder(current.right, result); //right 29 | } 30 | 31 | public List preorderTraversal(TreeNode root) { 32 | List result = new ArrayList<>(); 33 | preOrder(root, result); 34 | return result; 35 | } 36 | } -------------------------------------------------------------------------------- /BinaryTrees[Practice]/SameTree.java: -------------------------------------------------------------------------------- 1 | 2 | //https://leetcode.com/problems/same-tree/ 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode() {} 10 | * TreeNode(int val) { this.val = val; } 11 | * TreeNode(int val, TreeNode left, TreeNode right) { 12 | * this.val = val; 13 | * this.left = left; 14 | * this.right = right; 15 | * } 16 | * } 17 | */ 18 | 19 | 20 | //1. p and q both should be not null => if any one is null return false but both null then we return true 21 | //2. if p.val != q.val return false; 22 | //3. boolean leftVal = isSameTree(p.left, q.left) 23 | //3. boolean rightVal = isSameTree(p.right, q.right) 24 | 25 | // return leftVal && rightVal; 26 | // 27 | 28 | // true <=(1,1)[true, true] 29 | 30 | class Solution { 31 | public boolean isSameTree(TreeNode p, TreeNode q) { 32 | if(p == null && q == null){ 33 | return true; 34 | } 35 | if(p == null || q == null){ 36 | return false; 37 | } 38 | //both are not null 39 | if(p.val != q.val){ 40 | return false; 41 | } 42 | //p.val == q.val 43 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 44 | } 45 | } -------------------------------------------------------------------------------- /BitManipulation[Inclass]/BitRotation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | static boolean isRotation(long x, long y) { 8 | int i = 32; 9 | while (i-- > 0) { 10 | long lastBit = (x & 1); 11 | x >>= 1; 12 | x |= (lastBit << 31); 13 | if(x == y){ 14 | return true; 15 | } 16 | } 17 | return false; 18 | } 19 | 20 | // driver code to test above function 21 | public static void main(String[] args) throws IOException{ 22 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 23 | String str[] = br.readLine().strip().split(" "); 24 | long x = Long.parseLong(str[0]); 25 | long y = Long.parseLong(str[1]); 26 | 27 | if (isRotation(x, y)) { 28 | System.out.println("Yes"); 29 | } else { 30 | System.out.println("No"); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /BitManipulation[Inclass]/RightMostDifferent.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | 9 | public static int solve(int m, int n){ //11, 9 10 | int output = m ^ n; // 1011 ^ 1001 = 0010 11 | int i = 32; 12 | count = 1 13 | while(i-- > 0){ 14 | if((output & 1) == 1){ //0001 & 0001 = 0001 15 | return 32 - i; 16 | } 17 | output >>= 1; //0010 => 0001 18 | } 19 | return -1; 20 | } 21 | 22 | 23 | public static void main (String[] args) { 24 | Scanner sc = new Scanner(System.in); 25 | int t = sc.nextInt(); 26 | while(t-- > 0){ 27 | int m = sc.nextInt(); 28 | int n = sc.nextInt(); 29 | System.out.println(solve(m, n)); 30 | } 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /BitManipulation[Inclass]/TwoBits.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | long x = sc.nextLong(); 10 | long y = Long.MAX_VALUE; 11 | 12 | for(long i = 0; i < 63; i++){ 13 | long first = (1l << i); //0000000.....10 14 | for(long j = i + 1; j < 63; j++){ 15 | long second = (1l << j);//0000000000...100 16 | long number = first | second; //00000000.....110 17 | y = Math.min(y, Math.abs(x - number)); 18 | } 19 | } 20 | System.out.println(y); 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /BitManipulation[Postclass]/BitCount.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | long n = sc.nextLong(); 10 | long cnt=0; 11 | while(n>0) 12 | { 13 | long p=n%2l; 14 | cnt+=p; 15 | n/=2l; 16 | } 17 | System.out.println(cnt); 18 | } 19 | } -------------------------------------------------------------------------------- /BitManipulation[Postclass]/BitDifference.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | //1,3 => 3, 1 8 | //(nc2) * 2 9 | 10 | 11 | static long mod = (long) 1e9+7; 12 | 13 | public static void main (String[] args) { 14 | Scanner sc = new Scanner(System.in); 15 | int n = sc.nextInt(); 16 | long[] array = new long[n]; 17 | for(int i = 0; i < n; i++){ 18 | array[i] = sc.nextLong(); 19 | } 20 | long result = 0; 21 | for(int i = 0; i < 64; i++){ 22 | long count = 0; //how many ones in that column bit 23 | long bitshift = (1l << i); //000.....10 24 | for(int j = 0; j < n; j++){ 25 | if((array[j] & bitshift) == 0){ 26 | count++; //counting number of 0's last bit + second last bit 27 | } 28 | } 29 | result += (count*(n - count)*2); 30 | result %= mod; 31 | } 32 | System.out.println(result); 33 | } 34 | } -------------------------------------------------------------------------------- /BitManipulation[Postclass]/FixingTheMiddle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.lang.*; 4 | 5 | class Main { 6 | public static void main (String[] args){ 7 | 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | 11 | while(t-- > 0) 12 | { 13 | long n= sc.nextLong(); 14 | 15 | int numberOfBits=1+(int)Math.floor(Math.log(n)/Math.log(2)); //finding number of bits 16 | 17 | if(numberOfBits%2!=0) //if bits are odd 18 | { 19 | n=n^(1<<(numberOfBits/2)); 20 | } 21 | else //else if bits are even 22 | { 23 | n=n^(1<<(numberOfBits/2)); 24 | n=n^(1<<((numberOfBits/2)-1)); 25 | } 26 | System.out.println(n); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /CircularLinkedList[InClass]/CheckCLL.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | int val; 5 | 6 | Node(int val) { 7 | this.val = val; 8 | next = null; 9 | } 10 | } 11 | */ 12 | 13 | public static int check(Node head) { 14 | /* 15 | a. 1->2->3->4->null 16 | b. 1->2->3->1 17 | */ 18 | 19 | Node temp = head.next; 20 | while(temp != null && temp != head){ 21 | temp = temp.next; 22 | } 23 | if(temp == null) 24 | return 0; 25 | return 1; 26 | } -------------------------------------------------------------------------------- /CircularLinkedList[InClass]/InsertionInCLL.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | Node prev; 5 | int val; 6 | 7 | Node(int val) { 8 | this.val = val; 9 | next = null; 10 | prev = null; 11 | } 12 | } 13 | */ 14 | public static Node Reverse(Node head) { 15 | Node temp = null; 16 | Node current = head; 17 | 18 | while (current != null) { 19 | temp = current.prev; 20 | current.prev = current.next; 21 | current.next = temp; 22 | current = current.prev; 23 | } 24 | 25 | if (temp != null) { 26 | head = temp.prev; 27 | } 28 | return head; 29 | } -------------------------------------------------------------------------------- /Combinatorics[InClass]/CombinationsAllPair.java: -------------------------------------------------------------------------------- 1 | static int AllPair(int N){ 2 | // for(int i = 1; i < N; i++){ 3 | // System.out.print("(" +i +", " + (N - i) +")"); 4 | // } 5 | // System.out.println(); 6 | return N-1; 7 | } -------------------------------------------------------------------------------- /Combinatorics[InClass]/Pascals.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static int MAX = 3001; 8 | public static long MOD = (long) 1e9 + 7; 9 | public static void main (String[] args) { 10 | /* 11 | It is not exactly a 2d table 12 | 13 | [null,null, null, null ......]x 3000 14 | [[],[],[],[] ......]x 3000 15 | */ 16 | ArrayList[] array = new ArrayList[MAX]; 17 | //int[] array = new int[MAX]; 18 | //[0,0,0,...0]x 3000 19 | for(int i = 0; i < MAX; i++){ 20 | array[i] = new ArrayList(); 21 | } 22 | 23 | Scanner sc = new Scanner(System.in); 24 | int n = sc.nextInt(); 25 | 26 | // n = 3 27 | /* 28 | [ 29 | [1l], 30 | [1l, 1l], 31 | [1l, 2l, 1l], 32 | [1l, 3l, 3l, 1l] 33 | ] 34 | */ 35 | 36 | for(int i = 0; i <= n; i++){ 37 | for(int j = 0; j <= i; j++){ 38 | if(j == 0 || j == i){ 39 | array[i].add(Long.valueOf(1)); 40 | } 41 | else{ 42 | array[i].add((array[i-1].get(j-1) + array[i-1].get(j)) % MOD); 43 | } 44 | } 45 | } 46 | 47 | for(int j = 0; j < array[n].size(); j++){ 48 | System.out.print(array[n].get(j) + " "); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /Combinatorics[PostClass]/NumberSubsequences.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | static long mod = (long) (1e9 + 7); 8 | public static void main (String[] args) { 9 | Scanner sc = new Scanner(System.in); 10 | String s = sc.nextLine(); 11 | long ans = 1l, c = 0l; 12 | for(int i = 0; i < s.length(); i++){ 13 | if(s.charAt(i) == 'a'){ 14 | c++; 15 | } 16 | if(s.charAt(i) == 'b'){ 17 | ans = (ans*(c+1)) % mod; 18 | c = 0; 19 | } 20 | } 21 | ans = (ans*(c+1)) % mod; 22 | System.out.println((ans - 1) % mod); 23 | } 24 | } -------------------------------------------------------------------------------- /Combinatorics[PostClass]/SimpleColours.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | long n = sc.nextLong(); 10 | long k = sc.nextLong(); 11 | 12 | long mod = (long) 1e9 + 7; 13 | long ans=k; 14 | for(int i=0;i= coin){ 17 | minValue = Math.min(minValue, dp[v - coin]); 18 | } 19 | } 20 | dp[v] = minValue; 21 | if(minValue != Integer.MAX_VALUE){ 22 | dp[v]++; 23 | } 24 | } 25 | 26 | return dp[value]; 27 | } 28 | 29 | public static void main (String[] args) { 30 | Scanner sc = new Scanner(System.in); 31 | int t = sc.nextInt(); 32 | while(t-- > 0){ 33 | int value = sc.nextInt(); 34 | int n = sc.nextInt(); 35 | int coins[] = new int[n]; 36 | for(int i = 0; i < n; i++){ 37 | coins[i] = sc.nextInt(); 38 | } 39 | int ans = minCoins(coins, n, value); 40 | if(ans == Integer.MAX_VALUE){ 41 | System.out.println("Not Possible"); 42 | } 43 | else{ 44 | System.out.println(ans); 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /DP[InClass]/SticklerThief.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | public static int maxLoot(int houses[], int n, int[] dp){ 9 | dp[0] = houses[0]; 10 | dp[1] = Math.max(houses[0], houses[1]); 11 | for(int i = 2; i < n; i++){ 12 | dp[i] = Math.max(dp[i-1], dp[i-2] + houses[i]); 13 | } 14 | return dp[n-1]; 15 | } 16 | 17 | //sc.nextInt(); //regex parsing 18 | // ..5 25....... 19 | //br.readLine(); //fast 20 | public static void main (String[] args) throws IOException{ 21 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 22 | int t = Integer.parseInt(br.readLine().trim()); 23 | int houses[] = new int[10001]; 24 | int dp[] = new int[10001]; 25 | while(t-- > 0){ 26 | int n = Integer.parseInt(br.readLine().trim()); 27 | String[] str = br.readLine().trim().split(" "); 28 | for(int i = 0; i < n; i++){ 29 | houses[i] = Integer.parseInt(str[i]); 30 | } 31 | System.out.println(maxLoot(houses, n, dp)); 32 | } 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /DP[PostClass]/IncreasingSubsequences.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | static long mod = (long) 1e9 + 7; 8 | public static long longestIncresing(long a[], int n){ 9 | 10 | long dp[] = new long[n]; 11 | Arrays.fill(dp, 1); 12 | //5 4 3 2 1 13 | for(int i = 1; i < n; i++){ 14 | for(int j = 0; j < i; j++){ 15 | if(a[i] > a[j]){ 16 | dp[i] += dp[j]; 17 | dp[i] %= mod; 18 | } 19 | } 20 | } 21 | 22 | long ans = 0; 23 | for(int i = 0; i < n; i++){ 24 | ans += dp[i]; 25 | ans %= mod; 26 | } 27 | return ans; 28 | } 29 | 30 | public static void main (String[] args) { 31 | Scanner sc = new Scanner(System.in); 32 | int t = sc.nextInt(); 33 | while(t-- > 0){ 34 | int n = sc.nextInt(); 35 | long a[] = new long[n]; 36 | for(int i = 0; i < n; i++){ 37 | a[i] = sc.nextLong(); 38 | } 39 | System.out.println(longestIncresing(a, n)); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /DP[PostClass]/LongestIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | public static int longestIncresing(int a[], int n){ 9 | 10 | int dp[] = new int[n]; 11 | dp[0] = 1; 12 | //5 4 3 2 1 13 | for(int i = 1; i < n; i++){ 14 | int max_value = Integer.MIN_VALUE; 15 | for(int j = 0; j < i; j++){ 16 | if(a[i] > a[j]){ 17 | max_value = Math.max(max_value, dp[j]); 18 | } 19 | } 20 | if(max_value == Integer.MIN_VALUE){ 21 | dp[i] = 1; 22 | } 23 | else{ 24 | dp[i] = max_value + 1; 25 | } 26 | } 27 | 28 | int ans = 1; 29 | for(int i = 0; i < n; i++){ 30 | ans = Math.max(ans, dp[i]); 31 | } 32 | return ans; 33 | } 34 | 35 | public static void main (String[] args) { 36 | Scanner sc = new Scanner(System.in); 37 | int t = sc.nextInt(); 38 | while(t-- > 0){ 39 | int n = sc.nextInt(); 40 | int a[] = new int[n]; 41 | for(int i = 0; i < n; i++){ 42 | a[i] = sc.nextInt(); 43 | } 44 | System.out.println(longestIncresing(a, n)); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /DP[PostClass]/StepsToReachInTop.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | long[] dp = new long[51]; 10 | dp[1] = 1; 11 | dp[2] = 2; 12 | dp[3] = 4; 13 | for(int i = 4; i <= 50; i++){ 14 | dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; 15 | } 16 | int n = sc.nextInt(); 17 | System.out.println(dp[n]); 18 | } 19 | } -------------------------------------------------------------------------------- /Dequeue[Inclass]/MaximumofAllSize.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | int k = sc.nextInt(); 12 | int a[] = new int[n]; 13 | for(int i = 0; i < n; i++){ 14 | a[i] = sc.nextInt(); 15 | } 16 | 17 | //1 2 3 1 4 5 2 3 1 18 | //0 1 2 3 4 5 6 7 8 19 | 20 | Deque dq = new LinkedList<>(); 21 | //First k elements just add 22 | 23 | //dq: [2] 24 | int i; 25 | for(i = 0; i < k; i++){ 26 | //removing useless 27 | while(!dq.isEmpty() && a[dq.peekLast()] <= a[i]){ 28 | dq.removeLast(); 29 | } 30 | dq.addLast(i); //index; 31 | } 32 | //1 2 3 1 4 5 2 3 1 33 | //0 1 2 3 4 5 6 7 8 34 | //dq: [2] 35 | //Output: 3 36 | 37 | //5 3 2 1 38 | //6 7 8 9 39 | 40 | //dq: 7 8 9 41 | //6 <= 9 - 3 42 | for(; i S = new LinkedList<>(); 23 | Deque G = new LinkedList<>(); 24 | 25 | int i; 26 | for(i = 0; i < k; i++){ 27 | //removing useless 28 | while(!S.isEmpty() && a[S.peekLast()] >= a[i]){ 29 | S.removeLast(); 30 | } 31 | while(!G.isEmpty() && a[G.peekLast()] <= a[i]){ 32 | G.removeLast(); 33 | } 34 | S.addLast(i); 35 | G.addLast(i); 36 | } 37 | long sum = 0; 38 | for(; i = a[i]){ 50 | S.removeLast(); 51 | } 52 | while(!G.isEmpty() && a[G.peekLast()] <= a[i]){ 53 | G.removeLast(); 54 | } 55 | S.addLast(i); 56 | G.addLast(i); 57 | } 58 | sum += a[S.peekFirst()] + a[G.peekFirst()]; 59 | System.out.println(sum); 60 | } 61 | } -------------------------------------------------------------------------------- /Dequeue[Postclass]/CircularRotation.java: -------------------------------------------------------------------------------- 1 | static void circularRotate(Deque deq, int d, int n) 2 | { 3 | // Push first d elements 4 | // from last to the beginning 5 | for (int i = 0; i < d%n; i++) { 6 | int val = deq.peekLast(); 7 | deq.removeLast(); 8 | deq.addFirst(val); 9 | } 10 | } -------------------------------------------------------------------------------- /DoubleLinkedList[InClass]/InsertNodeHead.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | class Node { 4 | Node next; 5 | Node prev; 6 | int val; 7 | 8 | Node(int val) { 9 | this.val = val; 10 | next = null; 11 | prev = null; 12 | } 13 | } 14 | */ 15 | 16 | 17 | public static Node insertnew(Node head,int k) { 18 | Node newnode = new Node(k); //(null, k, null) 19 | if(head == null){ //linked list was empty 20 | return newnode; //(null, k, null) 21 | } 22 | //head = //(address(newnode), head.val, adress(head.next))............. 23 | newnode.next = head;//(null, k, add(head)) 24 | head.prev = newnode;// 25 | return newnode; 26 | } -------------------------------------------------------------------------------- /DoubleLinkedList[InClass]/InsertNodeKthPosition.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | class Node { 4 | Node next; 5 | Node prev; 6 | int val; 7 | 8 | Node(int val) { 9 | this.val = val; 10 | next = null; 11 | prev = null; 12 | } 13 | } 14 | */ 15 | 16 | /** 17 | 1. beginning 18 | 2. middle 19 | 3. end 20 | 21 | **/ 22 | public static Node insertnew(Node head,int K, int pos) { 23 | Node newnode = new Node(K); 24 | if(pos == 1){ 25 | //beginning 26 | newnode.next = head; 27 | head.prev = newnode; 28 | return newnode; 29 | } 30 | //k = 0, pos = 3, LL = 1->(temp, 2)->(temp2, 3)->4->5; 31 | int cnt = 1; 32 | Node temp = head; //temp = 2 33 | while(cnt < pos - 1){ 34 | temp = temp.next; 35 | cnt++; 36 | } 37 | //temp is pointing to 1 before position 38 | if(temp.next == null){ 39 | //end 40 | newnode.prev = temp; 41 | temp.next = newnode; 42 | } 43 | else{ 44 | Node temp2 = temp.next; 45 | 46 | newnode.next = temp2; 47 | temp2.prev = newnode; 48 | 49 | temp.next = newnode; 50 | newnode.prev = temp; 51 | } 52 | return head; 53 | } -------------------------------------------------------------------------------- /DoubleLinkedList[PostClass]/DeleteElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | class Node { 4 | Node next; 5 | Node prev; 6 | int val; 7 | 8 | Node(int val) { 9 | this.val = val; 10 | next = null; 11 | prev = null; 12 | } 13 | } 14 | */ 15 | 16 | public static Node deleteElement(Node head, int k) { 17 | 18 | Node start = head; 19 | Node end = head; 20 | while(k-- > 0){ 21 | end = end.next; 22 | } 23 | if(end == null){ 24 | start = start.next; 25 | start.prev = null; 26 | return start; 27 | } 28 | 29 | while(end.next != null){ 30 | start = start.next; 31 | end = end.next; 32 | } 33 | 34 | //create link between s.next and s.next.next 35 | if(start.next.next == null){ 36 | //deleting element; 37 | start.next = null; 38 | return head; 39 | } 40 | 41 | start.next.next.prev = start; 42 | start.next = start.next.next; 43 | 44 | return head; 45 | 46 | } -------------------------------------------------------------------------------- /DoubleLinkedList[PostClass]/ReverseElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | Node prev; 5 | int val; 6 | 7 | Node(int val) { 8 | this.val = val; 9 | next = null; 10 | prev = null; 11 | } 12 | } 13 | */ 14 | public static Node Reverse(Node head) { 15 | Node temp = null; 16 | Node current = head; 17 | 18 | while (current != null) { 19 | temp = current.prev; 20 | current.prev = current.next; 21 | current.next = temp; 22 | current = current.prev; 23 | } 24 | 25 | if (temp != null) { 26 | head = temp.prev; 27 | } 28 | return head; 29 | } -------------------------------------------------------------------------------- /FundementalsInJava[InClass]/FahrenheitToCelsius.java: -------------------------------------------------------------------------------- 1 | static int FahrenheitToCelsius(int F){ 2 | return ((F-32)/9)*5; 3 | } 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /FundementalsInJava[InClass]/Operators.java: -------------------------------------------------------------------------------- 1 | static void Operators(int a,int b){ 2 | int x= a+b; 3 | System.out.println(x); 4 | x=a-b; 5 | System.out.println(x); 6 | x=a*b; 7 | System.out.println(x); 8 | x=a/b; 9 | System.out.println(x); 10 | } -------------------------------------------------------------------------------- /FundementalsInJava[InClass]/SimpleInterest.java: -------------------------------------------------------------------------------- 1 | static int SimpleInterest(int P, int R, int Tm){ 2 | return (P*Tm*R)/100; 3 | } -------------------------------------------------------------------------------- /FundementalsInJava[InClass]/StartCoding.java: -------------------------------------------------------------------------------- 1 | static void printHelloWorld() 2 | { 3 | System.out.println("Hello World"); 4 | } -------------------------------------------------------------------------------- /HeapSort[Inclass]/MaxInQueue.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 10 | int n = sc.nextInt(); 11 | while(n-- > 0){ 12 | pq.add(sc.nextLong()); 13 | } 14 | 15 | int q = sc.nextInt(); 16 | while(q-- > 0){ 17 | int op = sc.nextInt(); 18 | if(op == 1){ 19 | pq.add(sc.nextLong()); 20 | } 21 | else{ 22 | System.out.println(pq.peek()); 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /HeapSort[Inclass]/MinimumRopeCost.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | while(t-- > 0){ 11 | int n =sc.nextInt(); 12 | PriorityQueue pq = new PriorityQueue<>(); 13 | for(int i = 0; i < n; i++){ 14 | pq.add(sc.nextLong()); 15 | } 16 | long cost = 0l; 17 | while(pq.size() > 1){ 18 | long x = pq.remove(); 19 | long y = pq.remove(); 20 | cost += (x+y); 21 | pq.add(x+y); 22 | } 23 | System.out.println(cost); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /HeapSort[PostClass]/MaxDistinctBooks.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | 9 | /** 10 | 11 | 5 7 5 5 1 2 2, k = 4 12 | 5 | 3 13 | 7 | 1 14 | 1 | 1 15 | 2 | 2 16 | 17 | 18 | Max Heap = 1, 1, 1 = 3 19 | 3 - 2 20 | 2 - 1 21 | 22 | total = 7 23 | distinct = 4 - (4 - 3) 24 | 25 | difference = 3 26 | 27 | */ 28 | 29 | 30 | public static void main (String[] args) throws IOException{ 31 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 32 | int t = Integer.parseInt(br.readLine()); 33 | while(t-- > 0){ 34 | String str[] = br.readLine().split(" "); 35 | int n = Integer.parseInt(str[0]); 36 | int k = Integer.parseInt(str[1]); 37 | HashMap hm = new HashMap<>(); 38 | str = br.readLine().split(" "); 39 | int value, duplicates = 0; 40 | for(int i = 0; i < n; i++){ 41 | value = Integer.parseInt(str[i]); 42 | if(hm.containsKey(value)){ 43 | duplicates++; 44 | hm.put(value, hm.get(value) + 1); 45 | } 46 | else{ 47 | hm.put(value, 1); 48 | } 49 | } 50 | if(k <= duplicates){ 51 | System.out.println(hm.size()); 52 | } 53 | else{ 54 | System.out.println(hm.size() - (k - duplicates)); 55 | } 56 | 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /HeapSort[PostClass]/MaxProdKIntegers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | while(t-- > 0){ 11 | int n = sc.nextInt(); 12 | int k = sc.nextInt(); 13 | long[] arr = new long[n]; 14 | for(int i = 0; i < n; i++){ 15 | arr[i] = sc.nextLong(); 16 | } 17 | Arrays.sort(arr); 18 | long ans = 1; 19 | for(int i = n - k; i < n; i++){ 20 | ans *= arr[i]; 21 | } 22 | System.out.println(ans); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /HeapSort[PostClass]/SequenceFinder.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | 7 | class MinPair implements Comparable{ 8 | long value; 9 | int index; 10 | MinPair(long value, int index){ 11 | this.value = value; 12 | this.index = index; 13 | } 14 | public int compareTo(MinPair mp) { 15 | if(this.value > mp.value){ 16 | return 1; 17 | } 18 | else if(this.value == mp.value){ 19 | return 0; 20 | } 21 | else{ 22 | return -1; 23 | } 24 | } 25 | } 26 | 27 | class MaxPair implements Comparable{ 28 | long value; 29 | int index; 30 | MaxPair(long value, int index){ 31 | this.value = value; 32 | this.index = index; 33 | } 34 | public int compareTo(MaxPair mp) { 35 | if(this.value > mp.value){ 36 | return -1; 37 | } 38 | else if(this.value == mp.value){ 39 | return 0; 40 | } 41 | else{ 42 | return 1; 43 | } 44 | } 45 | } 46 | 47 | class Main { 48 | public static void main (String[] args) { 49 | Scanner sc = new Scanner(System.in); 50 | int n = sc.nextInt(); 51 | long arr[] = new long[3*n]; 52 | for(int i = 0; i < 3*n; i++){ 53 | arr[i] = sc.nextLong(); 54 | } 55 | 56 | PriorityQueue minHeap1 = new PriorityQueue<>(); 57 | PriorityQueue maxHeap = new PriorityQueue<>(); 58 | PriorityQueue minHeap2 = new PriorityQueue<>(); 59 | 60 | int c[] = new int[3*n]; 61 | Arrays.fill(c, 1); 62 | long sum1 = 0, sum2 = 0; 63 | for(int i = 0; i < n; i++){ 64 | minHeap1.add(new MinPair(arr[i], i)); 65 | sum1 += arr[i]; 66 | } 67 | for(int i = n; i < 3*n; i++){ 68 | maxHeap.add(new MaxPair(arr[i], i)); 69 | sum2 += arr[i]; 70 | } 71 | for(int i = 0; i < n; i++){ 72 | MaxPair pair = maxHeap.remove(); 73 | sum2 -= pair.value; 74 | c[pair.index] = 0; 75 | minHeap2.add(new MinPair(pair.value, pair.index)); 76 | } 77 | 78 | long ans = sum1 - sum2; 79 | for(int i = n; i < 2*n; i++){ 80 | if(c[i] == 1){ 81 | sum2 -= arr[i]; 82 | MinPair pair = minHeap2.remove(); 83 | while(pair.index <= i){ 84 | pair = minHeap2.remove(); 85 | } 86 | sum2 += pair.value; 87 | c[pair.index] = 1; 88 | } 89 | minHeap1.add(new MinPair(arr[i], i)); 90 | sum1 += arr[i]; 91 | c[i] = 1; 92 | MinPair pair = minHeap1.remove(); 93 | sum1 -= pair.value; 94 | c[pair.index] = 0; 95 | ans = Math.max(ans, sum1 - sum2); 96 | } 97 | System.out.println(ans); 98 | } 99 | } -------------------------------------------------------------------------------- /Heaps[InClass]/Chocolates.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | int k = sc.nextInt(); 11 | 12 | PriorityQueue pq_max = new PriorityQueue<>(Collections.reverseOrder()); 13 | for(int i = 0; i < n; i++){ 14 | pq_max.add(sc.nextLong()); 15 | } 16 | long ans = 0; 17 | for(int i = 0; i < k; i++){ 18 | long value = pq_max.peek(); 19 | ans += value; 20 | pq_max.remove(); 21 | pq_max.add(value / 2); 22 | } 23 | System.out.println(ans); 24 | } 25 | } -------------------------------------------------------------------------------- /Heaps[InClass]/FindMedian.java: -------------------------------------------------------------------------------- 1 | static PriorityQueue smaller = new PriorityQueue<>(Collections.reverseOrder()); //Max heap for lower values 2 | static PriorityQueue larger = new PriorityQueue<>(); // Min heap for larger values 3 | public static double getMedian(int X) //X = 4 4 | { 5 | //smaller = [4, 10] and larger = [15] 6 | //adding 7 | if(smaller.size() == 0 || smaller.peek() >= X){ 8 | smaller.add(X); 9 | } 10 | else{ 11 | larger.add(X); 12 | } 13 | 14 | //shifting 15 | if(smaller.size() - larger.size() > 1){ 16 | larger.add(smaller.remove()); 17 | } 18 | else if(larger.size() - smaller.size() > 1){ 19 | smaller.add(larger.remove()); 20 | } 21 | 22 | //smaller = [4, 5] and larger = [10, 15] 23 | //odd elements 24 | if(smaller.size() > larger.size()){ 25 | return Double.valueOf(smaller.peek()); 26 | } 27 | 28 | else if(larger.size() > smaller.size()){ 29 | return Double.valueOf(larger.peek()); 30 | } 31 | 32 | //even element 33 | return (Double.valueOf(smaller.peek()) + Double.valueOf(larger.peek())) / 2.0; 34 | } -------------------------------------------------------------------------------- /Heaps[Postclass]/AnotherArrayOperation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | PriorityQueue minHeap = new PriorityQueue<>(); 10 | PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 11 | 12 | int n = sc.nextInt(); 13 | int q = sc.nextInt(); 14 | long sum = 0; 15 | for(int i = 0; i < n; i++){ 16 | long value = sc.nextLong(); 17 | minHeap.add(value); 18 | maxHeap.add(value); 19 | sum += value; 20 | } 21 | long ans[] = new long[n]; 22 | for(int i = 0; i < n; i++){ 23 | ans[i] = sum; 24 | long minValue = minHeap.remove(); 25 | long maxValue = maxHeap.remove(); 26 | minHeap.add(maxValue - minValue); 27 | maxHeap.add(maxValue - minValue); 28 | sum -= minValue; 29 | sum -= maxValue; 30 | sum += (maxValue - minValue); 31 | } 32 | for(int i = 0; i < q; i++){ 33 | int k = sc.nextInt(); 34 | System.out.println(ans[k]); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Heaps[Postclass]/InterviewQuestions.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | PriorityQueue minHeap = new PriorityQueue<>(); 10 | PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 11 | 12 | int t = sc.nextInt(); 13 | while(t-- > 0){ 14 | int op = sc.nextInt(); 15 | if(op == 1){ 16 | int value = sc.nextInt(); 17 | minHeap.add(value); 18 | maxHeap.add(value); 19 | } 20 | else if(op == 2){ 21 | int value = sc.nextInt(); 22 | boolean minPresent = minHeap.remove(value); 23 | boolean maxPresent = maxHeap.remove(value); 24 | if(!minPresent && !maxPresent){ 25 | System.out.println(-1); 26 | } 27 | } 28 | else if(op == 3){ 29 | if(maxHeap.size() == 0){ 30 | System.out.println(-1); 31 | } 32 | else{ 33 | System.out.println(maxHeap.peek()); 34 | } 35 | } 36 | else{ 37 | if(minHeap.size() == 0){ 38 | System.out.println(-1); 39 | } 40 | else{ 41 | System.out.println(minHeap.peek()); 42 | } 43 | } 44 | } 45 | 46 | } 47 | } -------------------------------------------------------------------------------- /Heaps[Postclass]/KthLargest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | while(t-- > 0){ 11 | PriorityQueue pq = new PriorityQueue<>(); 12 | int n = sc.nextInt(); 13 | int k = sc.nextInt(); 14 | for(int i = 1; i<=n; i++){ 15 | if(i < k){ 16 | pq.add(sc.nextLong()); 17 | System.out.print("-1 "); 18 | } 19 | else if( i == k ){ 20 | pq.add(sc.nextLong()); 21 | System.out.print(pq.peek()+ " "); 22 | } 23 | else{ 24 | long value = sc.nextLong(); 25 | if(value > pq.peek()){ 26 | pq.remove(); 27 | pq.add(value); 28 | } 29 | System.out.print(pq.peek()+" "); 30 | } 31 | } 32 | System.out.println(); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /IntroductionArray[Inclass]/MaxAndMin.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | class Main 4 | { 5 | 6 | public static void main(String[] args){ 7 | Scanner sc = new Scanner(System.in); 8 | int t = sc.nextInt(); 9 | 10 | while (t-- > 0) { 11 | 12 | int n = sc.nextInt(); 13 | int[] arr = new int[n]; 14 | 15 | for(int i = 0; i < n; i++) 16 | arr[i] = sc.nextInt(); 17 | 18 | findMinMax(arr, n); 19 | System.out.println(); 20 | } 21 | } 22 | public static void findMinMax(int arr[], int n) 23 | { 24 | int min = Integer.MAX_VALUE; 25 | int max = Integer.MIN_VALUE; 26 | 27 | for(int i = 0; i < n; i++) 28 | { 29 | min = Math.min(arr[i], min); 30 | max = Math.max(arr[i], max); 31 | } 32 | 33 | System.out.print(max + " " + min); 34 | } 35 | } -------------------------------------------------------------------------------- /IntroductionArray[Inclass]/Negative.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | class Main 7 | { 8 | public static void main (String[] args) throws java.lang.Exception 9 | { 10 | Scanner sc = new Scanner(System.in); 11 | int n = sc.nextInt(); 12 | int a[] = new int[n]; 13 | for(int i=0;i first) { 23 | third = second; 24 | second = first; 25 | first = arr[i]; 26 | } 27 | 28 | /* If arr[i] is in between first and 29 | second then update second */ 30 | else if (arr[i] > second) { 31 | third = second; 32 | second = arr[i]; 33 | } 34 | 35 | else if (arr[i] > third) 36 | third = arr[i]; 37 | } 38 | 39 | System.out.println(first + " " + second + " " + third); 40 | } 41 | 42 | 43 | public static void main (String[] args) { 44 | Scanner sc = new Scanner(System.in); 45 | int t = sc.nextInt(); 46 | while(t-- > 0){ 47 | int n = sc.nextInt(); 48 | int a[] = new int[n]; 49 | for(int i=0;ia[i]){ 21 | System.out.println("NO"); 22 | return; 23 | } 24 | cnt++; 25 | } 26 | System.out.println("YES"); 27 | } 28 | } -------------------------------------------------------------------------------- /IntroductionToLoopAndControls[InClass]/Armstrong.java: -------------------------------------------------------------------------------- 1 | static boolean isArmstrong(int N) 2 | { 3 | int num = N; 4 | int sum = 0; 5 | while(N > 0) 6 | { 7 | int digit = N%10; 8 | sum += digit*digit*digit; 9 | N = N/10; 10 | } 11 | if(num == sum) 12 | return true; 13 | else return false; 14 | } -------------------------------------------------------------------------------- /IntroductionToLoopAndControls[InClass]/MaxInteger.java: -------------------------------------------------------------------------------- 1 | static int MaxInteger(int a ,int b, int c){ 2 | if(a>=b && a>=c){ 3 | return a; 4 | } 5 | if(b>=a && b>=c){ 6 | return b; 7 | } 8 | return c; 9 | } -------------------------------------------------------------------------------- /IntroductionToLoopAndControls[InClass]/Palindrome.java: -------------------------------------------------------------------------------- 1 | static boolean isPalindrome(int N) 2 | { 3 | int sum = 0; 4 | int rev = N; 5 | while(N > 0) 6 | { 7 | int digit = N%10; 8 | sum = sum*10+digit; 9 | N = N/10; 10 | } 11 | if(rev == sum) 12 | return true; 13 | else return false; 14 | } -------------------------------------------------------------------------------- /IntroductionToLoopAndControls[PostClass]/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main 6 | { 7 | public static void main (String[] args) 8 | { 9 | 10 | Scanner sc = new Scanner(System.in); 11 | int x= sc.nextInt(); 12 | fizzbuzz(x); 13 | } 14 | 15 | static void fizzbuzz(int n){ 16 | for(int i=1;i<=n;i++){ 17 | if(i%3==0 && i%5==0){System.out.print("FizzBuzz ");} 18 | else if(i%5==0){System.out.print("Buzz ");} 19 | else if(i%3==0){System.out.print("Fizz ");} 20 | else{System.out.print(i+" ");} 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /IntroductionToLoopAndControls[PostClass]/Pattern.java: -------------------------------------------------------------------------------- 1 | static void pattern(int n){ 2 | for(int i=1;i<=n;i++){ 3 | for(int j=1;j<=i;j++){ 4 | System.out.print(j + " "); 5 | } 6 | System.out.println(); 7 | } 8 | } -------------------------------------------------------------------------------- /IntroductionToLoopAndControls[PostClass]/StudentGrades.java: -------------------------------------------------------------------------------- 1 | static char grades(int a, int b, int c, int d, int e) 2 | { 3 | int sum = a+b+c+d+e; 4 | int per = sum/5; 5 | if(per >= 80) 6 | return 'A'; 7 | else if(per >= 60) 8 | return 'B'; 9 | else if(per >= 40) 10 | return 'C'; 11 | else 12 | return 'D'; 13 | 14 | } -------------------------------------------------------------------------------- /JavaCollections[Inclass]/CountDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | int a[] = new int[n]; 11 | for(int i = 0; i < n; i++){ 12 | a[i] = sc.nextInt(); 13 | } 14 | 15 | HashMap hm = new HashMap<>(); 16 | /*Inserting the array in hashmap*/ 17 | for(int i = 0; i < n; i++){ 18 | if(hm.containsKey(a[i])){ 19 | /*number already present*/ 20 | //2 3 => 2 4 21 | //a[i] = 2, hm.get(a[i]) = 4 22 | hm.put(a[i], hm.get(a[i]) + 1); 23 | } 24 | else{ 25 | /*number not present*/ 26 | hm.put(a[i], Integer.valueOf(1)); 27 | } 28 | } 29 | /* 30 | which entries value is greater than zero 31 | By Iterating over hashmap 32 | */ 33 | ArrayList keys = new ArrayList<>(); 34 | for(Integer key: hm.keySet()){ 35 | if(hm.get(key) > 1){ 36 | keys.add(key); 37 | } 38 | } 39 | 40 | /*Sorted order*/ 41 | Collections.sort(keys); //1 2 42 | 43 | for(Integer key: keys){ 44 | System.out.println(key+" "+hm.get(key)); //1 4 \n 2 3 45 | } 46 | 47 | 48 | } 49 | } -------------------------------------------------------------------------------- /JavaCollections[Inclass]/FindPairsWithGivenSum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | /* 8 | n = 4, k = 6 9 | 1 5 7 1 10 | (1, 5) (1, 7) (1, 1) (5, 7) (5, 1) (7, 1) 11 | 2 pairs 12 | 13 | N = 7, k = 6 14 | 1 5 7 5 1 1 5 15 | Output: 9 16 | 17 | */ 18 | public static void main (String[] args) { 19 | Scanner sc = new Scanner(System.in); 20 | int n = sc.nextInt(); 21 | int k = sc.nextInt(); 22 | HashMap hm = new HashMap<>(); 23 | long ans = 0; 24 | //1 5 7 1 5, k = 6 25 | //hm = [{1, 2}, {5, 2}, {7, 1}] 26 | for(int i = 0; i < n; i++){ 27 | int ele = sc.nextInt(); // 1 5 7 1 5 28 | if(hm.containsKey(k - ele)){ 29 | ans += hm.get(k - ele); // ans = 1 + 1 + 2 30 | } 31 | if(hm.containsKey(ele)){ 32 | /*number already present*/ 33 | hm.put(ele, hm.get(ele) + 1); 34 | } 35 | else{ 36 | /*number not present*/ 37 | hm.put(ele, Integer.valueOf(1)); 38 | } 39 | } 40 | System.out.println(ans); 41 | } 42 | } -------------------------------------------------------------------------------- /JavaCollections[PostClass]/CountDistincElements.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | HashMap m = new HashMap<>(); 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | int k = sc.nextInt(); 12 | long a[] = new long[n]; 13 | for(int i=0;i0) 11 | { 12 | int n = sc.nextInt(); 13 | sc.nextLine(); 14 | HashMap ss = new HashMap<>(); 15 | char A[] = new char[n]; 16 | int B[] = new int[n]; 17 | String str[] = sc.nextLine().strip().split(" "); 18 | ArrayList keys = new ArrayList<>(); 19 | for(int i=0;i [(1, address(2)) -> e3 -> (2, null)] 38 | public static Node insertEnd(int val){ 39 | if(h3 == null){ 40 | h3 = new Node(val); 41 | e3 = h3; 42 | } 43 | else{ 44 | Node newnode = new Node(val); //(2, null) 45 | e3.next = newnode; 46 | e3 = e3.next; 47 | } 48 | return h3; 49 | } 50 | 51 | 52 | public static Node Merge (Node h1, Node h2){ 53 | h3 = null; 54 | e3 = null; 55 | while(h1!=null && h2!=null){ 56 | if(h1.val <= h2.val){ 57 | h3 = insertEnd(h1.val); 58 | h1 = h1.next; 59 | } 60 | else{ 61 | h3 = insertEnd(h2.val); 62 | h2 = h2.next; 63 | } 64 | } 65 | while(h1 != null){ 66 | h3 = insertEnd(h1.val); 67 | h1 = h1.next; 68 | } 69 | while(h2 != null){ 70 | h3 = insertEnd(h2.val); 71 | h2 = h2.next; 72 | } 73 | return h3; 74 | } -------------------------------------------------------------------------------- /LinkedList-II[Inclass]/PalindromeList.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | int val; 5 | 6 | Node(int val) { 7 | this.val = val; 8 | next = null; 9 | } 10 | } 11 | */ 12 | 13 | public static Node insertBeginning(Node head, int val){ 14 | if(head == null){ 15 | return new Node(val); 16 | } 17 | Node newnode = new Node(val); 18 | newnode.next = head; 19 | return newnode; 20 | } 21 | 22 | public static boolean IsPalindrome(Node h1) { 23 | //traverse the linked list, concat in string 24 | //h1 = 1->2->3->4 25 | //h2 = 4->3->2->1 26 | 27 | if(h1.next == null){ 28 | //1 node 29 | return true; 30 | } 31 | Node temp1 = h1; 32 | Node h2 = null; 33 | while(temp1 != null){ 34 | h2 = insertBeginning(h2, temp1.val); 35 | temp1 = temp1.next; 36 | } 37 | 38 | temp1 = h1; 39 | Node temp2 = h2; 40 | while(temp1 != null && temp2 != null){ 41 | if(temp1.val != temp2.val){ 42 | return false; 43 | } 44 | temp1 = temp1.next; 45 | temp2 = temp2.next; 46 | } 47 | return true; 48 | 49 | } -------------------------------------------------------------------------------- /LinkedList-II[PostClass]/DeleteMiddle.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | int val; 5 | 6 | Node(int val) { 7 | this.val = val; 8 | next = null; 9 | } 10 | } 11 | */ 12 | 13 | public static Node deleteMiddleElement(Node head) { 14 | int cnt = 0; 15 | Node temp = head; 16 | while (temp != null) { 17 | cnt++; 18 | temp = temp.next; 19 | } 20 | if (cnt == 1) { 21 | head.val = -1; 22 | return head; 23 | } 24 | if (cnt == 2) { 25 | head.next = null; 26 | return head; 27 | } 28 | temp = head; 29 | int I = 1; 30 | cnt = cnt / 2; 31 | while (I != cnt) { 32 | temp = temp.next; 33 | I++; 34 | } 35 | temp.next = temp.next.next; 36 | return head; 37 | } -------------------------------------------------------------------------------- /LinkedList-II[PostClass]/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | // information about the class Nodeclass Node { 3 | Node next; 4 | int val; 5 | 6 | Node(int val) { 7 | this.val = val; 8 | next = null; 9 | } 10 | } 11 | */ 12 | 13 | 14 | public static Node ReverseLinkedList(Node head) { 15 | 16 | Node prev = null; 17 | Node current = head; 18 | Node next = null; 19 | while (current != null) { 20 | next = current.next; 21 | current.next = prev; 22 | prev = current; 23 | current = next; 24 | } 25 | head = prev; 26 | return head; 27 | 28 | } -------------------------------------------------------------------------------- /LinkedList[InClass]/LinkedListInsertion[InClass].java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | int val; 5 | 6 | Node(int val) { 7 | this.val = val; 8 | next = null; 9 | } 10 | } 11 | 12 | 5 2 6 13 | 14 | k = 6 15 | pos = 4 16 | 1->2->3->4->5 17 | 18 | i = 1; 19 | prev = head; //prev(1, x) 20 | while(i < pos - 1){ 21 | temp = temp.next; 22 | } 23 | 24 | */ 25 | 26 | public static Node addElement(Node head, int k ,int pos ) { 27 | 28 | //1 2 3 4 5 6 29 | //k = 8, pos = 4 30 | 31 | //Output: 1 2 3 8 4 5 6 32 | // LL = (1, add(2)) (2, add(3)) (3, add(8)), (8, add(4)), (4,add(5)), (5,add(6)) (6, null) 33 | //head = address(1) 34 | Node newelement = new Node(k); //(8, null) 35 | if(head == null || pos == 1){ 36 | newelement.next = head; 37 | return newelement; 38 | } 39 | int i = 1; //3 40 | Node prev = head; //prev = address(3) 41 | while(i < pos - 1){ 42 | prev = prev.next; 43 | i++; 44 | } 45 | newelement.next = prev.next; // 46 | prev.next = newelement; 47 | return head; 48 | } -------------------------------------------------------------------------------- /LinkedList[PostClass]/DeleteKthEnd.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | class Node { 4 | Node next; 5 | int val; 6 | 7 | Node(int val) { 8 | this.val = val; 9 | next = null; 10 | } 11 | } 12 | */ 13 | 14 | public static Node deleteElement(Node head, int k) { 15 | 16 | Node start = head; 17 | Node end = head; 18 | while(k-- > 0){ 19 | end = end.next; 20 | } 21 | if(end == null){ 22 | start = start.next; 23 | return start; 24 | } 25 | 26 | while(end.next != null){ 27 | start = start.next; 28 | end = end.next; 29 | } 30 | 31 | //create link between s.next and s.next.next 32 | if(start.next.next == null){ 33 | //deleting element; 34 | start.next = null; 35 | return head; 36 | } 37 | 38 | start.next = start.next.next; 39 | 40 | return head; 41 | 42 | } -------------------------------------------------------------------------------- /LinkedList[PostClass]/IntersectionLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public static Node intersection(Node head1,Node head2){ int aLength = getLength(head1), bLength = getLength(head2); 3 | Node currA = head1, currB = head2; 4 | if (bLength > aLength) 5 | for (int i = 0; i < bLength - aLength; i++) currB = currB.next; 6 | 7 | if (aLength > bLength) 8 | for (int i = 0; i < aLength - bLength; i++) currA = currA.next; 9 | 10 | while (currA != null && currB != null) { 11 | if (currA == currB) return currA; 12 | currA = currA.next; 13 | currB = currB.next; 14 | } 15 | 16 | return null; 17 | } 18 | 19 | private static int getLength(Node head) { 20 | Node curr = head; 21 | int len = 0; 22 | while (curr != null) { 23 | curr = curr.next; 24 | len++; 25 | } 26 | return len; 27 | } 28 | -------------------------------------------------------------------------------- /LinkedList[PostClass]/PrintLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | Node next; 4 | int val; 5 | 6 | Node(int val) { 7 | this.val = val; 8 | next = null; 9 | } 10 | } 11 | */ 12 | public static void printList(Node head) { 13 | Node temp = head; 14 | int count = 0; 15 | while(temp != null){ 16 | System.out.print(temp.val+" "); 17 | temp = temp.next; 18 | count++; 19 | } 20 | System.out.println("\n"+count); 21 | } -------------------------------------------------------------------------------- /MathModular[Arithmetic][Inclass]/ModularExponential.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | static long mod = (long)1e9 + 7; 9 | 10 | public static long power(long n, long p){ 11 | long result = 1; 12 | n = n % mod; 13 | while(p > 0){ 14 | if( p % 2 == 1){ 15 | result = (result * n) % mod; 16 | } 17 | n = (n * n) % mod; 18 | p /= 2; 19 | } 20 | 21 | return result; 22 | } 23 | 24 | public static void main (String[] args) { 25 | 26 | Scanner sc = new Scanner(System.in); 27 | long n = sc.nextLong(); 28 | long p = sc.nextLong(); 29 | 30 | long result = power(n, p); 31 | System.out.println(result); 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /MathModular[Arithmetic][Inclass]/Tribonocci.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | /* 9 | Fibbonocci series was fib(n) = fib(n-1) + fib(n-2) 10 | tribonocci series say is trib(n) = trib(n-1) + trib(n-2) + trib(n-3) 11 | trib(1) = a 12 | trib(2) = b 13 | trib(3) = c 14 | trib(4) = a + b + c 15 | trib(5) = b + c + a + b + c = a + 2b + 2c 16 | .... 17 | 18 | */ 19 | 20 | 21 | static long mod = (long)1e9 + 7; // 1 * 10^9 + 7 = 1000000007 22 | public static void main (String[] args) { 23 | Scanner sc = new Scanner(System.in); 24 | int n = sc.nextInt(); 25 | long a = sc.nextLong(); 26 | long b = sc.nextLong(); 27 | long c = sc.nextLong(); 28 | long trib[] = new long[n+1]; 29 | 30 | trib[1] = a % mod; 31 | trib[2] = b % mod; 32 | trib[3] = c % mod; 33 | 34 | for(int i = 4; i <= n; i++){ 35 | trib[i] = (trib[i-1] + trib[i-2] + trib[i-3]) % mod; 36 | } 37 | 38 | System.out.println(trib[n]); 39 | } 40 | } -------------------------------------------------------------------------------- /MathModular[Arithmetic][Postclass]/NumberGame.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | static long mod = (long) 1e9 + 7; 9 | 10 | 11 | static long[][] mul(long [][] A, long[][] B, int n){ 12 | 13 | /* 14 | A = 15 | [[1 0 0] 16 | [1 1 1] 17 | [0 1 0]] 18 | B = 19 | [[1 0 0] 20 | [1 1 1] 21 | [0 1 0]] 22 | 23 | result = 24 | [[1 0 0] 25 | [2 2 1] 26 | [1 1 1]] 27 | 28 | */ 29 | 30 | 31 | long result[][] = new long[n][n]; 32 | for(int i = 0; i < n; i++){ 33 | for(int j = 0; j < n; j++){ 34 | for(int k = 0; k < n; k++){ 35 | result[i][j] = ((result[i][j] % mod) + ((A[i][k] * B[k][j]) % mod)) % mod; 36 | } 37 | } 38 | } 39 | return result; 40 | } 41 | 42 | static long[][] pow(long matrix[][], int n, long p){ 43 | long result[][] = new long[n][n]; 44 | for(int i = 0; i < n; i++){ 45 | result[i][i] = Long.valueOf(1); 46 | } 47 | /* 48 | result = 49 | [1 0 0] 50 | [0 1 0] 51 | [0 0 1] 52 | 53 | matrix = 54 | [[1 0 0] 55 | [1 1 1] 56 | [0 1 0]] 57 | 58 | 4 59 | */ 60 | 61 | while(p > 0){ 62 | if(p % 2 == 1){ 63 | result = mul(result, matrix, n); //result = matrix ^ 4 64 | } 65 | matrix = mul(matrix, matrix, n); // matrix^4 66 | p /= 2; //p = 1 67 | } 68 | 69 | return result; // matrix ^ 4 70 | } 71 | 72 | public static void main (String[] args) { 73 | Scanner sc = new Scanner(System.in); 74 | long p = sc.nextLong(); 75 | int n = 9; 76 | long matrix[][] = new long[n][n]; 77 | 78 | for(int i = 0; i < n; i++){ 79 | for(int j = 0; j <= i; j++){ 80 | matrix[i][j] = 1; 81 | } 82 | } 83 | 84 | long[][] result = pow(matrix, n, p); 85 | 86 | long ans = 0; 87 | for(int i = 0; i < n; i++){ 88 | ans = (ans + result[i][0]) % mod; 89 | } 90 | System.out.println(ans); 91 | } 92 | } -------------------------------------------------------------------------------- /MathModular[Arithmetic][Postclass]/RaisedPowerP.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | static long mod = (long) 1e9 + 7; 9 | 10 | 11 | static long[][] mul(long [][] A, long[][] B, int n){ 12 | 13 | /* 14 | A = 15 | [[1 0 0] 16 | [1 1 1] 17 | [0 1 0]] 18 | B = 19 | [[1 0 0] 20 | [1 1 1] 21 | [0 1 0]] 22 | 23 | result = 24 | [[1 0 0] 25 | [2 2 1] 26 | [1 1 1]] 27 | 28 | */ 29 | 30 | 31 | long result[][] = new long[n][n]; 32 | for(int i = 0; i < n; i++){ 33 | for(int j = 0; j < n; j++){ 34 | for(int k = 0; k < n; k++){ 35 | result[i][j] = ((result[i][j] % mod) + ((A[i][k] * B[k][j]) % mod)) % mod; 36 | } 37 | } 38 | } 39 | return result; 40 | } 41 | 42 | static long[][] pow(long matrix[][], int n, long p){ 43 | long result[][] = new long[n][n]; 44 | for(int i = 0; i < n; i++){ 45 | result[i][i] = Long.valueOf(1); 46 | } 47 | /* 48 | result = 49 | [1 0 0] 50 | [0 1 0] 51 | [0 0 1] 52 | 53 | matrix = 54 | [[1 0 0] 55 | [1 1 1] 56 | [0 1 0]] 57 | 58 | 4 59 | */ 60 | 61 | while(p > 0){ 62 | if(p % 2 == 1){ 63 | result = mul(result, matrix, n); //result = matrix ^ 4 64 | } 65 | matrix = mul(matrix, matrix, n); // matrix^4 66 | p /= 2; //p = 1 67 | } 68 | 69 | return result; // matrix ^ 4 70 | } 71 | 72 | public static void main (String[] args) { 73 | Scanner sc = new Scanner(System.in); 74 | int n = sc.nextInt(); 75 | long p = sc.nextLong(); 76 | 77 | long matrix[][] = new long[n][n]; 78 | /* 79 | [ 80 | [3 ,4, 5,... n], 81 | [3 ,4, 5,... n], 82 | [3 ,4, 5,... n], 83 | .. 84 | .. 85 | [3 ,4, 5,... n], 86 | ] 87 | 88 | matrix[0] = [3 ,4, 5,... n](first row) 89 | matrix[0][1] = 4(first row)(second column) 90 | O(n^3logp) 91 | 92 | matrix = 93 | [[1 0 0] 94 | [1 1 1] 95 | [0 1 0]] 96 | 97 | 4 98 | */ 99 | 100 | for(int i = 0; i < n; i++){ 101 | for(int j = 0; j < n; j++){ 102 | matrix[i][j] = sc.nextLong(); 103 | matrix[i][j] %= mod; 104 | } 105 | } 106 | 107 | long[][] result = pow(matrix, n, p); 108 | 109 | for(int i = 0; i < n; i++){ 110 | for(int j = 0; j < n; j++){ 111 | System.out.print(result[i][j] + " "); 112 | } 113 | System.out.println(); 114 | } 115 | } 116 | } -------------------------------------------------------------------------------- /Maths[GCD]/GCD.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | public static long gcd(long n, long m){ 9 | if(m == 0){ 10 | return n; 11 | } 12 | return gcd(m, n % m); 13 | } 14 | 15 | public static void main (String[] args) { 16 | Scanner sc = new Scanner(System.in); 17 | long n = sc.nextLong(); 18 | long m = sc.nextLong(); 19 | System.out.println(gcd(n, m)); 20 | } 21 | } -------------------------------------------------------------------------------- /Maths[GCD]/MSpecialGCD.java: -------------------------------------------------------------------------------- 1 | static int gcd(int a, int b){ 2 | if(b == 0){ 3 | return a; 4 | } 5 | return gcd(b, a % b); 6 | } 7 | 8 | static int primeFactor(int n){ 9 | 10 | if(n % 2 == 0){ 11 | return 2; 12 | } 13 | for(int i = 3; i <= Math.sqrt(n); i+=2){ 14 | /* 15 | N = 101 16 | 10 17 | i = 3, i = 5, i = 7, i = 9 18 | */ 19 | if(n%i == 0){ 20 | return i; 21 | } 22 | } 23 | return n; 24 | } 25 | 26 | 27 | static void printM_SpecialGCD(int N, int M) 28 | { 29 | 30 | //N = 10, M = 5 31 | int prime = primeFactor(N); //prime = 2 32 | int count = 0; 33 | int i = prime; // i = 2 34 | while(count < M){ 35 | int res = gcd(N + i, N); //(22, 10) = 2 36 | if(res == prime){ 37 | System.out.print((N+i)+" "); //12 14 16 18 22 38 | count++; // 5 39 | } 40 | i += prime; // 14 41 | } 42 | } 43 | 44 | 45 | 46 | //N = 10, M = 5 47 | 48 | //smallest_prime_factor(N) = 2 49 | 50 | //i = 2 ..... i = sqrt(N) => find a factor which is a prime 51 | //return N, n is a prime number 52 | 53 | 54 | //I have to find 5 numbers which are greater 10 whose gcd (, 10) is 2 55 | // gcd(12, 10) = 2 56 | // gcd(14, 10) = 2 57 | // gcd(16, 10) = 2 58 | // gcd(18, 10) = 2 59 | // gcd(22, 10) = 2 60 | 61 | //12 14 16 18 22 -------------------------------------------------------------------------------- /Maths[GCD][Postclass]/GoodTeamLeader.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | HashMap hm = new HashMap<>(); 11 | for(int i = 0; i < n; i++){ 12 | long value = sc.nextLong(); 13 | long x = (long)Math.sqrt(value); 14 | hm.put(value, hm.getOrDefault(value, 0) + 1); 15 | for(long j=2;j<=x;j++){ 16 | if(value%j==0){ 17 | hm.put(j, hm.getOrDefault(j, 0) + 1); 18 | if(j*j!=value){ 19 | hm.put(value/j, hm.getOrDefault(value/j, 0) + 1); 20 | } 21 | } 22 | } 23 | } 24 | int ans=0; 25 | for(Long l : hm.keySet()){ 26 | ans = Math.max(ans, hm.get(l)); 27 | } 28 | System.out.println(ans); 29 | } 30 | } -------------------------------------------------------------------------------- /Maths[GCD][Postclass]/SpecialNumbers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | long n = sc.nextLong(); 10 | long x = (long)Math.sqrt(n); 11 | HashMap hm = new HashMap<>(); 12 | for(long i=1;i<=x;i++){ 13 | if(n%i==0){ 14 | hm.put(i, hm.getOrDefault(i, 0) + 1); 15 | if(n/i!=i){ 16 | hm.put(n/i, hm.getOrDefault(n/i, 0) + 1); 17 | } 18 | } 19 | } 20 | System.out.println(hm.size()); 21 | } 22 | } -------------------------------------------------------------------------------- /Maths[PrimalityTesting]/CheckIfPrime.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | public static boolean isPrime(long n){ 9 | //If a number is prime I will return true else false 10 | 11 | /* 12 | n <= 1 return false 13 | n = 2, even prime number 14 | 15 | Which number is not a prime number? 16 | which has a divisor which is not 1 or not itself 17 | n = (a * b) 18 | 19 | n = 12 20 | 1, 2, 3, 4, 6, 12 21 | (1, 12), (2, 6), (3, 4) 22 | 23 | 35 24 | 1, 5, 7, 35 25 | sqrt(35) = 5 26 | 35 % 2 == 0 ? No 27 | 35 % 3 == 0 ? No 28 | 35 % 4 == 0 ? No 29 | 35 % 5 == 0 ? Yes 30 | 31 | 37 32 | 1, 37 33 | 37 % 2 == 0 ? No 34 | 37 % 3 == 0 ? No 35 | 37 % 4 == 0 ? No 36 | 37 % 5 == 0 ? No 37 | 37 % 6 == 0 ? No 38 | 39 | */ 40 | // n = 37 41 | if(n <= 1){ 42 | return false; 43 | } 44 | long sqrt_n = (long)Math.sqrt(n); //sqrt_n = 6 45 | for(long i = 2; i <= sqrt_n; i++){ 46 | if(n % i == 0){ 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | 53 | 54 | public static void main (String[] args) { 55 | 56 | Scanner sc = new Scanner(System.in); 57 | int testcases = sc.nextInt(); 58 | while(testcases > 0){ 59 | long n = sc.nextLong(); 60 | if(isPrime(n)){ 61 | System.out.println("Yes"); 62 | } 63 | else{ 64 | System.out.println("No"); 65 | } 66 | testcases--; 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /Maths[PrimalityTesting]/ExactlyThreeDivisors.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | /* 9 | 10 | First we are going to find if a number is prime or not 11 | till the max size 100000 12 | Second we will find how many numbers are prime from 13 | 1 to n[within a range] 14 | */ 15 | int MAX = 100001; 16 | int a[] = new int[MAX]; //All the values in array is 0 17 | boolean b[] = new boolean[MAX]; //All values of boolean is false 18 | 19 | //Array indexing 0..100001 20 | b[0] = true; 21 | b[1] = true; 22 | /* 23 | Prime - false 24 | Not prime - true 25 | [0 = true, 1 = true, 2 = false, 3 = false, 4 = true] 26 | [5 = false, 6 = true, 7= false, 8 = true, 9 = true] 27 | [10 = true, 11 = false, 12= true, 13 = false, 14 = true] 28 | [15 = true, 16 = true, 17= false, 18 = true, 19 = false] 29 | 30 | Every number can be stated as multiple of prime numbers 31 | 32 | */ 33 | for(int i = 2; i < MAX ; i++){ 34 | if(b[i] == false){ 35 | for(int j = 2*i; j < MAX; j += i){ 36 | b[j] = true; 37 | } 38 | } 39 | } 40 | 41 | /* 42 | b = [0 = true, 1 = true, 2 = false, 3 = false, 4 = true] 43 | [5 = false, 6 = true, 7= false, 8 = true, 9 = true] 44 | [10 = true, 11 = false, 12= true, 13 = false, 14 = true] 45 | [15 = true, 16 = true, 17= false, 18 = true, 19 = false] 46 | 47 | a = [0 = 0, 1 = 0, 2 = 1, 3 = 2, 4 = 2] 48 | [5 = 3, 6 = 3, 7 = 4, 8 = 4, 9 = 4] 49 | [10 = 4, 11 = 5, 12 = 5, 13 = 6, 14 = 6] 50 | [15 = 6, 16 = 6, 17 = 7, 18 = 7, 19 = 8] 51 | 52 | */ 53 | int count = 0; 54 | for(int i = 2; i < MAX; i++){ 55 | if(b[i] == false){ 56 | count++; 57 | } 58 | a[i] = count; 59 | } 60 | 61 | Scanner sc = new Scanner(System.in); 62 | int testcases = sc.nextInt(); 63 | while(testcases > 0){ 64 | 65 | int number = sc.nextInt(); // 30 66 | int sqrt_number = (int) Math.sqrt(number); // 5 67 | System.out.println(a[sqrt_number]); // 3 68 | 69 | testcases--; 70 | } 71 | 72 | 73 | } 74 | } -------------------------------------------------------------------------------- /Maths[PrimalityTesting]/NumberOfPrimes.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | public static boolean isPrime(long n){ 9 | if(n <= 1){ 10 | return false; 11 | } 12 | long sqrt_n = (long)Math.sqrt(n); //sqrt_n = 6 13 | for(long i = 2; i <= sqrt_n; i++){ 14 | if(n % i == 0){ 15 | return false; 16 | } 17 | } 18 | return true; 19 | } 20 | 21 | public static void main (String[] args) { 22 | Scanner sc = new Scanner(System.in); 23 | int n = sc.nextInt(); 24 | int count = 0; 25 | for(int i = 1; i <= n; i++){ 26 | if(isPrime(i)){ 27 | count++; 28 | } 29 | } 30 | System.out.println(count); 31 | } 32 | } -------------------------------------------------------------------------------- /MergeSortAndJavaFunds[Inclass]/DragonSlayer.java: -------------------------------------------------------------------------------- 1 | static int DragonSlayer(int A, int B, int C,int D){ 2 | int x = C/B; 3 | if(C%B!=0){x++;} 4 | int y = A/D; 5 | if(A%D!=0){y++;} 6 | if(x= end){ 50 | //stop splitting 51 | return; 52 | } 53 | int mid = (start) + (end - start) / 2; 54 | mergeSort(arr, start , mid); //left call 55 | mergeSort(arr, mid+1 , end); //right call 56 | merge(arr, start, mid, end); //merge [start...mid] [mid+1...end] 57 | } 58 | 59 | public static void main (String[] args) throws IOException { 60 | Scanner sc = new Scanner(System.in); 61 | int n = sc.nextInt(); 62 | long array[] = new long[n]; 63 | for(int i = 0; i < n; i++){ 64 | array[i] = sc.nextLong(); 65 | } 66 | mergeSort(array, 0, n - 1); 67 | System.out.println(count); 68 | 69 | } 70 | } -------------------------------------------------------------------------------- /MergeSortAndJavaFunds[Inclass]/QueensAttack.java: -------------------------------------------------------------------------------- 1 | static int QueenAttack(int X, int Y, int P, int Q){ 2 | if(X==P || Y==Q || Math.abs(X-P)==Math.abs(Y-Q) ){ 3 | return 1; 4 | } 5 | return 0; 6 | } -------------------------------------------------------------------------------- /MergeSort[Inclass]/ImplementingMergeSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Merge sort: Time complexity O(nlogn) nlogn < n^2 3 | 4 | Imagine you have 1000 sheets of paper,and in each sheet 5 | a number is written. 6 | We want to sort all the sheets(ascending order). 7 | 1000 8 | 500 500 9 | 250 250 250 250 10 | 125 125 125 125 125 125 125 125 11 | 62 63 62 6362 6362 6362 6362 6362 6362 6362 63 12 | . 13 | . 14 | . 15 | . 16 | . 17 | 1 11111111.......................................1 (1000 people) 18 | 19 | Till now we divided. 20 | Now we will merge 21 | [25, 37] ...................................[67 89] (500 groups) 22 | 23 | (250 groups each of size 4 and they will also be sorted) 24 | 25 | .... 26 | 27 | 28 | ... 29 | 30 | .... 31 | 32 | ... (1 group of 1000 sheets) 33 | 34 | 35 | For example: [i=12, 15, 37, 83], [j = 10, 13, 19, 40] 36 | 37 | [index = 10,index = 12,13,15,19,37,40,83] 38 | 39 | Merging time is O(n) 40 | At every level my merging is going to take O(n) time 41 | 42 | So my final time complexity is: Number of levels * O(n) 43 | 44 | 45 | Last level has 1000 sheets 46 | Second last level(500) sheets 47 | Last => Second last => (1000 / 2)(2) => 1000 => n 48 | 49 | Second => third last = (250)(4) => 1000 => n 50 | 51 | Third => fourthlast => 125(8) => 1000 => n 52 | 53 | So my final time complexity is: number of levels * O(n) 54 | 55 | 56 | 1000 => 1000/2 => 1000/4 => 1000/8.......... (1000/2^x) 57 | After x steps my one single array size is going to be 1000 / 2^x 58 | 1000/2^x = 1, here x is the number of steps to reach to 1 59 | 1000 = 2^x 60 | x = log_{2}(n) 61 | Numbe of steps = x = log_{2}(n) 62 | 63 | O(n * log_{2}(n)) 64 | 65 | */ 66 | 67 | 68 | 69 | /* 70 | 71 | mergeSort - 1 72 | [242, 438, 613, 788, 725, 963, 933, 237] 73 | start = 0 74 | end = 7 75 | mid = 3 76 | [242, 438, 613, 788] [725, 963, 933, 237] 77 | 78 | mergeSort - 2 79 | [242, 438, 613, 788, 725, 963, 933, 237] 80 | start = 0 , end = 3 81 | mid = 1 82 | [241, 438] [613, 788] 83 | 84 | 85 | mergeSort-3 86 | [242, 438, 613, 788, 725, 963, 933, 237] 87 | start = 0 88 | end = 1 89 | mid = 0 90 | [242] [438] => [242, 438] 91 | merge(arr, 0, 0, 1) 92 | 93 | mergeSort-4 94 | start = 0 95 | end = 0 96 | 97 | mergeSort - 5 98 | start = 1 99 | end = 1 100 | 101 | 102 | */ 103 | 104 | 105 | // arr = [12, 15, 37, 83, 10, 13, 19, 40], start = 0, mid = 3, end = 7 106 | // 107 | static int temp[] = new int[10001]; //global array 108 | 109 | public static void merge(int[] arr, int start, int mid, int end){ 110 | for(int i = 0; i < arr.length; i++){ 111 | temp[i] = arr[i]; 112 | } 113 | //temp = [12, 15, 37, 83, 10 13, 19, 40], j 114 | // arr = [10, 12, 13, 15, 19, 37, 40, 83], index 115 | int i = start; 116 | int j = mid + 1; 117 | int index = start; 118 | while(i <= mid && j <= end){ 119 | if(temp[i] <= temp[j]){ 120 | arr[index] = temp[i]; 121 | i++; 122 | } 123 | else{ 124 | arr[index] = temp[j]; 125 | j++; 126 | } 127 | index++; 128 | } 129 | while(i <= mid){ 130 | arr[index] = temp[i]; 131 | index++; 132 | i++; 133 | } 134 | while(j <= end){ 135 | arr[index] = temp[j]; 136 | index++; 137 | j++; 138 | } 139 | } 140 | 141 | public static void mergeSort(int arr[], int start, int end){ 142 | //if array is size 1, start == end ? 143 | if(start >= end){ 144 | //stop splitting 145 | return; 146 | } 147 | int mid = (start) + (end - start) / 2; 148 | mergeSort(arr, start , mid); //left call 149 | mergeSort(arr, mid+1 , end); //right call 150 | merge(arr, start, mid, end); //merge [start...mid] [mid+1...end] 151 | } 152 | 153 | 154 | 155 | public static int[] implementMergeSort(int arr[], int start, int end) //start = 0, end = n-1 156 | { 157 | mergeSort(arr, start, end); 158 | return arr; 159 | } -------------------------------------------------------------------------------- /Queue[InClass]/GenerateBinaryNumbers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | Queue qu = new LinkedList<>(); 11 | qu.add(1l); 12 | while(n-- > 0){ 13 | Long x = qu.poll(); 14 | System.out.print(x+ " "); 15 | qu.add(10*x); 16 | qu.add(10*x + 1); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Queue[InClass]/OperationsInQueue.java: -------------------------------------------------------------------------------- 1 | // enqueue():- that takes the queue 2 | // and the integer to be added as a parameter. 3 | public static void enqueue(Queue qu, int x) 4 | { 5 | qu.add(x); 6 | } 7 | 8 | // dequeue():- that takes the queue as parameter. 9 | public static void dequeue(Queue qu) 10 | { 11 | if(qu.size() != 0){ 12 | qu.poll(); 13 | } 14 | } 15 | 16 | // displayfront():- that takes the queue as parameter. 17 | public static void displayfront(Queue qu) 18 | { 19 | if(qu.size() != 0){ 20 | System.out.println(qu.peek()); 21 | } 22 | else{ 23 | System.out.println("0"); 24 | } 25 | } -------------------------------------------------------------------------------- /Queue[InClass]/QueueArrayImplementation.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | class Queue{ 4 | static final int MAX = 10000; 5 | int rear=0,front=0; 6 | int a[] = new int[MAX]; 7 | } 8 | int rear=0,front=0; //pointer to rear and front 9 | int a[] //array that contain elements of queue 10 | */ 11 | public static void enqueue(int x, int size) 12 | { 13 | if(rear >= size){ 14 | System.out.println("Queue is full"); 15 | return; 16 | } 17 | a[rear] = x; 18 | rear++; 19 | } 20 | //front = 3, rear = 3 //3 elements in the queue 21 | public static void dequeue() 22 | { 23 | if(front >= rear){ 24 | System.out.println("Queue is empty"); 25 | return; 26 | } 27 | front++; 28 | } 29 | public static void displayfront() 30 | { 31 | if(front >= rear){ 32 | System.out.println("Queue is empty"); 33 | return; 34 | } 35 | System.out.println(a[front]); 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /Queue[PostClass]/MaximumKSubarray.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | int k = sc.nextInt(); 12 | int a[] = new int[n]; 13 | for(int i = 0; i < n; i++){ 14 | a[i] = sc.nextInt(); 15 | } 16 | 17 | //1 2 3 1 4 5 2 3 1 18 | //0 1 2 3 4 5 6 7 8 19 | 20 | Deque dq = new LinkedList<>(); 21 | //First k elements just add 22 | 23 | //dq: [2] 24 | int i; 25 | for(i = 0; i < k; i++){ 26 | //removing useless 27 | while(!dq.isEmpty() && a[dq.peekLast()] <= a[i]){ 28 | dq.removeLast(); 29 | } 30 | dq.addLast(i); //index; 31 | } 32 | //1 2 3 1 4 5 2 3 1 33 | //0 1 2 3 4 5 6 7 8 34 | //dq: [2] 35 | //Output: 3 36 | 37 | //5 3 2 1 38 | //6 7 8 9 39 | 40 | //dq: 7 8 9 41 | //6 <= 9 - 3 42 | for(; i ReverseK(Queue queue, int k) { 2 | 3 | 4 | 5 | Stack stack = new Stack(); 6 | 7 | // Push the first K elements into a Stack 8 | for (int i = 0; i < k; i++) { 9 | stack.push(queue.peek()); 10 | queue.remove(); 11 | } 12 | 13 | 14 | // Enqueue the contents of stack at the back 15 | // of the queue 16 | while (!stack.empty()) { 17 | queue.add(stack.peek()); 18 | stack.pop(); 19 | } 20 | 21 | 22 | // Remove the remaining elements and enqueue 23 | // them at the end of the Queue 24 | for (int i = 0; i < queue.size() - k; i++) { 25 | queue.add(queue.peek()); 26 | queue.remove(); 27 | } 28 | return queue; 29 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NewtonSchoolFalconBatch 2 | All Codes for newton school falcon batch. 3 | -------------------------------------------------------------------------------- /RecursionContd[InClass]/Fibonacci.java: -------------------------------------------------------------------------------- 1 | static long Fibonacci(long n) 2 | { 3 | if (n == 0) 4 | { 5 | return 0; 6 | } 7 | else if(n==1){ 8 | return 1; 9 | } 10 | return Fibonacci(n-1) + Fibonacci(n-2); 11 | } -------------------------------------------------------------------------------- /RecursionContd[InClass]/Welcome.java: -------------------------------------------------------------------------------- 1 | public static int safe_Position(int n, int k) 2 | { 3 | return solve_problem(n, k) + 1; //(5 2) 4 | } 5 | 6 | public static int solve_problem(int n, int k){ 7 | if(n == 1){ 8 | /*if only one person is there 0 is the safe position*/ 9 | return 0; 10 | } 11 | return (solve_problem(n-1,k) + k) % n; 12 | } -------------------------------------------------------------------------------- /RecursionContd[PostClass]/ComputePower.java: -------------------------------------------------------------------------------- 1 | static int Power(int n,int p) 2 | { 3 | if(p==0) 4 | return 1; 5 | return n*Power(n,p-1); 6 | 7 | } -------------------------------------------------------------------------------- /RecursionContd[PostClass]/MultiplyByRecursion.java: -------------------------------------------------------------------------------- 1 | static int Multiply_by_recursion(int n, int m) 2 | { 3 | if(n==0 || m==0){return 0;} 4 | if (m == 1){ 5 | return n; 6 | } 7 | return n + Multiply_by_recursion(n,m-1); 8 | } -------------------------------------------------------------------------------- /RecursionContd[PostClass]/Printdigits.java: -------------------------------------------------------------------------------- 1 | static void Print_Digits(int N){ 2 | if(N==0){return;} 3 | Print_Digits(N/10); 4 | int x=N%10; 5 | if(x==1){System.out.print("one ");} 6 | else if(x==2){System.out.print("two ");} 7 | else if(x==3){System.out.print("three ");} 8 | else if(x==4){System.out.print("four ");} 9 | else if(x==5){System.out.print("five ");} 10 | else if(x==6){System.out.print("six ");} 11 | else if(x==7){System.out.print("seven ");} 12 | else if(x==8){System.out.print("eight ");} 13 | else if(x==9){System.out.print("nine ");} 14 | else if(x==0){System.out.print("zero ");} 15 | 16 | } -------------------------------------------------------------------------------- /Recursion[Inclass]/Factorial.java: -------------------------------------------------------------------------------- 1 | static int Factorial(int N) 2 | { 3 | if(N==0){ 4 | return 1; 5 | } 6 | 7 | return N*Factorial(N-1); 8 | } -------------------------------------------------------------------------------- /Recursion[Inclass]/PowerFunction.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.lang.*; 4 | 5 | class Main 6 | { 7 | public static void main (String[] args)throws Exception { 8 | 9 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 10 | int t = Integer.parseInt(read.readLine()); 11 | 12 | while(t-- > 0) 13 | { 14 | String str[] = read.readLine().trim().split(" "); 15 | double X = Double.parseDouble(str[0]); 16 | int N = Integer.parseInt(str[1]); 17 | 18 | System.out.println(String.format("%.2f", myPow(X, N))); 19 | } 20 | } 21 | 22 | public static double myPow(double x, int n) { 23 | // if (n == Integer.MIN_VALUE) 24 | // n = - (Integer.MAX_VALUE - 1); 25 | if (n == 0) 26 | return 1.0; 27 | else if (n < 0) 28 | return 1 / myPow(x, -n); 29 | else if (n % 2 == 1) 30 | return x * myPow(x, n - 1); 31 | else { 32 | double sqrt = myPow(x, n / 2); 33 | return sqrt * sqrt; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Recursion[Inclass]/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | public static void toh(int n, String source, String temp, String destination){ 9 | if(n == 0){ 10 | return; 11 | } 12 | toh(n - 1, source, destination ,temp); 13 | System.out.println(n+":"+source+"->"+destination); 14 | toh(n - 1, temp, source , destination); 15 | } 16 | 17 | public static void main (String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n = sc.nextInt(); 20 | toh(n, "A", "B", "C"); 21 | } 22 | } -------------------------------------------------------------------------------- /Recursion[Postclass]/CandyCrush.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | 9 | public static long cost(long n){ 10 | if (n == 0){ 11 | return 0; 12 | } 13 | long g = (n-1)/3+1; 14 | return g*g + cost(n-g); 15 | } 16 | 17 | public static void main (String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int q = sc.nextInt(); 20 | while(q-- > 0){ 21 | long n = sc.nextLong(); 22 | System.out.println(cost(n)); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Recursion[Postclass]/SumOfDigits.java: -------------------------------------------------------------------------------- 1 | public static int sumOfProductOfDigits(int n1, int n2) 2 | { 3 | if(n1 == 0 || n2 == 0){ 4 | return 0; 5 | } 6 | return (n1 % 10) * (n2 % 10) + sumOfProductOfDigits(n1 / 10, n2 / 10); 7 | } -------------------------------------------------------------------------------- /SimpleSorting[InClass]/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | //java//util//Lots of java files 5 | 6 | // don't change the name of this class 7 | // you can add inner classes if needed 8 | class Main { 9 | /* 10 | If n is the size of the array we need n - 1 iterations 11 | 12 | 13 | [1st Iteration] => 4 1 3 9 7 14 | => 1 4 3 9 7 (1 swap) 15 | => 1 3 4 9 7 (1 swap) 16 | => 1 3 4 9 7 (0 swap) 17 | => 1 3 4 7 9 (1 swap) 18 | [2nd Iteration] => 1 3 4 7 9(1,3) 19 | => 1 3 4 7 9(3,4) 20 | => 1 3 4 7 9(4,7) 21 | 22 | 23 | Every Iteration I will make one less comparison. 24 | Becaus second iteration there is not swap I do not have to make a third 25 | Iterations 26 | [1st Iteration] => 4 3 2 1 27 | => 3 4 2 1(1 swap) 28 | => 3 2 4 1(1 swap) 29 | => 3 2 1 4(1 swap) 30 | 31 | [2nd Iteration] => 3 2 1 4 32 | => 2 3 1 4(1 swap) 33 | => 2 1 3 4(1 swap) 34 | 35 | [3rd Iteration] => 2 1 3 4 36 | => 1 2 3 4(1 swap) 37 | 38 | In selection sort in worst case also you will have n swaps 39 | 40 | Use Bubble sort for time 41 | Use Selection sort for less number of write operations 42 | 43 | */ 44 | 45 | public static void bubbleSort(int a[], int n){ 46 | int swap = 0; 47 | 48 | for(int i = 0; i < n-1; i++){ 49 | /* 50 | After 1st iteration n-1th element is in right place 51 | after every iteration n-1-i is in the right place 52 | */ 53 | swap = 0; 54 | //2 1 3 4 55 | for(int j = 0; j < n-1-i ; j++){ //j < n-2 56 | if(a[j] > a[j+1]){ 57 | int temp = a[j]; 58 | a[j] = a[j+1]; 59 | a[j+1] = temp; 60 | swap++; 61 | } 62 | } 63 | if(swap == 0){ 64 | break; 65 | } 66 | } 67 | } 68 | 69 | public static void main (String[] args) { 70 | Scanner sc = new Scanner(System.in); 71 | int testcases = sc.nextInt(); 72 | while(testcases-- > 0){ 73 | /* Input Section */ 74 | int n = sc.nextInt(); 75 | int a[] = new int[n]; 76 | for(int i = 0; i < n; i++){ 77 | a[i] = sc.nextInt(); 78 | } 79 | bubbleSort(a, n); 80 | /* Output Section */ 81 | for(int i = 0; i < n; i++){ 82 | System.out.print(a[i]+ " "); 83 | } 84 | System.out.println(); //New line for every test case 85 | } 86 | 87 | } 88 | } -------------------------------------------------------------------------------- /SimpleSorting[InClass]/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | 7 | /* 8 | Sorting - To put it simply, Arranging the collection of elements in ascending/descending order 9 | - Or in any particular order, but mostly we are interested in ascending/descending order. 10 | 11 | There are different ways to sort an array? 12 | One of them selection sort(simple) sorting algorithm. 13 | 14 | 4 1 2 5 7 6 15 | 1 2 4 5 6 7 16 | 1 2 4 5 6 7 17 | Select the largest and place it in the last position 18 | Select the second-largest and place it in the second last position 19 | .... 20 | This will sort the whole array 21 | 22 | This is the whole idea of selection sort 23 | */ 24 | 25 | 26 | class Main { 27 | 28 | /* 29 | int a = 5, b = 10 30 | After swap/interchange => b = 5, a = 10 31 | 32 | int temp = b; //temp = 10 33 | b = a; //b = 5 34 | a = temp; // a = 10 35 | */ 36 | 37 | 38 | 39 | public static void selectionSort(int a[], int n){ 40 | /* 41 | 1 2 4 5 6 7 42 | i = 5// Find the element for 5th position 43 | max_index = 4 44 | 45 | i = 4// Find the element for 4th position 46 | max_index = 4 47 | 48 | i = 3 49 | max_index = 3 50 | 51 | i = 2 52 | max_index = 0 53 | 54 | i = 1 55 | max_index = 0 56 | 57 | i = 0 58 | */ 59 | 60 | for(int i = n - 1; i > 0; i--){ 61 | int max_index = i; 62 | for(int j = 0; j < i; j++){ 63 | if(a[j] > a[max_index]){ 64 | max_index = j; 65 | } 66 | } 67 | //After finding max_index, swap it with the correct position 68 | if(max_index != i){ 69 | int temp = a[i]; 70 | a[i] = a[max_index]; 71 | a[max_index] = temp; 72 | } 73 | } 74 | } 75 | 76 | 77 | public static void main (String[] args) { 78 | Scanner sc = new Scanner(System.in); 79 | int testcases = sc.nextInt(); 80 | while(testcases-- > 0){ 81 | /* Input Section */ 82 | int n = sc.nextInt(); 83 | int a[] = new int[n]; 84 | for(int i = 0; i < n; i++){ 85 | a[i] = sc.nextInt(); 86 | } 87 | selectionSort(a, n); 88 | /* Output Section */ 89 | for(int i = 0; i < n; i++){ 90 | System.out.print(a[i]+ " "); 91 | } 92 | System.out.println(); //New line for every test case 93 | } 94 | 95 | } 96 | } -------------------------------------------------------------------------------- /SimpleSorting[PostClass]/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | //java//util//Lots of java files 5 | 6 | // don't change the name of this class 7 | // you can add inner classes if needed 8 | class Main { 9 | /* 10 | If n is the size of the array we need n - 1 iterations 11 | 12 | 13 | [1st Iteration] => 4 1 3 9 7 14 | => 1 4 3 9 7 (1 swap) 15 | => 1 3 4 9 7 (1 swap) 16 | => 1 3 4 9 7 (0 swap) 17 | => 1 3 4 7 9 (1 swap) 18 | [2nd Iteration] => 1 3 4 7 9(1,3) 19 | => 1 3 4 7 9(3,4) 20 | => 1 3 4 7 9(4,7) 21 | 22 | 23 | Every Iteration I will make one less comparison. 24 | Becaus second iteration there is not swap I do not have to make a third 25 | Iterations 26 | [1st Iteration] => 4 3 2 1 27 | => 3 4 2 1(1 swap) 28 | => 3 2 4 1(1 swap) 29 | => 3 2 1 4(1 swap) 30 | 31 | [2nd Iteration] => 3 2 1 4 32 | => 2 3 1 4(1 swap) 33 | => 2 1 3 4(1 swap) 34 | 35 | [3rd Iteration] => 2 1 3 4 36 | => 1 2 3 4(1 swap) 37 | 38 | In selection sort in worst case also you will have n swaps 39 | 40 | Use Bubble sort for time 41 | Use Selection sort for less number of write operations 42 | 43 | */ 44 | 45 | public static void bubbleSort(int a[], int n){ 46 | int swap = 0; 47 | 48 | for(int i = 0; i < n-1; i++){ 49 | /* 50 | After 1st iteration n-1th element is in right place 51 | after every iteration n-1-i is in the right place 52 | */ 53 | swap = 0; 54 | //2 1 3 4 55 | for(int j = 0; j < n-1-i ; j++){ //j < n-2 56 | if(a[j] < a[j+1]){ 57 | int temp = a[j]; 58 | a[j] = a[j+1]; 59 | a[j+1] = temp; 60 | swap++; 61 | } 62 | } 63 | if(swap == 0){ 64 | break; 65 | } 66 | } 67 | } 68 | 69 | public static void main (String[] args) { 70 | Scanner sc = new Scanner(System.in); 71 | int testcases = 1; 72 | while(testcases-- > 0){ 73 | /* Input Section */ 74 | int n = sc.nextInt(); 75 | int a[] = new int[n]; 76 | for(int i = 0; i < n; i++){ 77 | a[i] = sc.nextInt(); 78 | } 79 | bubbleSort(a, n); 80 | /* Output Section */ 81 | for(int i = 0; i < n; i++){ 82 | System.out.print(a[i]+ " "); 83 | } 84 | System.out.println(); //New line for every test case 85 | } 86 | 87 | } 88 | } -------------------------------------------------------------------------------- /Stack[InClass]/HeightProblem.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | //12 5 9 2 4 7 3 11 | Stack st = new Stack<>(); 12 | //st = [2, 3] 13 | for(int i = 0; i < n; i++){ 14 | long x = sc.nextLong(); // 7 15 | while(!st.empty() && st.peek() >= x){ 16 | st.pop(); 17 | } 18 | if(st.empty()){ 19 | System.out.print("-1 "); 20 | } 21 | else{ 22 | System.out.print(st.peek()+" "); 23 | } 24 | st.push(x); 25 | } //-1 -1 5 -1 2 4 2 26 | } 27 | } -------------------------------------------------------------------------------- /Stack[InClass]/StackArrayImplementation.java: -------------------------------------------------------------------------------- 1 | /* 2 | int top=-1; // index of current top 3 | int a[] // array which contain element of stack 4 | */ 5 | // function to add element in the stack 6 | //x=element to be added 7 | //size=maximum size of array 8 | 9 | //a = [3,2,5], top = 2, size = 3 10 | //3 2 4 pop 5 11 | 12 | void push(int x, int size) 13 | { 14 | if(top == size - 1){ 15 | System.out.println("Stack overflow"); 16 | return; 17 | } 18 | top++; 19 | a[top] = x; 20 | } 21 | 22 | // Function to pop element from stack 23 | void pop() 24 | { 25 | if (top == -1){ 26 | System.out.println("Stack underflow"); 27 | 28 | } 29 | else{ 30 | top--; 31 | } 32 | } 33 | 34 | void top() 35 | { 36 | if(top == -1) { 37 | System.out.println("Empty stack"); 38 | } 39 | else{ 40 | System.out.println(a[top]); 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /Stack[InClass]/StackOperationClass.java: -------------------------------------------------------------------------------- 1 | public static void push(Stack st, int x) 2 | { 3 | st.push(x); 4 | } 5 | 6 | // Function to pop element from stack 7 | public static void pop(Stack st) 8 | { 9 | if(!st.empty()) 10 | st.pop(); 11 | } 12 | 13 | public static void top(Stack st) 14 | { 15 | if(!st.empty()){ 16 | System.out.println(st.peek()); 17 | } 18 | else{ 19 | System.out.println(0); 20 | } 21 | } -------------------------------------------------------------------------------- /Stack[PostClass]/GreaterIsBetter.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | 7 | class Pair{ 8 | long first; 9 | long second; 10 | Pair(long first, long second){ 11 | this.first = first; 12 | this.second = second; 13 | } 14 | } 15 | 16 | class Main { 17 | public static void main (String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n = sc.nextInt(); 20 | Stack s = new Stack<>(); 21 | Stack s1 = new Stack<>(); 22 | 23 | long a[] = new long[n]; 24 | long b[] = new long[n]; 25 | 26 | for(int i = 0; i < n; i++){ 27 | a[i] = sc.nextLong(); 28 | while(!(s.empty())){ 29 | if(s.peek().first>a[i]){ 30 | break; 31 | } 32 | s.pop(); 33 | } 34 | if(s.empty()){ 35 | b[i]=-1l; 36 | } 37 | else{ 38 | b[i]=s.peek().second+1; 39 | } 40 | Pair p = new Pair(a[i], i); 41 | s.push(p); 42 | } 43 | 44 | for(int i=n-1;i>=0;i--){ 45 | while(!(s1.empty())){ 46 | if(s1.peek().first>a[i]){ 47 | break; 48 | } 49 | s1.pop(); 50 | } 51 | if(s1.empty()){ 52 | b[i]+=-1; 53 | } 54 | else{ 55 | b[i]+=s1.peek().second+1; 56 | } 57 | Pair p = new Pair(a[i], i); 58 | s1.push(p); 59 | } 60 | 61 | for(int i=0;i s = new Stack<>(); 22 | for(int i = 0; i < arrSize; i++) 23 | { 24 | while(!s.empty() == true && arr[s.peek()] > arr[i]) 25 | s.pop(); 26 | if(s.empty() == true) 27 | System.out.print(-1 +" "); 28 | else 29 | System.out.print(arr[s.peek()]+" "); 30 | s.push(i); 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /Stack[PostClass]/StockSpanProblem.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Stack st = new Stack<>(); 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | int a[] = new int[n+1]; 12 | a[0] = Integer.MAX_VALUE; 13 | st.push(0); 14 | for(int i = 1; i <= n; i++){ 15 | a[i] = sc.nextInt(); 16 | while(!st.empty() && a[st.peek()] <= a[i]) 17 | st.pop(); 18 | System.out.print(i - st.peek()+" "); 19 | st.push(i); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /StringsManipulation/Anagram.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | String str1 = sc.nextLine(); 10 | String str2 = sc.nextLine(); 11 | if(str1.length() != str2.length()){ 12 | System.out.println("NO"); 13 | return; 14 | } 15 | int count[] = new int[26]; 16 | //bacb [1,2,1..........0] 17 | 18 | for(int i = 0; i < str1.length(); i++){ 19 | //ASCII codes 20 | //'a' => 97, b='98' 21 | //'z' => 122 22 | count[str1.charAt(i) - 'a']++; 23 | } 24 | for(int i = 0; i < str2.length(); i++){ 25 | count[str2.charAt(i) - 'a']--; 26 | } 27 | for(int i = 0; i < 26; i++){ 28 | if(count[i] != 0){ 29 | System.out.println("NO"); 30 | return; 31 | } 32 | } 33 | System.out.println("YES"); 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /StringsManipulation/MaxHammingDistance.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | String str = sc.nextLine(); 10 | int n = str.length(); 11 | char[] strCharArray = str.toCharArray(); 12 | 13 | int[] count = new int[26]; 14 | int maxValue = 0; 15 | for(int i = 0; i < n; i++){ 16 | count[str.charAt(i) - 'a']++; 17 | if(maxValue < count[str.charAt(i) - 'a']){ 18 | maxValue = count[str.charAt(i) - 'a']; 19 | } 20 | } 21 | //maxValue is max number of times a character will come 22 | //aaaaabbbb, maxValue = 5 23 | //bbbba 24 | //i = 0, maxValue = 5 25 | Arrays.sort(strCharArray); 26 | char[] rCharArray = new char[n]; 27 | for(int i = 0; i < n; i++){ 28 | rCharArray[i] = strCharArray[(i + maxValue) % n]; 29 | } 30 | int ans = 0; 31 | for(int i = 0; i < n; i++){ 32 | if(strCharArray[i] != rCharArray[i]){ 33 | ans++; 34 | } 35 | } 36 | System.out.println(ans); 37 | } 38 | } -------------------------------------------------------------------------------- /StringsManipulation/Reverse.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main 6 | { 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner sc = new Scanner(System.in); 10 | String s = sc.next(); 11 | for(int i = s.length()-1;i>=0;i--){ 12 | System.out.print(s.charAt(i)); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Strings[InClass]/BeautifulString.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | //10203: No 9 | 10 | /* 11 | 100101 12 | 1 digit number consecutive sequence: 1, 0, 0, 1, 0, 1: No 13 | 2 digit number consecutive sequence: 10, 01, 01: No 14 | 3 digit number consecutive sequence: 100, 101: Yes 100 15 | 16 | 1000101: 7 17 | 1 digit number consecutive sequence: 1, 0, 0, 0, 1, 0, 1: No 18 | 2 digit number consecutive sequence: 10, 00, 10, 1: No 19 | 3 digit number consecutive sequence: 100, 010, 1: No 20 | 4 digit number consecutive sequence: 1000, 101: We dont have to check 21 | */ 22 | public static void main (String[] args) { 23 | Scanner sc = new Scanner(System.in); 24 | String str = sc.nextLine(); 25 | 26 | int length = str.length(); 27 | long ans = -1; 28 | 29 | for(int digit = 1; digit*2 <= length; digit++){ 30 | long x = 0; 31 | //str = 135136, digit = 3 32 | for(int i = 0; i < digit; i++){ 33 | x = (10 * x) + (str.charAt(i) - '0'); //x = 1, 13, 135 34 | //'1' - '0' => 49 - 48 = 1 35 | //'3' - '0' => 51 - 48 = 3 36 | //'5' - '0' => 53 - 48 = 5 37 | } 38 | String consecutiveSequnce = ""; 39 | long y = x; 40 | while(consecutiveSequnce.length() < str.length()){ 41 | consecutiveSequnce += String.valueOf(x); //consecutiveSequnce = "135136" 42 | x++; //136 43 | } 44 | if(consecutiveSequnce.equals(str)){ 45 | ans = y; 46 | break; 47 | } 48 | } 49 | if(ans == -1){ 50 | System.out.println("NO"); 51 | } 52 | else{ 53 | System.out.println("YES "+ans); 54 | } 55 | 56 | } 57 | } -------------------------------------------------------------------------------- /Strings[InClass]/IsPalindrome.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | String str = sc.nextLine(); 10 | //ABCDCZA 11 | int i = 0; //i = 0 12 | int j = str.length()-1; //j = 6 13 | 14 | while(i < j){ 15 | if(str.charAt(i) != str.charAt(j)){ 16 | System.out.println(0); 17 | return; 18 | } 19 | i++; 20 | j--; 21 | } 22 | System.out.println(1); 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Strings[InClass]/Permutation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | 8 | //ABCDE 9 | //['A', 'B', 'C', 'D', 'E'] 10 | //['A', 'D', 'C', 'B', 'E'] 11 | //ADCBE 12 | public static String swap(String str, int i, int j){ 13 | char strArray[] = str.toCharArray(); 14 | char temp = strArray[i]; 15 | strArray[i] = strArray[j]; 16 | strArray[j] = temp; 17 | return String.valueOf(strArray); 18 | } 19 | 20 | 21 | public static void permute(String str, int left, int right, ArrayList ans){ 22 | if(left == right){ 23 | ans.add(str); 24 | } 25 | else{ 26 | for(int i = left; i <= right; i++){ 27 | String swapped_str = swap(str, left, i); 28 | permute(swapped_str, left+1, right, ans); 29 | } 30 | } 31 | } 32 | 33 | public static void main (String[] args) { 34 | Scanner sc = new Scanner(System.in); 35 | String str = sc.nextLine(); 36 | int n = str.length(); 37 | ArrayList ans = new ArrayList<>(); 38 | permute(str, 0, n - 1, ans); 39 | Collections.sort(ans); 40 | for(int i = 0; i < ans.size(); i++){ 41 | System.out.print(ans.get(i) +" "); 42 | } 43 | 44 | } 45 | } -------------------------------------------------------------------------------- /Strings[InClass]/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | /* 10 | 2 11 | hello 12 | helloworld 13 | */ 14 | 15 | int t = sc.nextInt(); //2 16 | sc.nextLine(); //'\n' 17 | HashMap hm = new HashMap<>(); 18 | /* 19 | hm = [{}] 20 | 21 | */ 22 | while(t-- > 0){ 23 | String str = sc.nextLine(); //helloworld 24 | hm.clear(); 25 | for(int i = 0; i < str.length(); i++){ 26 | if(!hm.containsKey(str.charAt(i))){ 27 | System.out.print(str.charAt(i)); //helo 28 | hm.put(str.charAt(i), 1); 29 | } 30 | } 31 | System.out.println(); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Strings[InClass]/StringLength.java: -------------------------------------------------------------------------------- 1 | static int StringLength(String S){ 2 | return S.length(); 3 | } -------------------------------------------------------------------------------- /Strings[InClass]/Substring.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | String A = sc.nextLine(); 10 | String B = sc.nextLine(); 11 | if(B.indexOf(A) == -1){ 12 | System.out.println("No"); 13 | } 14 | else{ 15 | System.out.println("Yes"); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Trees[Inclass]/HeighOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node 3 | { 4 | int data; 5 | Node left, right; 6 | Node(int data) 7 | { 8 | this.data = data; 9 | this.left = this.right = null; 10 | } 11 | } 12 | */ 13 | 14 | /* 15 | 1 16 | 10 12 17 | 14 18 18 | */ 19 | 20 | //1 h_left = 2 21 | 22 | static int getHeight(Node node) 23 | { 24 | if(node == null){ 25 | return 0; 26 | } 27 | int h_left = getHeight(node.left); 28 | int h_right = getHeight(node.right); 29 | return Math.max(h_left, h_right) + 1; 30 | } -------------------------------------------------------------------------------- /Trees[Inclass]/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node 3 | { 4 | int data; 5 | Node left, right; 6 | 7 | Node(int item) 8 | { 9 | data = item; 10 | left = right = null; 11 | } 12 | } 13 | */ 14 | static void levelOrder(Node root){ 15 | if(root == null){ 16 | return; 17 | } 18 | 19 | Queue queue = new LinkedList<>(); 20 | queue.add(root);//add root 21 | 22 | while(queue.size() > 0){ 23 | Node node = queue.remove(); //remove 24 | System.out.print(node.data+" "); //print 25 | //Add Children 26 | if(node.left != null){ 27 | queue.add(node.left); 28 | } 29 | if(node.right != null){ 30 | queue.add(node.right); 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /Trees[PostClass]/CounSubtreesWithSum.java: -------------------------------------------------------------------------------- 1 | static int c = 0; 2 | static int countSubtreesWithSumXUtil(Node root,int x) 3 | { 4 | // if tree is empty 5 | if (root==null)return 0; 6 | 7 | // sum of nodes in the left subtree 8 | int ls = countSubtreesWithSumXUtil(root.left,x); 9 | 10 | // sum of nodes in the right subtree 11 | int rs = countSubtreesWithSumXUtil(root.right, x); 12 | 13 | 14 | int sum = ls + rs + root.data; 15 | 16 | // if tree's nodes sum == x 17 | if (sum == x)c++; 18 | return sum; 19 | } 20 | 21 | static int countSubtreesWithSumX(Node root, int x) 22 | { 23 | c = 0; 24 | // if tree is empty 25 | if (root==null)return 0; 26 | 27 | // sum of nodes in the left subtree 28 | int ls = countSubtreesWithSumXUtil(root.left, x); 29 | 30 | // sum of nodes in the right subtree 31 | int rs = countSubtreesWithSumXUtil(root.right, x); 32 | 33 | // check if above sum is equal to x 34 | if ((ls + rs + root.data) == x)c++; 35 | return c; 36 | } -------------------------------------------------------------------------------- /Trees[PostClass]/MirrorOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.io.*; // for handling input/output 2 | import java.util.*; // contains Collections framework 3 | 4 | // don't change the name of this class 5 | // you can add inner classes if needed 6 | class Main { 7 | public static void main (String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | int q = sc.nextInt(); 11 | 12 | int l[] = new int[n+1]; 13 | int r[] = new int[n+1]; 14 | int p[] = new int[n+1]; //parent 15 | 16 | for(int i = 1; i <= n; i++){ 17 | l[i] = sc.nextInt(); 18 | r[i] = sc.nextInt(); 19 | 20 | if(l[i] != -1) p[l[i]] = i; 21 | if(r[i] != -1) p[r[i]] = i; 22 | } 23 | while(q-- > 0){ 24 | ArrayList list = new ArrayList<>(); 25 | int x = sc.nextInt(); 26 | while(x != 1){ 27 | if(l[p[x]] == x){ 28 | list.add(0, 1); 29 | } 30 | else{ 31 | list.add(0, 0); 32 | } 33 | x = p[x]; 34 | } 35 | for(Integer i : list){ 36 | if(x == -1) break; 37 | if(i.equals(0)){ 38 | if(l[x] == -1){ 39 | x = l[x]; 40 | break; 41 | } 42 | x = l[x]; 43 | } 44 | else{ 45 | if(r[x] == -1){ 46 | x = r[x]; 47 | break; 48 | } 49 | x = r[x]; 50 | } 51 | } 52 | System.out.println(x); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /Trees[PostClass]/RightViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | private static void printRightView(Node root) 2 | { 3 | if (root == null) 4 | return; 5 | 6 | Queue queue = new LinkedList<>(); 7 | queue.add(root); 8 | 9 | while (!queue.isEmpty()) 10 | { 11 | // number of nodes at current level 12 | int n = queue.size(); 13 | 14 | // Traverse all nodes of current level 15 | for (int i = 1; i <= n; i++) { 16 | Node temp = queue.poll(); 17 | 18 | // Print the right most element at 19 | // the level 20 | if (i == n) 21 | System.out.print(temp.data + " "); 22 | 23 | // Add left node to queue 24 | if (temp.left != null) 25 | queue.add(temp.left); 26 | 27 | // Add right node to queue 28 | if (temp.right != null) 29 | queue.add(temp.right); 30 | } 31 | } 32 | } --------------------------------------------------------------------------------