├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── Arrays ├── EquilibriumPoint.java ├── FrequenciesOfLimitedRangeArrayElements.java ├── LeadersInArray.java ├── MaxOccurredInteger.java ├── MinAdjacentDifferenceCircularArray.java ├── PrefixSumArray.java ├── ReverserArrayInGroup.java ├── RotateArray.java ├── SmallestPositiveMissingNumber.java ├── StrongestNeighbour.java └── WaveArray.java ├── BinarySearchTree ├── BST.java ├── BSTElementInRange.java ├── BSTNodesInRange.java ├── CheckBST.java ├── ClosestElementInBST.java ├── FixTwoNodes.java ├── FloorInBST.java ├── LevelOrderToBST.java ├── LowestCommonAncestor.java ├── PairSumBST.java ├── TopView.java └── VerticalTraversal.java ├── BitManipulation ├── BinaryToGray.java ├── CheckKthBitSetOrNot.java ├── CheckPowerOfTwo.java ├── CountSetBits.java ├── DivideAndMultiply.java ├── FirstBitFromRight.java ├── FlipBits.java ├── LogBase2.java ├── LongestConsecutiveOnes.java ├── MSB.java ├── MissingNumber.java ├── OneOddOccuring.java ├── SetBit.java ├── SwapNumbers.java ├── ToggleBits.java └── Unset.java ├── Contest ├── BooleanMatrixProblem.java ├── ConversionToOne.java ├── GetTheShadow.java ├── KSum.java ├── KthSmallestDifference.java ├── NearestPerfectSquare.java ├── ToggleTheMiddle.java ├── WithoutAdjacent.java └── XORPair.java ├── DSU └── ConnectedComponent.java ├── Deque ├── ImplementaionDeque.java └── MaxAllSubarraySizeK.java ├── DynamicProgramming ├── FibonacciNumber.java └── LongestCommonSubsequence.java ├── Graph ├── DetectCycleDirected.java ├── DetectCycleKahnAlgo.java ├── DetectCycleUndirected.java ├── FindPathExists.java ├── Graph.java ├── NumberIsland.java ├── PrimsAlgorithm.java ├── ShortestPathDAG.java ├── ShortestPathUnweightedGraph.java ├── TopologicalSortDFS.java └── TopologicalSorting.java ├── Hashing ├── CheckTwoArraysEqual.java ├── CountDistinctElementInEveryWindow.java ├── CountDistinctElements.java ├── CountNonRepeatedElements.java ├── FirstRepeatingElement.java ├── FrequencyOfArrayElements.java ├── InsertionOfArray.java ├── Itinerary-from-a-given-list-of-tickets.java ├── LongestCommonSpanTwoBinaryArray.java ├── LongestCommonSubsequence.java ├── LongestSubArrayWithGivenSum.java ├── P_HashMap.java ├── P_HashSet.java ├── PairWithSumX.java ├── PrintNonRepeatedElements.java ├── SeparateChaining.java ├── SubArrayWithGivenSum.java ├── SubArrayWithZeroSum.java ├── UnionOfArray.java └── WinnerElection.java ├── Heap ├── Heap.java ├── HeapSort.java ├── KClosestElement.java ├── KthLargestInAStream.java ├── MedianOfStream.java ├── MergeKSortedArrays.java ├── PrintKLargestElements.java ├── PriorityQueueDemo.java ├── PurchasingMaxItems.java ├── ReorganizeString.java └── SortKSortedArray.java ├── Implementation ├── BFS.java ├── BinarySearch.java ├── DFS.java ├── InsertionSort.java ├── MergeSort.java ├── P_LinkedList.java ├── P_Queue.java ├── P_Stack.java └── QuickSort.java ├── LinkedList ├── DeleteAlternate.java ├── DoublyLinkedList.java ├── MergeKLinkedList.java ├── MiddleOfLinkedList.java ├── NthPointerFromENd.java ├── RmDuplicateSorted.java ├── SinglyLinkedList.java ├── SplitAlternatingly.java └── UnionIntersection.java ├── Mathematics ├── LastTermOfGP.java ├── NumberOfDigitsInANumber.java └── PrimeNumber.java ├── Matrix ├── AddMatrix.java ├── BooleanMatrixProblem.java ├── SearchInMatrix.java ├── SnakePattern.java └── SpiralTraversal.java ├── Miscellaneous ├── FactorialDigits.java ├── NaturalNumbers.java └── QuadraticEquation.java ├── Queue ├── GenerateNumberGivenDigits.java ├── QueueAsArray.java ├── QueueImplementation.java ├── ReverseQueue.java └── StackUsingQueue.java ├── README.md ├── Recursion ├── JosephusProblem.java ├── PossibleWordsFromPhoneDigits.java ├── RodCutting.java ├── StringPalindrome.java ├── SubsetOfString.java ├── SubsetSumArray.java └── TowerOfHanoi.java ├── Searching ├── FindFloor.java ├── LeftMostIndex.java ├── MajorityElement.java ├── OccurrenceCountOfElement.java ├── PeakElements.java ├── SortedRotatedArraySearch.java ├── SquareRoot.java └── TwoPointerApproach.java ├── SegmentTree ├── BinaryIndexTreeImplementation.java └── SegmentTreeImplementation.java ├── Sorting ├── BucketSort.java ├── ChocolateDistribution.java ├── CountInversionInArray.java ├── CountingSort.java ├── CycleSort.java ├── IntersectionOfTwoSortedArray.java ├── KthSmallestElement.java ├── ListTypeArray.java ├── MergeOverlappingIntervals.java ├── MergeTwoSortedArray.java ├── NormalArray.java ├── QuickSortUsingHoarePartition.java ├── QuickSortUsingLomutoPartition.java ├── RadixSort.java ├── SegregateElementOfThreeType.java ├── SegregateElementsOfTwoType.java └── UnionOfTwoSortedArray.java ├── Stack ├── ArrayImplementation.java ├── BalancedParenthesis.java ├── DeleteMidOfStack.java ├── EvalPostfix.java ├── GetMin.java ├── GetMinAtPop.java ├── Histogram1.java ├── Histogram2.java ├── InfixToPostfix.java ├── KStackInArray.java ├── LargestRectangularArea.java ├── LinkedListStack.java ├── NextGreater.java ├── PreviousGreater.java ├── RemoveConsecutiveDuplicates.java ├── RemoveConsecutiveDuplicates2.java ├── StockSpan.java └── TwoStacksInAnArray.java ├── Strings ├── CheckAnagram.java ├── CheckPanagram.java ├── IsogramWords.java ├── KeypadTyping.java ├── LeftMostRepeating.java ├── LexicographicRankProblem.java ├── PermutationOfPatternExist.java ├── RotationOfStringOrNot.java └── SumOfNumberInString.java ├── Tree ├── BinaryTreeImplementation.java ├── HeightOfBinaryTree.java ├── LevelOrderTraversal.java ├── LowestCommonAncestor.java ├── MaxInBinaryTree.java ├── MorrisTraversal.java ├── PrintLeftView.java ├── PrintNodeAtDistK.java ├── SizeOfBinaryTree.java └── TreeTraversal.java ├── _config.yml └── trie ├── CamelCase.java └── MostFrequentWord.java /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /Practice 2 | .idea/ 3 | SummerTrainingGFG.iml 4 | out/ 5 | -------------------------------------------------------------------------------- /Arrays/EquilibriumPoint.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * @author Vishal Singh */ 9 | public class EquilibriumPoint { 10 | static boolean hasEquilibriumPoint(int[] arr,int n){ 11 | int sum = 0; 12 | for (int i = 0; i < n; i++) { 13 | sum += arr[i]; 14 | } 15 | int leftSum = 0; 16 | for (int i = 0; i < n; i++) { 17 | if (leftSum == sum-arr[i]){ 18 | return true; 19 | } 20 | leftSum+=arr[i]; 21 | sum-=arr[i]; 22 | } 23 | return false; 24 | } 25 | public static void main(String[] args)throws IOException { 26 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 27 | System.out.print("Enter the size of the array\n:->"); 28 | int n = Integer.parseInt(br.readLine()); 29 | String[] strings = br.readLine().split(" "); 30 | int[] arr = new int[n]; 31 | for (int i = 0; i < n; i++) { 32 | arr[i] = Integer.parseInt(strings[i]); 33 | } 34 | System.out.println(hasEquilibriumPoint(arr,n)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Arrays/FrequenciesOfLimitedRangeArrayElements.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.ArrayList; 7 | 8 | /** 9 | *@author Vishal Singh */ 10 | /* 11 | * Given an array A[] of N positive integers which can contain integers from 1 to N 12 | * where elements can be repeated or can be absent from the array. 13 | * Your task is to count the frequency of all elements from 1 to N.*/ 14 | 15 | public class FrequenciesOfLimitedRangeArrayElements { 16 | public static void main(String[] args) throws IOException { 17 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 18 | int t = Integer.parseInt(br.readLine()); 19 | while (t-- > 0) { 20 | int n = Integer.parseInt(br.readLine()); 21 | String[] str = br.readLine().split(" "); 22 | int[] arr = new int[n]; 23 | int[] temp = new int[n]; 24 | for (int i = 0; i < n; i++) { 25 | arr[i] = Integer.parseInt(str[i]); 26 | temp[i] = 0; 27 | } 28 | for (int i = 0; i < n; i++) { 29 | temp[arr[i]-1] = temp[arr[i]-1]+1; 30 | } 31 | for (int i = 0; i < n; i++) { 32 | System.out.print(temp[i]+" "); 33 | } 34 | /* USING ARRAY LIST */ 35 | ArrayList a= new ArrayList(n); 36 | for (int i = 0; i < n ; i++) { 37 | a.add(0); 38 | } 39 | for (int i = 0; i < n ; i++) { 40 | int index = arr[i] -1; 41 | int element = a.get(index)+1; 42 | a.set(index,element); 43 | } 44 | System.out.println(a); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Arrays/LeadersInArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.ArrayList; 7 | 8 | /** 9 | * @author Vishal Singh */ 10 | public class LeadersInArray { 11 | static void leaderInArray(int[] arr,int n){ 12 | ArrayList arrayList = new ArrayList<>(n); 13 | int currLeader = arr[n-1]; 14 | arrayList.add(currLeader); 15 | for (int i = n-2; i >= 0 ; i--) { 16 | if (arr[i]>=currLeader){ 17 | currLeader = arr[i]; 18 | arrayList.add(currLeader); 19 | } 20 | } 21 | for (int i = arrayList.size()-1; i >=0 ; i--) { 22 | System.out.print(arrayList.get(i)+" "); 23 | } 24 | System.out.println(); 25 | } 26 | public static void main(String[] args)throws IOException { 27 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 28 | int testCase = Integer.parseInt(br.readLine()); 29 | while (testCase-->0){ 30 | int n = Integer.parseInt(br.readLine()); 31 | String[] input = br.readLine().split(" "); 32 | int[] arr = new int[n]; 33 | for (int i = 0; i < n; i++) { 34 | arr[i] = Integer.parseInt(input[i]); 35 | } 36 | leaderInArray(arr,n); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Arrays/MaxOccurredInteger.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * @author Vishal Singh */ 9 | public class MaxOccurredInteger { 10 | static int maxOccurredInteger(int[] left, int[] right){ 11 | int[] arr = new int[1000000]; 12 | for (int i = 0; i < left.length; i++) { 13 | arr[left[i]]+=1; 14 | arr[right[i]+1]--; 15 | } 16 | int maxSum = arr[0]; 17 | int index = 0; 18 | for (int i = 1; i < arr.length; i++) { 19 | arr[i] = arr[i] + arr[i-1]; 20 | if (maxSum < arr[i]){ 21 | maxSum = arr[i]; 22 | index = i; 23 | } 24 | } 25 | return index; 26 | } 27 | public static void main(String[] args)throws IOException { 28 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 29 | System.out.println(maxOccurredInteger( new int[]{1,2,3}, 30 | new int[]{3,5,7} 31 | )); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Arrays/MinAdjacentDifferenceCircularArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.StringTokenizer; 7 | 8 | 9 | /** 10 | * @author Vishal Singh */ 11 | 12 | public class MinAdjacentDifferenceCircularArray { 13 | static class FastReader{ 14 | BufferedReader br; 15 | StringTokenizer st; 16 | FastReader(){ 17 | br = new BufferedReader(new InputStreamReader(System.in)); 18 | } 19 | String next(){ 20 | while (st == null || !st.hasMoreElements()){ 21 | try { 22 | st = new StringTokenizer(br.readLine()); 23 | } 24 | catch (IOException e){ 25 | e.printStackTrace(); 26 | } 27 | } 28 | return st.nextToken(); 29 | } 30 | int nextInt(){ 31 | return Integer.parseInt(next()); 32 | } 33 | String nextLine(){ 34 | String str = ""; 35 | try { 36 | str = br.readLine(); 37 | } 38 | catch (IOException e){ 39 | e.printStackTrace(); 40 | } 41 | return str; 42 | } 43 | } 44 | public static void main(String[] args) { 45 | FastReader fastReader = new FastReader(); 46 | int testCases = fastReader.nextInt(); 47 | while (testCases-->0){ 48 | int n = fastReader.nextInt(); 49 | String[] arr = fastReader.nextLine().split(" "); 50 | int minDiffer = Math.abs( Integer.parseInt(arr[n-1]) -Integer.parseInt(arr[0]) ); 51 | System.out.println(minDiffer); 52 | for (int i = 1; i < n 53 | ; i++) { 54 | int minCheck = Math.abs( Integer.parseInt(arr[i]) - Integer.parseInt(arr[i-1]) ); 55 | System.out.println(" "+minCheck); 56 | if (minCheck"); 12 | int n = Integer.parseInt(br.readLine()); 13 | String[] strings = br.readLine().split(" "); 14 | int[] arr = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | arr[i] = Integer.parseInt(strings[i]); 17 | } 18 | // Finding the prefix sum 19 | for (int i = 1; i < arr.length; i++) { 20 | arr[i] = arr[i]+arr[i-1]; 21 | } 22 | for (int i: 23 | arr) { 24 | System.out.print(i+" "); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Arrays/ReverserArrayInGroup.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.util.ArrayList; 4 | /** 5 | * @author Vishal Singh */ 6 | 7 | public class ReverserArrayInGroup { 8 | public static ArrayList reverseInGroups(ArrayList mv, int n, int k) { 9 | for (int i = 0; i < n ; i=i+k) { 10 | 11 | int l = i; 12 | int r = Math.min(i + k - 1, n - 1); 13 | int temp; 14 | while (l arrayList = new ArrayList<>(); 26 | arrayList.add(1); 27 | arrayList.add(2); 28 | arrayList.add(3); 29 | arrayList.add(4); 30 | arrayList.add(5); 31 | arrayList.add(6); 32 | System.out.println(reverseInGroups(arrayList,arrayList.size(),3)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Arrays/RotateArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class RotateArray { 6 | static void reverse(int arr[],int low,int high){ 7 | int temp = 0; 8 | while (low=0 && arr[i]<=n){ 14 | temp[arr[i]] = 1; 15 | } 16 | } 17 | for (int i = 1; i <= n; i++) { 18 | if (temp[i] == 0){ 19 | return i; 20 | } 21 | } 22 | return n+1; 23 | } 24 | public static void main(String[] args)throws IOException { 25 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 26 | int testCase = Integer.parseInt(br.readLine()); 27 | while (testCase-->0) { 28 | int n = Integer.parseInt(br.readLine()); 29 | String[] input = br.readLine().split(" "); 30 | int[] arr = new int[n]; 31 | for (int i = 0; i < n; i++) { 32 | arr[i] = Integer.parseInt(input[i]); 33 | } 34 | System.out.println(smallestPositiveNumber(arr,n)); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Arrays/StrongestNeighbour.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class StrongestNeighbour { 6 | 7 | static void maximumAdjacent(int sizeOfArray, int[] arr){ 8 | /* 9 | ******************************* 10 | * Use string buffer for fast output 11 | * ***********************************/ 12 | StringBuffer s=new StringBuffer(); 13 | for(int i = 0;i < sizeOfArray-1; i=i+1){ 14 | s.append(Math.max(arr[i], arr[i + 1])).append(" "); 15 | } 16 | System.out.print(s); 17 | } 18 | public static void main(String[] args) { 19 | maximumAdjacent(6,new int[]{1,2,2,3,4,5}); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Arrays/WaveArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Arrays; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * @author Vishal Singh */ 9 | 10 | public class WaveArray { 11 | public static void main(String[] args)throws IOException { 12 | /* 13 | * Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it. 14 | * In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). 15 | * */ 16 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 17 | int t = Integer.parseInt(br.readLine()); 18 | while(t-- > 0){ 19 | int n = Integer.parseInt(br.readLine()); 20 | String[] str = br.readLine().split(" "); 21 | int[] arr = new int[n]; 22 | for (int i = 0; i < n; i++) { 23 | arr[i] = Integer.parseInt(str[i]); 24 | } 25 | for (int i = 0; i < n-1; i+=2) { 26 | int temp = arr[i]; 27 | arr[i] = arr[i+1]; 28 | arr[i+1] = temp; 29 | } 30 | for (int i = 0; i < n; i++) { 31 | System.out.print(arr[i]+" "); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /BinarySearchTree/BSTElementInRange.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BinarySearchTree; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 25-12-2020 8 | */ 9 | 10 | public class BSTElementInRange { 11 | static class Node { 12 | int data; 13 | Node left, right; 14 | 15 | Node(int data) { 16 | this.data = data; 17 | } 18 | } 19 | 20 | Node root; 21 | static ArrayList arrayList; 22 | 23 | public static ArrayList printNearNodes(Node root, int low, int high) { 24 | arrayList = new ArrayList<>(); 25 | inOrder(root, low, high); 26 | return arrayList; 27 | } 28 | 29 | static void inOrder(Node root, int low, int high) { 30 | if (root == null){ 31 | return; 32 | } 33 | if (low < root.data) { 34 | inOrder(root.left, low, high); 35 | } 36 | if (root.data >= low && root.data <= high) { 37 | arrayList.add(root.data); 38 | } 39 | if (high >= root.data) { 40 | inOrder(root.right, low, high); 41 | } 42 | 43 | } 44 | 45 | static int func(int a,int b){ 46 | if (a set = new HashSet<>(); 20 | static void findPairSum(Node root,int sum){ 21 | System.out.println(inOrder(root, sum)); 22 | } 23 | static boolean inOrder(Node root, int sum){ 24 | if (root == null){ 25 | return false; 26 | } 27 | if(inOrder(root.left,sum)){ 28 | return true; 29 | } 30 | if (set.contains(sum - root.data)){ 31 | return true; 32 | }else { 33 | set.add(root.data); 34 | } 35 | return inOrder(root.right,sum); 36 | } 37 | public static void main(String[] args){ 38 | PairSumBST tree = new PairSumBST(); 39 | tree.root = new Node(20); 40 | tree.root.left = new Node(8); 41 | tree.root.right = new Node(22); 42 | tree.root.left.left = new Node(4); 43 | tree.root.left.right = new Node(12); 44 | tree.root.left.right.left = new Node(10); 45 | tree.root.left.right.right = new Node(14); 46 | findPairSum(tree.root, 34); 47 | } 48 | } -------------------------------------------------------------------------------- /BitManipulation/BinaryToGray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class BinaryToGray { 6 | static void convert(int n){ 7 | int x = n; 8 | int temp = 0; 9 | while ((x>>=1) != 0){ 10 | temp++; 11 | } 12 | System.out.println(Math.pow(2,temp)); 13 | } 14 | public static void main(String[] args) { 15 | convert(7); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /BitManipulation/CheckKthBitSetOrNot.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class CheckKthBitSetOrNot { 6 | static void kthBitLeftShift(int n, int k){ 7 | if ( (n & (1 << (k-1))) != 0) { 8 | System.out.println("Yes the kth bit is set as One"); 9 | } 10 | else { 11 | System.out.println("No the kth bit is not set as One"); 12 | } 13 | } 14 | static void kthBitRightShift(int n, int k){ 15 | if ( ( (n>>(k-1)) & 1 ) == 1 ) { 16 | System.out.println("Yes the kth bit is set as One"); 17 | } 18 | else { 19 | System.out.println("No the kth bit is not set as One"); 20 | } 21 | } 22 | public static void main(String[] args) { 23 | int n = 5; 24 | int k = 3; 25 | kthBitLeftShift(n,k); 26 | kthBitRightShift(n,k); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /BitManipulation/CheckPowerOfTwo.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class CheckPowerOfTwo { 6 | public static void main(String[] args) { 7 | int num = 15; 8 | int num1 = 16; 9 | System.out.println( (num & (num-1)) == 0); 10 | System.out.println( (num1 &(num1-1)) == 0); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BitManipulation/CountSetBits.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class CountSetBits { 6 | /* 7 | * n = 5 8 | * binary = 1 0 1 9 | * in 32 bits 000000.......0101 10 | * */ 11 | public static void main(String[] args) { 12 | int n = 17; 13 | int res = 0; 14 | while (n>0){ 15 | if (n%2 != 0) { 16 | res++; 17 | } 18 | n = n/2; 19 | } 20 | System.out.println(res); 21 | n = 5; 22 | res = 0; 23 | while (n>0){ 24 | if ((n&1) == 0) { 25 | res++; 26 | } 27 | n = n>>1; 28 | } 29 | n = 5; 30 | res = 0; 31 | while (n>0){ 32 | res += (n&1); 33 | n = n>>1; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /BitManipulation/DivideAndMultiply.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class DivideAndMultiply { 6 | public static void main(String[] args) { 7 | int n = 5; 8 | System.out.println("Divide: "+(n>>1)); 9 | System.out.println("Multiply: "+(n<<1)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BitManipulation/FirstBitFromRight.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class FirstBitFromRight { 6 | static int firstBit(int n){ 7 | if (n>=1){ 8 | int x = n ^ (n-1); 9 | x = x + 1; 10 | System.out.println(x); 11 | System.out.println((Math.log(x))); 12 | return (int)Math.ceil(Math.log(x)/Math.log(2)); 13 | } 14 | return 0; 15 | } 16 | public static void main(String[] args) { 17 | System.out.println(firstBit(544)); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /BitManipulation/FlipBits.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class FlipBits { 6 | public static void main(String[] args) { 7 | int num = 23; 8 | int allBits1 = 0; 9 | System.out.println(allBits1); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BitManipulation/LogBase2.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class LogBase2 { 6 | //only for 32 bit 7 | public static void main(String[] args) { 8 | int num = 160; 9 | int log2 = 0; 10 | while ((num>>=1) != 0){ 11 | log2++; 12 | } 13 | System.out.println(log2); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /BitManipulation/LongestConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class LongestConsecutiveOnes { 6 | static int maxConsecutiveOnes(int x) { 7 | int currMax = 0; 8 | int max = 0; 9 | while(x>0){ 10 | if((x&1) == 1) { 11 | currMax++; 12 | } 13 | else { 14 | currMax = 0; 15 | } 16 | if(currMax>=max){ 17 | max = currMax; 18 | } 19 | x = x>>1; 20 | } 21 | return max; 22 | } 23 | public static void main(String[] args) { 24 | System.out.println(maxConsecutiveOnes(14)); 25 | System.out.println(maxConsecutiveOnes(222)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /BitManipulation/MSB.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class MSB{ 6 | public static void main(String[] args) { 7 | int n = 10; 8 | int temp = 0; 9 | while ((n>>=1) != 0){ 10 | temp++; 11 | } 12 | System.out.println("MSB is: "+Math.pow(2,temp)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BitManipulation/MissingNumber.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.BitManipulation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class MissingNumber { 6 | public static void main(String[] args) { 7 | int arr[] = {1,4,3,2,5,6,7,9}; 8 | int one = 1; 9 | for (int i = 2; i <=1+arr.length ; i++) { 10 | one^=i; 11 | } 12 | int two = arr[0]; 13 | for (int i = 1; i 0){ 46 | int n = fr.nextInt(); 47 | int k = fr.nextInt(); 48 | int[] arr = new int[n]; 49 | for (int i = 0; i < n; i++) { 50 | arr[i] = fr.nextInt(); 51 | } 52 | Arrays.sort(arr); 53 | long sum = 0; 54 | for (int i = 0; i < k; i++) { 55 | sum+=arr[i]; 56 | } 57 | System.out.println(sum); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Contest/KthSmallestDifference.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Contest; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.Arrays; 7 | import java.util.StringTokenizer; 8 | 9 | /** 10 | * @author Vishal Singh 11 | */ 12 | public class KthSmallestDifference { 13 | static class FastReader{ 14 | BufferedReader br; 15 | StringTokenizer st; 16 | public FastReader(){ 17 | br = new BufferedReader(new InputStreamReader(System.in)); 18 | } 19 | String next(){ 20 | while (st == null || !st.hasMoreElements()){ 21 | try { 22 | st = new StringTokenizer(br.readLine()); 23 | }catch (IOException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | return st.nextToken(); 28 | } 29 | int nextInt(){ 30 | return Integer.parseInt(next()); 31 | } 32 | String nextLine(){ 33 | String str = ""; 34 | try { 35 | str = br.readLine(); 36 | } catch (IOException e) { 37 | e.printStackTrace(); 38 | } 39 | return str; 40 | } 41 | } 42 | static int smallestDistancePair(int[] arr, int k) { 43 | Arrays.sort(arr); 44 | int low = 0; 45 | int high = arr[arr.length - 1] - arr[0]; 46 | while (low < high) { 47 | int mi = (low + high) / 2; 48 | int count = 0, left = 0; 49 | for (int right = 0; right < arr.length; ++right) { 50 | while (arr[right] - arr[left] > mi) left++; 51 | count += right - left; 52 | } 53 | if (count >= k) high = mi; 54 | else low = mi + 1; 55 | } 56 | return low; 57 | } 58 | public static void main(String[] args) { 59 | FastReader fr = new FastReader(); 60 | int t = fr.nextInt(); 61 | while (t-->0){ 62 | int n = fr.nextInt(); 63 | int k = fr.nextInt(); 64 | int[] arr = new int[n]; 65 | for (int i = 0; i < n; i++) { 66 | arr[i] = fr.nextInt(); 67 | } 68 | System.out.println(smallestDistancePair(arr,k)); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Contest/NearestPerfectSquare.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Contest; 2 | import java.io.BufferedReader; 3 | import java.io.IOException; 4 | import java.io.InputStreamReader; 5 | import java.util.StringTokenizer; 6 | /** 7 | * @author Vishal Singh */ 8 | 9 | public class NearestPerfectSquare { 10 | static class FastReader 11 | { 12 | BufferedReader br; 13 | StringTokenizer st; 14 | 15 | public FastReader() 16 | { 17 | br = new BufferedReader(new 18 | InputStreamReader(System.in)); 19 | } 20 | String next() 21 | { 22 | while (st == null || !st.hasMoreElements()) 23 | { 24 | try 25 | { 26 | st = new StringTokenizer(br.readLine()); 27 | } 28 | catch (IOException e) 29 | { 30 | e.printStackTrace(); 31 | } 32 | } 33 | return st.nextToken(); 34 | } 35 | int nextInt(){ 36 | return Integer.parseInt(next()); 37 | } 38 | long nextLong(){ 39 | return Long.parseLong(next()); 40 | } 41 | } 42 | public static void main(String[] args) { 43 | FastReader fast = new FastReader(); 44 | 45 | int testCases = fast.nextInt(); 46 | 47 | for (int i = 0; i < testCases; i++) { 48 | long number = fast.nextLong(); 49 | long prev; 50 | long next; 51 | 52 | if ((long)(Math.sqrt(number)) == Math.sqrt(number)){ 53 | prev = ((long)Math.floor(Math.sqrt(number)))-1; 54 | next = ((long)Math.floor(Math.sqrt(number)))+1; 55 | } 56 | else { 57 | prev = ((long)Math.floor(Math.sqrt(number))); 58 | next = ((long)Math.floor(Math.sqrt(number)))+1; 59 | } 60 | System.out.println(( number - (prev*prev) ) <= Math.abs( number - (next*next) ) ? (prev*prev):(next*next)); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Contest/ToggleTheMiddle.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Contest; 2 | 3 | 4 | import java.io.BufferedReader; 5 | import java.io.IOException; 6 | import java.io.InputStreamReader; 7 | import java.util.StringTokenizer; 8 | 9 | /** 10 | * @author Vishal Singh 11 | */ 12 | public class ToggleTheMiddle { 13 | static class FastReader{ 14 | BufferedReader br; 15 | StringTokenizer st; 16 | public FastReader(){ 17 | br = new BufferedReader(new InputStreamReader(System.in)); 18 | } 19 | String next(){ 20 | while (st == null || !st.hasMoreElements()){ 21 | try { 22 | st = new StringTokenizer(br.readLine()); 23 | } catch (IOException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | return st.nextToken(); 28 | } 29 | String nextLine(){ 30 | String str = ""; 31 | try { 32 | str = br.readLine(); 33 | }catch (IOException e){ 34 | e.printStackTrace(); 35 | } 36 | return str; 37 | } 38 | int nextInt(){ 39 | return Integer.parseInt(next()); 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | FastReader fr = new FastReader(); 45 | int t = fr.nextInt(); 46 | while (t-->0){ 47 | int n = fr.nextInt(); 48 | int temp = n; 49 | n = (int)(Math.log(n)/Math.log(2) + 1); 50 | //System.out.println("N: "+n); 51 | if (n%2 == 0){ 52 | int bit1 = (int)(n/2); 53 | int r = 1 << (bit1-1); 54 | temp = temp^r; 55 | n = (int)(Math.log(temp)/Math.log(2) + 1); 56 | int b = bit1+1; 57 | if (n%2 == 0){ 58 | r = 1 << (b-1); 59 | } 60 | else { 61 | r = 1 << (b-2); 62 | } 63 | System.out.println(temp^r); 64 | }else { 65 | int bit1 = (int)(n/2)+1; 66 | int r = 1 << (bit1-1); 67 | System.out.println(temp^r); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Contest/XORPair.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Contest; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.HashSet; 7 | import java.util.StringTokenizer; 8 | 9 | /** 10 | * @author Vishal Singh 11 | */ 12 | public class XORPair { 13 | static class FastReader{ 14 | BufferedReader br; 15 | StringTokenizer st; 16 | public FastReader(){ 17 | br = new BufferedReader(new InputStreamReader(System.in)); 18 | } 19 | String next(){ 20 | while (st == null || !st.hasMoreElements()){ 21 | try { 22 | st = new StringTokenizer(br.readLine()); 23 | }catch (IOException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | return st.nextToken(); 28 | } 29 | int nextInt(){ 30 | return Integer.parseInt(next()); 31 | } 32 | String nextLine(){ 33 | String str = ""; 34 | try { 35 | str = br.readLine(); 36 | } catch (IOException e) { 37 | e.printStackTrace(); 38 | } 39 | return str; 40 | } 41 | } 42 | public static void main(String[] args) { 43 | FastReader fr = new FastReader(); 44 | int t = fr.nextInt(); 45 | while (t-->0){ 46 | int n = fr.nextInt(); 47 | int c = fr.nextInt(); 48 | int[] arr = new int[n]; 49 | for (int i = 0; i < n; i++) { 50 | arr[i] = fr.nextInt(); 51 | } 52 | HashSet set = new HashSet<>(); 53 | int r = 0; 54 | for (int i = 0; i < n; i++) { 55 | if (set.contains(arr[i]^c)){ 56 | r+=1; 57 | } 58 | set.add(arr[i]); 59 | } 60 | if (r>0){ 61 | System.out.println("Yes"); 62 | }else { 63 | System.out.println("No"); 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /DSU/ConnectedComponent.java: -------------------------------------------------------------------------------- 1 | package DSU; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 7/24/2021 8 | */ 9 | public class ConnectedComponent { 10 | static class Solution { 11 | 12 | class DSU { 13 | 14 | int[] parent, rank; 15 | int n; 16 | 17 | DSU(int n) { 18 | parent = new int[n]; 19 | rank = new int[n]; 20 | } 21 | 22 | public void union(int x, int y) { 23 | 24 | int xx = find(x); 25 | int yy = find(y); 26 | 27 | if (xx == yy) return; 28 | 29 | if (rank[xx] < rank[yy]) { 30 | parent[xx] = yy; 31 | } else if (rank[yy] < rank[xx]) { 32 | parent[yy] = xx; 33 | } else { 34 | parent[yy] = xx; 35 | rank[xx]++; 36 | } 37 | 38 | } 39 | 40 | public int find(int i) { 41 | if (parent[i] == i) return i; 42 | parent[i] = find(parent[i]); 43 | return parent[i]; 44 | } 45 | 46 | } 47 | 48 | public int detectCycle(int V, ArrayList> adj) { 49 | DSU d = new DSU(V); 50 | boolean[] vis = new boolean[V]; 51 | boolean cycle = false; 52 | for (int u = 0; u < adj.size(); u++) { 53 | boolean cycleFound = false; 54 | for (int v : adj.get(u)) { 55 | if (!vis[u] || !vis[v]) { 56 | vis[v] = true; 57 | vis[u] = true; 58 | int vv = d.find(v); 59 | int uu = d.find(u); 60 | if (vv == uu) { 61 | cycle = true; 62 | cycleFound = true; 63 | break; 64 | } 65 | else { 66 | d.union(v,u); 67 | } 68 | } 69 | } 70 | if (cycleFound) break; 71 | } 72 | return cycle ? 1 : 0; 73 | } 74 | } 75 | } -------------------------------------------------------------------------------- /Deque/ImplementaionDeque.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Deque; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class ImplementaionDeque { 9 | public static void main(String[] args) { 10 | ArrayDeque deque = new ArrayDeque<>(); 11 | deque.offerFirst(1); 12 | deque.offerLast(1); 13 | deque.addFirst(1); 14 | deque.addLast(1); 15 | System.out.println(deque); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Deque/MaxAllSubarraySizeK.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Deque; 2 | 3 | import java.util.Deque; 4 | import java.util.LinkedList; 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | public class MaxAllSubarraySizeK { 10 | public static void main(String[] args) { 11 | 12 | int[] arr = {10,8,5,12,15,7,6}; 13 | int k = 3; 14 | //total subarray = n-k+1 15 | int[] temp = new int[arr.length]; 16 | temp[0] = arr[0]; 17 | for (int i = 1; i < arr.length; i++) { 18 | temp[i] = Math.max(temp[i-1],arr[i]); 19 | } 20 | for (int i = 0; i < arr.length-k+1; i++) { 21 | System.out.print(temp[i+k-1]+" "); 22 | } 23 | Deque deque = new LinkedList<>(); 24 | deque.offerFirst(arr[0]); 25 | for (int i = 0; i < k; i++) { 26 | while (!deque.isEmpty() && arr[i]>=deque.peekLast()){ 27 | deque.removeLast(); 28 | } 29 | deque.addLast(i); 30 | } 31 | for (int i = k; i < arr.length; i++) { 32 | System.out.print(deque.peek()+" "); 33 | while (!deque.isEmpty() && deque.peek()<=i-k){ 34 | deque.removeFirst(); 35 | } 36 | while (!deque.isEmpty() && arr[i] >= arr[deque.peekLast()]){ 37 | deque.removeLast(); 38 | } 39 | deque.addLast(i); 40 | } 41 | System.out.println(!deque.isEmpty()?arr[deque.peek()]:""); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /DynamicProgramming/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | /** 5 | * @author Vishal Singh 6 | */ 7 | public class FibonacciNumber { 8 | /* 9 | * Idea is to save those values which you have already computed 10 | * Memoization Top-Down */ 11 | static int[] memoize; 12 | static int fibMemoization(int n){ 13 | if (memoize[n] == -1){ 14 | int res; 15 | if (n == 0 || n == 1){ 16 | res = n; 17 | }else { 18 | res = fibMemoization(n-1) + fibMemoization(n-2); 19 | } 20 | memoize[n] = res; 21 | } 22 | return memoize[n]; 23 | } 24 | /* 25 | * Faster than memoization 26 | * Tabulations Bottom - Up*/ 27 | static int fibTabulation(int n){ 28 | int[] f = new int[n+1]; 29 | f[0] = 0; 30 | f[1] = 1; 31 | for (int i = 2; i <= n; i++) { 32 | f[i] = f[i-1] + f[i-2]; 33 | } 34 | return f[n]; 35 | } 36 | public static void main(String[] args) { 37 | int n = 6; 38 | memoize = new int[n+1]; 39 | Arrays.fill(memoize,-1); 40 | System.out.println(fibMemoization(n)); 41 | 42 | System.out.println(fibTabulation(6)); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Graph/DetectCycleDirected.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 07-02-2021 8 | */ 9 | 10 | public class DetectCycleDirected { 11 | public static void addEdge(ArrayList> graph,int s,int d ){ 12 | graph.get(s).add(d); 13 | } 14 | public static void detectCycle(ArrayList> graph,int v){ 15 | boolean[] vis = new boolean[v]; 16 | boolean[] recStack = new boolean[v]; 17 | boolean isCycle = false; 18 | for (int i = 0; i < v; i++) { 19 | if (!vis[i]){ 20 | if (dfs(graph,vis,recStack,i)){ 21 | System.out.println("Cycle"); 22 | isCycle = true; 23 | } 24 | } 25 | } 26 | if (!isCycle){ 27 | System.out.println("No cycle"); 28 | } 29 | } 30 | public static boolean dfs(ArrayList> graph,boolean[] vis,boolean[] recStack,int s){ 31 | vis[s] = true; 32 | recStack[s] = true; 33 | for (int d: graph.get(s)){ 34 | if (!vis[d]){ 35 | if (dfs(graph,vis,recStack,d)){ 36 | return true; 37 | } 38 | }else if (recStack[d]){ 39 | return true; 40 | } 41 | } 42 | recStack[s] = false; 43 | return false; 44 | } 45 | public static void main(String[] args) { 46 | ArrayList> graph = new ArrayList<>(); 47 | int v = 6; 48 | for (int i = 0; i < v; i++) { 49 | graph.add(new ArrayList<>()); 50 | } 51 | addEdge(graph,0,1); 52 | addEdge(graph,2,1); 53 | addEdge(graph,2,3); 54 | addEdge(graph,3,4); 55 | addEdge(graph,4,5); 56 | addEdge(graph,5,3); 57 | System.out.println(graph); 58 | detectCycle(graph,v); 59 | } 60 | } -------------------------------------------------------------------------------- /Graph/DetectCycleKahnAlgo.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.ArrayList; 5 | import java.util.Queue; 6 | /** 7 | * @author Vishal Singh 8 | * 07-02-2021 */ 9 | 10 | public class DetectCycleKahnAlgo { 11 | public static void addEdge(ArrayList> graph, int s,int d){ 12 | graph.get(s).add(d); 13 | } 14 | public static void detectCycle(ArrayList> graph,int v){ 15 | int[] dependency = new int[v]; 16 | for (ArrayList integers : graph) { 17 | for (int d : integers) { 18 | dependency[d]++; 19 | } 20 | } 21 | Queue q = new ArrayDeque<>(); 22 | for (int i = 0; i < v; i++) { 23 | if (dependency[i] == 0){ 24 | q.add(i); 25 | } 26 | } 27 | int count = 0; 28 | while (!q.isEmpty()){ 29 | int s = q.poll(); 30 | count++; 31 | for (int d: graph.get(s)){ 32 | dependency[d]--; 33 | if (dependency[d]==0){ 34 | q.add(d); 35 | } 36 | } 37 | } 38 | if (count!=v){ 39 | System.out.println("Cycle"); 40 | }else { 41 | System.out.println("No cycle"); 42 | } 43 | } 44 | public static void main(String[] args) { 45 | ArrayList> graph = new ArrayList<>(); 46 | int v = 5; 47 | for (int i = 0; i < v; i++) { 48 | graph.add(new ArrayList<>()); 49 | } 50 | addEdge(graph,0, 1); 51 | addEdge(graph,4, 1); 52 | addEdge(graph,1, 2); 53 | addEdge(graph,2, 3); 54 | addEdge(graph,3, 1); 55 | 56 | detectCycle(graph,v); 57 | } 58 | } -------------------------------------------------------------------------------- /Graph/DetectCycleUndirected.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | 6 | /** 7 | * @author Vishal Singh 8 | * 06-02-2021 9 | */ 10 | 11 | public class DetectCycleUndirected { 12 | private static void addEdge(ArrayList> graph,int u,int v){ 13 | graph.get(u).add(v); 14 | graph.get(v).add(u); 15 | } 16 | private static boolean dfs(ArrayList> graph,int s,boolean[] visited,int parent){ 17 | visited[s] = true; 18 | for (int v: graph.get(s)){ 19 | if (!visited[v]){ 20 | if (dfs(graph,v,visited,s)){ 21 | return true; 22 | } 23 | }else if (v!=parent){ 24 | return true; 25 | } 26 | } 27 | return false; 28 | } 29 | private static void detectCycle(ArrayList> graph,int v){ 30 | /* Modified DFS */ 31 | boolean[] visited = new boolean[v]; 32 | boolean isCycle = false; 33 | for (int i = 0; i < v; i++) { 34 | if (!visited[i]){ 35 | if (dfs(graph,i,visited,-1)){ 36 | System.out.println("Cycle Present"); 37 | isCycle = true; 38 | break; 39 | } 40 | } 41 | } 42 | if (!isCycle){ 43 | System.out.println("No cycle present"); 44 | } 45 | } 46 | public static void main(String[] args) { 47 | ArrayList> graph = new ArrayList<>(); 48 | for (int i = 0; i < 4; i++) { 49 | graph.add(new LinkedList<>()); 50 | } 51 | addEdge(graph,0,1); 52 | addEdge(graph,1,2); 53 | addEdge(graph,2,3); 54 | addEdge(graph,0,2); 55 | detectCycle(graph,4); 56 | } 57 | } -------------------------------------------------------------------------------- /Graph/FindPathExists.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * @author Vishal Singh 9 | * 06-03-2021 10 | */ 11 | public class FindPathExists { 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().trim()); 15 | while (T-- > 0) { 16 | int n = Integer.parseInt(br.readLine().trim()); 17 | int[][] grid = new int[n][n]; 18 | for (int i = 0; i < n; i++) { 19 | String[] S = br.readLine().trim().split(" "); 20 | for (int j = 0; j < n; j++) { 21 | grid[i][j] = Integer.parseInt(S[j]); 22 | } 23 | } 24 | Solution obj = new Solution(); 25 | boolean ans = obj.is_Possible(grid); 26 | if (ans) 27 | System.out.println("1"); 28 | else 29 | System.out.println("0"); 30 | } 31 | } 32 | 33 | static class Solution { 34 | public boolean dfs(int[][] grid,int i ,int j,int n){ 35 | if (i<0 || i==n || j<0 || j ==n || grid[i][j]==0){ 36 | return false; 37 | } 38 | if (grid[i][j] == 2){ 39 | return true; 40 | } 41 | 42 | grid[i][j] = 0; 43 | return dfs(grid,i-1,j,n) || 44 | dfs(grid,i,j+1,n) || 45 | dfs(grid,i,j-1,n) || 46 | dfs(grid,i+1,j,n); 47 | } 48 | public boolean is_Possible(int[][] grid) { 49 | int i,j=0; 50 | label1: for (i = 0; i < grid.length; i++) { 51 | for (j = 0; j < grid.length; j++) { 52 | if (grid[i][j] == 1){ 53 | break label1; 54 | } 55 | } 56 | } 57 | return dfs(grid, i, j, grid.length); 58 | } 59 | } 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /Graph/NumberIsland.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * @author Vishal Singh 9 | * 05-03-2021 10 | */ 11 | public class NumberIsland { 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().trim()); 15 | while (T-- > 0) { 16 | String[] s = br.readLine().trim().split(" "); 17 | int n = Integer.parseInt(s[0]); 18 | int m = Integer.parseInt(s[1]); 19 | char[][] grid = new char[n][m]; 20 | for (int i = 0; i < n; i++) { 21 | String[] S = br.readLine().trim().split(" "); 22 | for (int j = 0; j < m; j++) { 23 | grid[i][j] = S[j].charAt(0); 24 | } 25 | } 26 | Solution obj = new Solution(); 27 | int ans = obj.numIslands(grid); 28 | System.out.println(ans); 29 | } 30 | } 31 | } 32 | 33 | class Solution { 34 | public void dfs(char[][] grid, int i, int j,int n,int m){ 35 | if (i<0 || i==n || j<0 || j==m || grid[i][j] != '1'){ 36 | return; 37 | } 38 | grid[i][j] = '2'; 39 | dfs(grid,i-1,j,n,m);//U 40 | dfs(grid,i-1,j+1,n,m);//UR 41 | dfs(grid,i-1,j-1,n,m);//UL 42 | 43 | dfs(grid,i,j+1,n,m);//R 44 | 45 | dfs(grid,i+1,j+1,n,m);//BR 46 | dfs(grid,i+1,j,n,m);//B 47 | dfs(grid,i+1,j-1,n,m);//BL 48 | 49 | dfs(grid,i,j-1,n,m);//L 50 | } 51 | 52 | public int numIslands(char[][] grid) { 53 | int n = grid.length; 54 | int ans = 0; 55 | for (int i = 0; i < n; i++) { 56 | int m = grid[i].length; 57 | for (int j = 0; j < m; j++) { 58 | if (grid[i][j] == '1') { 59 | ans++; 60 | dfs(grid, i, j,n,m); 61 | } 62 | } 63 | } 64 | return ans; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Graph/PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 09-02-2021 8 | */ 9 | public class PrimsAlgorithm { 10 | /** 11 | * @param graph adjacency matrix representation of graph 12 | * @param v number of vertices 13 | * Prints the length of Minimum Spanning Tree 14 | * MST -> Minimum Spanning Tree 15 | */ 16 | public static void primsAlgorithm(int[][] graph,int v) { 17 | /* 18 | * It stores the min weighted edge 19 | * Uses vertex/nodes as indexes of the array 20 | * */ 21 | int[] key = new int[v]; 22 | Arrays.fill(key,Integer.MAX_VALUE); 23 | key[0] = 0; 24 | /* 25 | * Length of the MST*/ 26 | int minLength = key[0]; 27 | /* 28 | * It stores the nodes/vertices already visited in the minimum spanning tree*/ 29 | boolean[] mset = new boolean[v]; 30 | for (int i = 0; i < v; i++) { 31 | /* 32 | * The current node you are at*/ 33 | int u = -1; 34 | /* 35 | * Find the smaller node to move to*/ 36 | for (int j = 0; j < v; j++) { 37 | /* 38 | * If mSet does not has the current element*/ 39 | if (!mset[j]){ 40 | if (u == -1 || key[j] < key[u]){ 41 | u = i; 42 | } 43 | } 44 | } 45 | mset[u] = true; 46 | minLength += key[u]; 47 | for (int j = 0; j < v; j++) { 48 | /* 49 | * If mSet does not has the current element 50 | * And graph is connected*/ 51 | if (!mset[j] && graph[u][j]!=0){ 52 | key[j] = Math.min(graph[u][j],key[j]); 53 | } 54 | } 55 | } 56 | System.out.println("PrimsAlgorithm.MST length = "+minLength); 57 | } 58 | public static void main(String[] args) { 59 | int[][] graph = { 60 | {0,5,8,0}, 61 | {5,0,10,15}, 62 | {8,10,0,20}, 63 | {0,15,20,0}, 64 | }; 65 | primsAlgorithm(graph,graph.length); 66 | } 67 | } -------------------------------------------------------------------------------- /Graph/ShortestPathUnweightedGraph.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | /** 9 | * @author Vishal Singh 10 | * 23-01-2021 11 | */ 12 | 13 | public class ShortestPathUnweightedGraph { 14 | static void addEdge(ArrayList> adj,int u,int v){ 15 | adj.get(u).add(v); 16 | adj.get(v).add(u); 17 | } 18 | static void shortestPath(ArrayList> adj,int source,int vertex){ 19 | boolean[] visited = new boolean[vertex]; 20 | int[] dist = new int[vertex]; 21 | Queue queue = new LinkedList<>(); 22 | queue.add(source); 23 | visited[source] = true; 24 | dist[source] = 0; 25 | while (!queue.isEmpty()){ 26 | int v = queue.poll(); 27 | for (int u : adj.get(v)) { 28 | if (!visited[u]) { 29 | queue.add(u); 30 | visited[u] =true; 31 | dist[u] = dist[v]+1; 32 | } 33 | } 34 | } 35 | System.out.println(Arrays.toString(dist)); 36 | } 37 | public static void main(String[] args) { 38 | ArrayList> adj = new ArrayList<>(); 39 | int v = 4; 40 | for (int i = 0; i < 4; i++) { 41 | adj.add(new ArrayList<>()); 42 | } 43 | addEdge(adj,0,1); 44 | addEdge(adj,1,2); 45 | addEdge(adj,2,3); 46 | addEdge(adj,0,2); 47 | addEdge(adj,1,3); 48 | shortestPath(adj,0,v); 49 | } 50 | } -------------------------------------------------------------------------------- /Graph/TopologicalSortDFS.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Graph; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Stack; 5 | 6 | /** 7 | * @author Vishal Singh 8 | * 07-02-2021 9 | */ 10 | public class TopologicalSortDFS { 11 | public static void addEdge(ArrayList> graph,int s,int d){ 12 | graph.get(s).add(d); 13 | } 14 | public static void topologicalSort(ArrayList> graph, int v){ 15 | boolean[] visited = new boolean[v]; 16 | Stack stack = new Stack<>(); 17 | for (int i = 0; i < v; i++) { 18 | if (!visited[i]){ 19 | dfs(graph,visited,stack,i); 20 | } 21 | } 22 | while (!stack.isEmpty()){ 23 | System.out.print(stack.pop()+" "); 24 | } 25 | System.out.println(); 26 | } 27 | public static void dfs(ArrayList> graph,boolean[] visited,Stack stack,int source){ 28 | visited[source] = true; 29 | for (int d: graph.get(source)){ 30 | if (!visited[d]){ 31 | dfs(graph,visited,stack,d); 32 | } 33 | } 34 | stack.push(source); 35 | } 36 | public static void main(String[] args){ 37 | ArrayList> graph = new ArrayList<>(); 38 | int v = 5; 39 | for (int i = 0; i < v; i++) { 40 | graph.add(new ArrayList<>()); 41 | } 42 | addEdge(graph,0,1); 43 | addEdge(graph,1,3); 44 | addEdge(graph,3,4); 45 | addEdge(graph,2,3); 46 | addEdge(graph,2,4); 47 | topologicalSort(graph,v); 48 | } 49 | } -------------------------------------------------------------------------------- /Hashing/CheckTwoArraysEqual.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.HashMap; 7 | 8 | /** 9 | * @author Vishal Singh 10 | */ 11 | public class CheckTwoArraysEqual { 12 | static int checkTwoArraysEqual(long[] a,long b[],int n){ 13 | HashMap setA = new HashMap<>(); 14 | HashMap setB = new HashMap<>(); 15 | for (int i = 0; i < n; i++) { 16 | if (setA.containsKey(a[i])){ 17 | setA.put(a[i],setA.get(a[i])+1); 18 | }else { 19 | setA.put(a[i],1l); 20 | } 21 | if (setB.containsKey(b[i])){ 22 | setB.put(b[i],setB.get(b[i])+1); 23 | }else { 24 | setB.put(b[i],1l); 25 | } 26 | } 27 | return setA.equals(setB) ? 1:0; 28 | } 29 | public static void main(String[] args)throws IOException { 30 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 31 | int testCase = Integer.parseInt(br.readLine()); 32 | while (testCase-->0){ 33 | int n1 = Integer.parseInt(br.readLine()); 34 | String[] curr1 = br.readLine().split(" "); 35 | String[] curr2 = br.readLine().split(" "); 36 | long[] arr1 = new long[n1]; 37 | long[] arr2 = new long[n1]; 38 | for (int i = 0; i < n1; i++) { 39 | arr1[i] = Long.parseLong(curr1[i]); 40 | arr2[i] = Long.parseLong(curr2[i]); 41 | } 42 | System.out.println(checkTwoArraysEqual(arr1,arr2,n1)); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Hashing/CountDistinctElementInEveryWindow.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class CountDistinctElementInEveryWindow { 9 | static void countDistinctElementInEveryWindow(int[] arr,int n,int k){ 10 | int totalWindow = n-k+1; 11 | HashMap hashMap = new HashMap<>(); 12 | for (int i = 0; i < k; i++) { 13 | if (hashMap.containsKey(arr[i])){ 14 | hashMap.put(arr[i],hashMap.get(arr[i])+1); 15 | } 16 | else 17 | hashMap.put(arr[i],1); 18 | } 19 | System.out.print(hashMap.size()+" "); 20 | for (int i = k; i < n; i++) { 21 | if (hashMap.get(arr[i-k]) == 0){ 22 | hashMap.remove(arr[i-k]); 23 | } 24 | else 25 | hashMap.put(arr[i-k],hashMap.get(arr[i-k])-1); 26 | 27 | if (hashMap.containsKey(arr[i])){ 28 | hashMap.put(arr[i],hashMap.get(arr[i])+1); 29 | } 30 | else { 31 | hashMap.put(arr[i],1); 32 | } 33 | System.out.print(hashMap.size()+" "); 34 | } 35 | 36 | } 37 | public static void main(String[] args) { 38 | int[] arr = {10,20,20,10,30,40,10}; 39 | int k = 4; 40 | countDistinctElementInEveryWindow(arr,arr.length,k); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Hashing/CountDistinctElements.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * @author Vishal Singh */ 7 | public class CountDistinctElements { 8 | static int countDistinctElements(int[] arr,int n){ 9 | HashSet hashSet = new HashSet<>(); 10 | for (int i = 0; i < n; i++) { 11 | hashSet.add(arr[i]); 12 | } 13 | return hashSet.size(); 14 | } 15 | public static void main(String[] args) { 16 | int[] arr = {15,12,13,12,13,13,18,12}; 17 | System.out.println(countDistinctElements(arr,arr.length)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Hashing/CountNonRepeatedElements.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class CountNonRepeatedElements { 9 | static long countNonRepeated(int arr[], int n) { 10 | HashMap map = new HashMap<>(); 11 | for (int i = 0; i < n; i++) { 12 | if (map.containsKey(arr[i])){ 13 | map.put(arr[i],map.get(arr[i])+1); 14 | } 15 | else { 16 | map.put(arr[i],1); 17 | } 18 | } 19 | long counter = 0; 20 | for (int i = 0; i < n; i++) { 21 | if (!(map.get(arr[i])>1)){ 22 | counter++; 23 | } 24 | } 25 | return counter; 26 | } 27 | public static void main(String[] args) { 28 | int[] arr = {9,1,9,1,9,1,0}; 29 | System.out.println(countNonRepeated(arr,arr.length)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Hashing/FirstRepeatingElement.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.LinkedHashMap; 7 | 8 | /** 9 | * @author Vishal Singh 10 | */ 11 | public class FirstRepeatingElement { 12 | static int firstRepeatingElement(int[] arr,int n){ 13 | LinkedHashMap map= new LinkedHashMap<>(); 14 | for (int i = 0; i 1)){ 24 | return (i+1); 25 | } 26 | } 27 | return -1; 28 | } 29 | public static void main(String[] args)throws IOException { 30 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 31 | int testCase = Integer.parseInt(br.readLine()); 32 | while (testCase-->0){ 33 | int n = Integer.parseInt(br.readLine()); 34 | String[] curr = br.readLine().split(" "); 35 | int[] arr = new int[n]; 36 | for (int i = 0; i < n; i++) { 37 | arr[i] = Integer.parseInt(curr[i]); 38 | } 39 | System.out.println(firstRepeatingElement(arr,arr.length)); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Hashing/InsertionOfArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * @author Vishal Singh */ 7 | public class InsertionOfArray { 8 | static int intersectionArray(int[] a,int[] b,int aSize,int bSize){ 9 | HashSet set = new HashSet<>(); 10 | for (int i = 0; i < aSize; i++) { 11 | set.add(a[i]); 12 | } 13 | int res = 0; 14 | for (int i = 0; i < bSize; i++) { 15 | if (set.contains(b[i])){ 16 | res++; 17 | set.remove(b[i]); 18 | } 19 | } 20 | return res; 21 | } 22 | public static void main(String[] args) { 23 | int[] a = {10,15,20,15,30,30,5}; 24 | int[] b = {30,5,30,80}; 25 | System.out.println("Intersection array has - "+intersectionArray(a,b,a.length,b.length)+" elements"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Hashing/Itinerary-from-a-given-list-of-tickets.java: -------------------------------------------------------------------------------- 1 | /* 2 | Question -: 3 | 4 | Find Itinerary from a given list of tickets 5 | 6 | Given a list of tickets, find itinerary in order using the given list. 7 | 8 | Input: 9 | "Chennai" -> "Banglore" 10 | "Bombay" -> "Delhi" 11 | "Goa" -> "Chennai" 12 | "Delhi" -> "Goa" 13 | 14 | Output: 15 | Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore, 16 | 17 | */ 18 | 19 | package com.company.JavaDaily; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | public class ticketProblem { 25 | public static void ticket() { 26 | HashMap data = new HashMap(); 27 | data.put("CHE", "BAN"); 28 | data.put("BOM", "DEL"); 29 | data.put("GOA", "CHE"); 30 | data.put("DEL", "GOA"); 31 | HashMap reverseData = new HashMap(); 32 | data.forEach((h, k) -> { 33 | reverseData.put(k, h); 34 | }); 35 | String start = null; 36 | for (Map.Entry e : data.entrySet()) { 37 | if (!reverseData.containsKey(e.getKey())) { 38 | start = e.getKey(); 39 | } 40 | } 41 | String to = data.get(start); 42 | for(Map.Entry e: data.entrySet()){ 43 | while (to!=null){ 44 | System.out.print(start+ " -> "+to+" ,"); 45 | start = to; 46 | to = data.get(start); 47 | } 48 | } 49 | 50 | } 51 | 52 | public static void main(String[] args) { 53 | ticket(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Hashing/LongestCommonSpanTwoBinaryArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class LongestCommonSpanTwoBinaryArray { 9 | static int longestSubArrayWithGivenSum(int[] arr,int n,int sum){ 10 | HashMap map = new HashMap<>(); 11 | int preSum =0; 12 | int max = 0; 13 | for (int i = 0; i < n; i++) { 14 | preSum += arr[i]; 15 | if (preSum == sum){ 16 | return i+1; 17 | } 18 | if (!map.containsKey(preSum)){ 19 | map.put(preSum,i); 20 | } 21 | if (map.containsKey(preSum-sum)){ 22 | max = Math.max(max,i-map.get(preSum-sum)); 23 | } 24 | } 25 | return max; 26 | } 27 | static int longestCommonSpanTwoBinaryArray(int[] arr1,int[] arr2,int m,int n){ 28 | int[] temp = new int[m]; 29 | for (int i = 0; i < m; i++) { 30 | temp[i] = arr1[i] - arr2[i]; 31 | } 32 | return longestSubArrayWithGivenSum(temp,temp.length,0); 33 | } 34 | public static void main(String[] args) { 35 | int[] arr1 = {0,1,0,1,1,1,1}; 36 | int[] arr2 = {1,1,1,1,1,0,1}; 37 | System.out.println(longestCommonSpanTwoBinaryArray(arr1,arr2,arr1.length,arr2.length)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Hashing/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class LongestCommonSubsequence { 9 | static int longestCommonSubsequence(int[] arr, int n){ 10 | HashSet hashSet = new HashSet<>(); 11 | for (int i = 0; i < n; i++) { 12 | hashSet.add(arr[i]); 13 | } 14 | int res = 0; 15 | for (int i = 0; i < n; i++) { 16 | int curr = 0; 17 | if (hashSet.contains(arr[i]-1)){ 18 | curr = 1; 19 | } 20 | while (hashSet.contains(arr[i]+curr)){ 21 | curr++; 22 | } 23 | res = Math.max(res,curr); 24 | } 25 | return res; 26 | } 27 | public static void main(String[] args) { 28 | int[] arr = {3,8,4,5,7}; 29 | System.out.println(longestCommonSubsequence(arr,arr.length)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Hashing/LongestSubArrayWithGivenSum.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * @author Vishal Singh */ 7 | public class LongestSubArrayWithGivenSum { 8 | static int longestSubArrayWithGivenSum(int[] arr,int n,int sum){ 9 | HashMap map = new HashMap<>(); 10 | int preSum =0; 11 | int max = 0; 12 | for (int i = 0; i < n; i++) { 13 | preSum += arr[i]; 14 | if (preSum == sum){ 15 | return i+1; 16 | } 17 | if (!map.containsKey(preSum)){ 18 | map.put(preSum,i); 19 | } 20 | if (map.containsKey(preSum-sum)){ 21 | max = Math.max(max,i-map.get(preSum-sum)); 22 | } 23 | } 24 | return max; 25 | } 26 | public static void main(String[] args) { 27 | int[] arr = {5,8,-4,-4,9,-2,2}; 28 | int sum = 0; 29 | System.out.println("Longest Sub array with sum 0 is of size: "+longestSubArrayWithGivenSum(arr,arr.length,sum)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Hashing/P_HashMap.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * @author Vishal Singh */ 7 | public class P_HashMap { 8 | public static void main(String[] args) { 9 | HashMap m = new HashMap<>(); 10 | m.put("First",1); 11 | m.put("Second",2); 12 | m.put("Third",3); 13 | System.out.println(m); 14 | System.out.println("Size: "+m.size()); 15 | System.out.println(m.containsKey("First")); 16 | System.out.println(m.remove("First")); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Hashing/P_HashSet.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashSet; 4 | import java.util.Iterator; 5 | 6 | /** 7 | * @author Vishal Singh */ 8 | public class P_HashSet { 9 | public static void main(String[] args) { 10 | HashSet h = new HashSet(); 11 | h.add("Hello"); 12 | h.add("I am"); 13 | h.add("Hashing"); 14 | System.out.println(h); 15 | System.out.println(h.contains("Hello")); 16 | 17 | Iterator i = h.iterator(); 18 | while (i.hasNext()){ 19 | System.out.print(i.next()+" "); 20 | } 21 | h.remove("I am"); 22 | System.out.println("\nSize: "+h.size()); 23 | for (String s: 24 | h) { 25 | System.out.println(s); 26 | } 27 | System.out.println("Is empty: "+h.isEmpty()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Hashing/PairWithSumX.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashSet; 4 | 5 | public class PairWithSumX { 6 | static boolean pairSum(int[] arr,int n, int x){ 7 | HashSet set = new HashSet<>(); 8 | for (int i = 0; i < n; i++) { 9 | if (set.contains(x-arr[i])){ 10 | return true; 11 | } 12 | set.add(arr[i]); 13 | } 14 | return false; 15 | } 16 | public static void main(String[] args) { 17 | int[] arr = {3,2,8,15,-2,8}; 18 | int sum = 17; 19 | System.out.println("Pair with sum "+sum+" "+pairSum(arr,arr.length,sum)); 20 | arr = new int[]{11,5,6}; 21 | sum = 10; 22 | System.out.println("Pair with sum "+sum+" "+pairSum(arr,arr.length,sum)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Hashing/PrintNonRepeatedElements.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedHashMap; 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | public class PrintNonRepeatedElements { 10 | static ArrayList printNonRepeated(int arr[], int n) { 11 | LinkedHashMap map = new LinkedHashMap<>(); 12 | for (int i = 0; i < n; i++) { 13 | if (map.containsKey(arr[i])){ 14 | map.put(arr[i],map.get(arr[i])+1); 15 | } 16 | else { 17 | map.put(arr[i],1); 18 | } 19 | } 20 | ArrayList arrayList = new ArrayList<>(); 21 | for (int i = 0; i < n; i++) { 22 | if (!(map.get(arr[i])>1)){ 23 | arrayList.add(arr[i]); 24 | } 25 | } 26 | return arrayList; 27 | } 28 | public static void main(String[] args) { 29 | int[] arr = {9,1,9,1,9,1,0}; 30 | System.out.println(printNonRepeated(arr,arr.length)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Hashing/SeparateChaining.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | import java.io.BufferedReader; 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.InputStreamReader; 6 | import java.util.ArrayList; 7 | /** 8 | * @author Vishal Singh 9 | */ 10 | public class SeparateChaining { 11 | static ArrayList> separateChaining(int arr[], int n, int hashSize) 12 | { 13 | ArrayList> hashTable = new ArrayList<>(); 14 | for (int i = 0; i < hashSize; i++) { 15 | hashTable.add(new ArrayList<>()); 16 | } 17 | for (int i = 0; i < n; i++) { 18 | int hashPos = arr[i]%hashSize; 19 | hashTable.get(hashPos).add(arr[i]); 20 | } 21 | return hashTable; 22 | } 23 | public static void main(String[] args)throws IOException { 24 | InputStream in = System.in; 25 | BufferedReader br = new BufferedReader(new InputStreamReader(in)); 26 | int testCases = Integer.parseInt(br.readLine()); 27 | while (testCases-->0){ 28 | int hashSize = Integer.parseInt(br.readLine()); 29 | int arraySize = Integer.parseInt(br.readLine()); 30 | String[] strArr = br.readLine().split(" "); 31 | int[] arr = new int[arraySize]; 32 | for (int i = 0; i < arraySize; i++) { 33 | arr[i] = Integer.parseInt(strArr[i]); 34 | } 35 | System.out.println(""); 36 | ArrayList> arrayLists = separateChaining(arr,arraySize,hashSize); 37 | for (int i = 0; i < arrayLists.size(); i++) { 38 | if (arrayLists.get(i).size() != 0) 39 | System.out.println(i+"->"+arrayLists.get(i)); 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Hashing/SubArrayWithGivenSum.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | 6 | public class SubArrayWithGivenSum { 7 | static boolean subArrayWithGivenSum(int[] arr,int n,int sum){ 8 | HashSet set = new HashSet<>(); 9 | int preSum =0; 10 | for (int i = 0; i < n; i++) { 11 | preSum += arr[i]; 12 | if (set.contains(preSum-sum)){ 13 | return true; 14 | } 15 | if (set.contains(preSum)){ 16 | return true; 17 | } 18 | set.add(preSum); 19 | } 20 | return false; 21 | } 22 | public static void main(String[] args) { 23 | int[] arr = {5,8,6,13,3,-1}; 24 | int sum = 22; 25 | System.out.println("Sub array with sum"+sum+" in array: "+ Arrays.toString(arr)+" = "+subArrayWithGivenSum(arr,arr.length,sum)); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Hashing/SubArrayWithZeroSum.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | 6 | /** 7 | * @author Vishal Singh */ 8 | public class SubArrayWithZeroSum { 9 | static boolean subArrayWithZeroSum(int[] arr,int n){ 10 | HashSet set = new HashSet<>(); 11 | int prefixSum = 0; 12 | for (int i = 0; i < n; i++) { 13 | prefixSum += arr[i]; 14 | if (set.contains(prefixSum)){ 15 | return true; 16 | } 17 | if (prefixSum == 0){ 18 | return true; 19 | } 20 | set.add(prefixSum); 21 | } 22 | return false; 23 | } 24 | public static void main(String[] args) { 25 | int[] arr = {1,4,-3,1,2}; 26 | System.out.println("Sub array with sum 0 in array: "+ Arrays.toString(arr)+" = "+subArrayWithZeroSum(arr,arr.length)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Hashing/UnionOfArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * Return distinct union size of the arrays*/ 8 | public class UnionOfArray { 9 | static int union(int[] a,int[] b,int aSize,int bSize){ 10 | HashSet set = new HashSet<>(); 11 | for (int i = 0; i < aSize; i++) { 12 | set.add(a[i]); 13 | } 14 | for (int i = 0; i < bSize; i++) { 15 | set.add(b[i]); 16 | } 17 | return set.size(); 18 | } 19 | public static void main(String[] args) { 20 | int[] a = {15,20,5,15}; 21 | int[] b = {15,15,15,20,10}; 22 | System.out.println("Distinct Size of Union of array is: "+union(a,b,a.length,b.length)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Hashing/WinnerElection.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Hashing; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | public class WinnerElection { 10 | static void electionWinner(String[] arr,int n){ 11 | HashMap map = new HashMap<>(); 12 | for (int i = 0; i < n; i++) { 13 | if (map.containsKey(arr[i])){ 14 | map.put(arr[i],map.get(arr[i])+1); 15 | } 16 | else { 17 | map.put(arr[i],1); 18 | } 19 | } 20 | int maxValueInMap = 0; 21 | String winner = ""; 22 | for (Map.Entry entry : map.entrySet()) 23 | { 24 | String key = entry.getKey(); 25 | Integer val = entry.getValue(); 26 | if (val > maxValueInMap) 27 | { 28 | maxValueInMap = val; 29 | winner = key; 30 | } 31 | else if (val == maxValueInMap && 32 | winner.compareTo(key) > 0) 33 | winner = key; 34 | } 35 | System.out.println(winner+" "+maxValueInMap); 36 | } 37 | public static void main(String[] args) { 38 | String[] names = {"john", "johnny", "jackie", "johnny", "john", 39 | "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", 40 | "john"}; 41 | electionWinner(names,names.length); 42 | 43 | names = new String[]{"john", "mike", "harry", "harry", "harry"}; 44 | electionWinner(names,names.length); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Heap/HeapSort.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.Arrays; 4 | 5 | class MinHeap { 6 | private int[] arr; 7 | private int capacity; 8 | private int size; 9 | 10 | MinHeap(int capacity) { 11 | this.capacity = capacity; 12 | } 13 | 14 | private int left(int i) { 15 | return 2 * i + 1; 16 | } 17 | 18 | private int right(int i) { 19 | return 2 * i + 2; 20 | } 21 | 22 | private int parent(int i) { 23 | return (i - 1) / 2; 24 | } 25 | 26 | public void buildHeap(int[] arr,int n) { 27 | for (int i = (n/2)-1; i >=0 ; i--) { 28 | heapify(arr,n,i); 29 | } 30 | } 31 | 32 | public void heapify(int[] arr,int n, int i){ 33 | int left = left(i); 34 | int right = right(i); 35 | int smallest = i; 36 | if (left < n && arr[left] < arr[i] ){ 37 | smallest=left; 38 | } 39 | if (right < n && arr[right] < arr[smallest]){ 40 | smallest = right; 41 | } 42 | if (smallest!=i){ 43 | int temp = arr[i]; 44 | arr[i] = arr[smallest]; 45 | arr[smallest] = temp; 46 | heapify(arr,n,smallest); 47 | } 48 | } 49 | 50 | public void sort(int[] arr) { 51 | int n = arr.length; 52 | buildHeap(arr,n); 53 | for (int i = n-1; i > 0; i--) { 54 | int temp = arr[0]; 55 | arr[0] = arr[i]; 56 | arr[i] = temp; 57 | heapify(arr,i,0); 58 | } 59 | } 60 | 61 | 62 | public int getSize() { 63 | return size; 64 | } 65 | } 66 | 67 | public class HeapSort { 68 | public static void main(String[] args) { 69 | MinHeap minHeap = new MinHeap(6); 70 | int[] arr = {3,1,2,11,0,2,33}; 71 | System.out.println(Arrays.toString(arr)); 72 | long start = System.nanoTime(); 73 | minHeap.sort(arr); 74 | long end = System.nanoTime(); 75 | System.out.println("Heap sort"); 76 | System.out.println((end-start)/100000.0+"ms"); 77 | System.out.println(Arrays.toString(arr)); 78 | } 79 | } -------------------------------------------------------------------------------- /Heap/KClosestElement.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author Vishal Singh 8 | * 16-01-2021 9 | */ 10 | 11 | public class KClosestElement { 12 | static class Pair { 13 | int elem; 14 | int diff; 15 | 16 | Pair(int elem, int diff) { 17 | this.elem = elem; 18 | this.diff = diff; 19 | } 20 | } 21 | 22 | static class SortByDiff implements Comparator { 23 | public int compare(Pair a, Pair b) { 24 | return b.diff - a.diff; 25 | } 26 | } 27 | 28 | public static void getKClosestElement(int[] arr, int n, int k, int x) { 29 | PriorityQueue pq = new PriorityQueue<>(new SortByDiff()); 30 | /* 31 | * I will do it today but in morning 32 | * */ 33 | for (int i = 0; i < k; i++) { 34 | pq.add(new Pair( 35 | arr[i], 36 | Math.abs(arr[i] - x) 37 | )); 38 | } 39 | for (int i = k; i < n; i++) { 40 | Pair curr = pq.peek(); 41 | if (curr != null && curr.diff > Math.abs(arr[i] - x)) { 42 | pq.poll(); 43 | pq.add(new Pair(arr[i], Math.abs(arr[i] - x))); 44 | } 45 | } 46 | System.out.print("K closest elements are: "); 47 | for (Pair p : pq) { 48 | System.out.print(" { "+p.elem + " } "); 49 | } 50 | System.out.println(); 51 | } 52 | 53 | public static void main(String[] args) { 54 | int[] arr = {10, 15, 7, 3, 4}; 55 | int k = 3; 56 | int closestTo = 8; 57 | getKClosestElement(arr, arr.length, k, closestTo); 58 | } 59 | } -------------------------------------------------------------------------------- /Heap/KthLargestInAStream.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 17-01-2021 8 | */ 9 | 10 | public class KthLargestInAStream { 11 | public static int kth(int[] arr, int n, int k){ 12 | if(n < k){ 13 | return -1; 14 | } 15 | PriorityQueue pq = new PriorityQueue<>(); 16 | for(int i = 0; i < k;i++){ 17 | pq.add(arr[i]); 18 | } 19 | for(int i = k; i < n;i++){ 20 | if(pq.peek()!=null && pq.peek() < arr[i]){ 21 | pq.poll(); 22 | pq.add(arr[i]); 23 | } 24 | } 25 | return pq.poll(); 26 | } 27 | public static void kthLargest(int arr[], int n, int k){ 28 | for(int i = 0; i < n; i++){ 29 | System.out.print(kth(arr,i+1,k)+" "); 30 | } 31 | System.out.println(); 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] arr = {857, 744, 492, 228, 366, 860, 937, 433, 552, 438, 229, 276, 408, 475, 122}; 36 | int k = 3; 37 | kthLargest(arr,arr.length,k); 38 | } 39 | } -------------------------------------------------------------------------------- /Heap/MedianOfStream.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author Vishal Singh 8 | * 17-01-2021 9 | */ 10 | 11 | public class MedianOfStream { 12 | public static void medianOfStream(int[] arr, int n){ 13 | PriorityQueue greaterHalf = new PriorityQueue<>(); 14 | PriorityQueue smallerHalf = new PriorityQueue<>(Collections.reverseOrder()); 15 | smallerHalf.add(arr[0]); 16 | System.out.println(arr[0]); 17 | for (int i = 1; i < arr.length; i++) { 18 | int temp = arr[i]; 19 | if (smallerHalf.size() > greaterHalf.size()){ 20 | if (smallerHalf.peek() > temp){ 21 | greaterHalf.add(smallerHalf.poll()); 22 | smallerHalf.add(temp); 23 | }else { 24 | greaterHalf.add(temp); 25 | } 26 | if (smallerHalf.peek()!=null && greaterHalf.peek()!=null) 27 | System.out.println((double) (smallerHalf.peek() + greaterHalf.peek()) / 2); 28 | }else { 29 | if (smallerHalf.peek()!=null && temp <= smallerHalf.peek()){ 30 | smallerHalf.add(temp); 31 | }else { 32 | greaterHalf.add(temp); 33 | smallerHalf.add(greaterHalf.poll()); 34 | } 35 | System.out.println(smallerHalf.peek()); 36 | } 37 | } 38 | } 39 | public static void main(String[] args) { 40 | int[] arr = {25, 7, 10, 15, 20}; 41 | medianOfStream(arr,arr.length); 42 | } 43 | } -------------------------------------------------------------------------------- /Heap/PrintKLargestElements.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 16-01-2021 8 | */ 9 | 10 | public class PrintKLargestElements { 11 | public static void getKLargestElements(int[] arr,int n,int k){ 12 | PriorityQueue pq = new PriorityQueue<>(); 13 | for (int i = 0; i < k; i++) { 14 | pq.add(arr[i]); 15 | } 16 | for (int i = k; i < n; i++) { 17 | if(pq.peek() < arr[i]){ 18 | pq.poll(); 19 | pq.add(arr[i]); 20 | } 21 | } 22 | System.out.println("The "+k+" largest elements are: "+pq); 23 | } 24 | public static void main(String[] args){ 25 | int[] arr = {8,6,4,10,9}; 26 | int k = 3; 27 | getKLargestElements(arr,arr.length,k); 28 | } 29 | } -------------------------------------------------------------------------------- /Heap/PriorityQueueDemo.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author Vishal Singh 8 | * 16-01-2021 9 | */ 10 | public class PriorityQueueDemo { 11 | /* 12 | * By defaul it is Min heap*/ 13 | public static void main(String[] args) { 14 | /* 15 | * Min Heap*/ 16 | PriorityQueue pq = new PriorityQueue<>(); 17 | pq.add(10); 18 | pq.add(1010); 19 | pq.add(110); 20 | pq.add(0); 21 | System.out.println(pq); 22 | System.out.println(pq.poll()); 23 | System.out.println(pq.peek()); 24 | /* 25 | * Max Heap*/ 26 | PriorityQueue max = new PriorityQueue<>(Collections.reverseOrder()); 27 | max.add(10); 28 | max.add(100); 29 | max.add(1); 30 | System.out.println(max); 31 | System.out.println(max.poll()); 32 | System.out.println(max.peek()); 33 | } 34 | } -------------------------------------------------------------------------------- /Heap/PurchasingMaxItems.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 16-01-2021 8 | */ 9 | 10 | public class PurchasingMaxItems { 11 | public static void purchaseMaxItems(int[] arr,int sum){ 12 | PriorityQueue pq = new PriorityQueue<>(); 13 | for (int i = 0; i < arr.length; i++) { 14 | pq.add(arr[i]); 15 | } 16 | int ans = 0; 17 | for (int i = 0; i < pq.size(); i++) { 18 | if(pq.peek() <= sum){ 19 | ans++; 20 | sum-=pq.poll(); 21 | }else{ 22 | break; 23 | } 24 | } 25 | System.out.println("You can buy a max of "+ans+" items"); 26 | } 27 | public static void main(String[] args){ 28 | int[] arr = {1,12,5,111,200}; 29 | int sum = 10; 30 | purchaseMaxItems(arr,sum); 31 | } 32 | } -------------------------------------------------------------------------------- /Heap/SortKSortedArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Heap; 2 | 3 | import java.util.Arrays; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author Vishal Singh 8 | * 16-01-2021 9 | */ 10 | 11 | public class SortKSortedArray { 12 | public static void sortKSortedArray(int[] arr, int n, int k) { 13 | PriorityQueue pq = new PriorityQueue<>(); 14 | for (int i = 0; i < k; i++) { 15 | pq.add(arr[i]); 16 | } 17 | int index = 0; 18 | for (int i = k + 1; i < n; i++) { 19 | arr[index++] = pq.poll(); 20 | pq.add(arr[i]); 21 | } 22 | while (!pq.isEmpty()) { 23 | arr[index++] = pq.poll(); 24 | } 25 | System.out.println(Arrays.toString(arr)); 26 | } 27 | 28 | public static void main(String[] args) { 29 | int[] arr = {10, 9, 7, 8, 4, 70, 50, 60}; 30 | int k = 4; 31 | int n = arr.length; 32 | sortKSortedArray(arr, n, k); 33 | } 34 | } -------------------------------------------------------------------------------- /Implementation/BFS.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | 3 | import java.util.Iterator; 4 | import java.util.LinkedList; 5 | /** 6 | * @author Vishal Singh */ 7 | 8 | //Breadth First Search for a graph 9 | public class BFS { 10 | private int noOfVertices; 11 | private LinkedList adj[]; 12 | BFS(int v) { 13 | noOfVertices = v; 14 | adj = new LinkedList[v]; 15 | for (int i = 0; i queue = new LinkedList(); 25 | visited[s] = true; 26 | queue.add(s); 27 | 28 | while (queue.size() != 0) { 29 | s = queue.poll(); 30 | System.out.println(s+" "); 31 | 32 | Iterator i = adj[s].listIterator(); 33 | while (i.hasNext()) { 34 | int n = i.next(); 35 | if(!visited[n]) { 36 | visited[n] = true; 37 | queue.add(n); 38 | } 39 | } 40 | } 41 | } 42 | public static void main(String[] args) { 43 | BFS b = new BFS(4); 44 | b.addEdge(0,1); 45 | b.addEdge(0,2); 46 | 47 | b.addEdge(1,2); 48 | 49 | b.addEdge(2,0); 50 | b.addEdge(2,3); 51 | 52 | b.addEdge(3,3); 53 | 54 | b.bfs(2); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Implementation/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class BinarySearch { 6 | int binSearch(int[] arr, int startIndex, int endIndex, int search) { 7 | 8 | if (endIndex>=startIndex) { 9 | 10 | int mid = (startIndex + endIndex) / 2; 11 | 12 | int mid2 =( startIndex + (endIndex-startIndex) ) / 2; // if the numbers are too high this way it prevents overflow 13 | 14 | if (search == arr[mid]) { 15 | return mid; 16 | } 17 | if (arr[mid] < search) { 18 | return binSearch(arr, mid + 1, endIndex, search); 19 | } 20 | if (arr[mid] > search) { 21 | return binSearch(arr, startIndex, mid - 1, search); 22 | } 23 | } 24 | return -1; 25 | } 26 | void search(int[] arr, int searchItem) { 27 | int foundStatus = binSearch(arr,0,arr.length-1,searchItem); 28 | if (foundStatus != -1) { 29 | System.out.println("Found"); 30 | } 31 | else { 32 | System.out.println("Not Found"); 33 | } 34 | } 35 | void pos(int[] arr, int searchItem) { 36 | int foundPos = binSearch(arr,0,arr.length-1,searchItem); 37 | if (foundPos != -1) { 38 | System.out.println(foundPos+1); 39 | } 40 | else { 41 | System.out.println("Not Found"); 42 | } 43 | } 44 | public static void main(String[] args) { 45 | BinarySearch obj = new BinarySearch(); 46 | int[] arr = { 2, 3, 4, 10, 40 }; 47 | obj.search(arr,2); 48 | obj.search(arr,4); 49 | obj.search(arr,40); 50 | obj.search(arr,400); 51 | 52 | obj.pos(arr,2); 53 | obj.pos(arr,4); 54 | obj.pos(arr,40); 55 | obj.pos(arr,400); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Implementation/DFS.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | 3 | import java.util.Iterator; 4 | import java.util.LinkedList; 5 | /** 6 | * @author Vishal Singh */ 7 | 8 | public class DFS { 9 | private int noOfVertices; 10 | private LinkedList adj[]; 11 | DFS(int v) { 12 | noOfVertices = v; 13 | adj = new LinkedList[v]; 14 | for (int i = 0; i < v ; i++) { 15 | adj[i] = new LinkedList(); 16 | } 17 | } 18 | void addEdge(int v,int w) { 19 | adj[v].add(w); 20 | } 21 | 22 | void DFSUtil(int v,boolean visited[]) { 23 | 24 | visited[v] = true; 25 | System.out.println(v+" "); 26 | 27 | Iterator i = adj[v].listIterator(); 28 | while (i.hasNext()) { 29 | int n =i.next(); 30 | if(!visited[n]) { 31 | DFSUtil(n,visited); 32 | } 33 | } 34 | } 35 | void dfs(int v) { 36 | boolean visited[] = new boolean[noOfVertices]; 37 | DFSUtil(v,visited); 38 | } 39 | public static void main(String[] args) { 40 | DFS d = new DFS(4); 41 | d.addEdge(0, 1); 42 | d.addEdge(0, 2); 43 | d.addEdge(1, 2); 44 | d.addEdge(2, 0); 45 | d.addEdge(2, 3); 46 | d.addEdge(3, 3); 47 | d.dfs(2); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Implementation/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Best performance when size of array is small 7 | * Stable Sorting 8 | * Best Case - Array Sorted - 9 | * Worst Case - Reverse Sorted - O(N^2) 10 | * 11 | * @author Vishal Singh */ 12 | public class InsertionSort { 13 | static void insertionSort(int[] arr,int n){ 14 | for (int i = 1; i < n; i++) { 15 | int key = arr[i]; 16 | int j = i-1; 17 | while (j>=0 && arr[j]>key){ 18 | arr[j+1] = arr[j]; 19 | j--; 20 | } 21 | arr[j+1] = key; 22 | } 23 | } 24 | public static void main(String[] args) { 25 | int[] arr = {50,20,40,10,30,60,80,99}; 26 | insertionSort(arr,arr.length); 27 | System.out.println(Arrays.toString(arr)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Implementation/MergeSort.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Stable Sorting 7 | * O(n log n) 8 | * Takes Extra Aux Space - O(n) 9 | * @author Vishal Singh */ 10 | public class MergeSort { 11 | /** 12 | * This merges the array 13 | * @param arr This is the original array 14 | * @param left This is the starting of index of the sub array 15 | * @param middle This is the mid point of the array 16 | * @param right This is the ending point of the array*/ 17 | static void merge(int[] arr,int left,int middle,int right){ 18 | 19 | int sizeOfArr1 = (middle-left)+1; 20 | int sizeOfArr2 = (right-middle); 21 | int[] arr1 = new int[sizeOfArr1]; 22 | int[] arr2 = new int[sizeOfArr2]; 23 | System.arraycopy(arr,left,arr1,0,sizeOfArr1); 24 | System.arraycopy(arr,middle+1,arr2,0,sizeOfArr2); 25 | 26 | int i = 0; 27 | int j = 0; 28 | int k = left; 29 | while (ileft){ 53 | int mid = left + (right-left)/2; // This avoids overflow 54 | mergeSort(arr,left,mid); 55 | mergeSort(arr,mid+1,right); 56 | merge(arr,left,mid,right); 57 | } 58 | } 59 | public static void main(String[] args) { 60 | int[] arr = {50,20,40,10,30,60,80,99}; 61 | mergeSort(arr,0,arr.length-1); 62 | System.out.println(Arrays.toString(arr)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Implementation/P_LinkedList.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | 3 | import java.util.LinkedList; 4 | /** 5 | * @author Vishal Singh */ 6 | 7 | public class P_LinkedList { 8 | public static void main(String[] args) { 9 | LinkedList li = new LinkedList(); 10 | for (int i = 0; i < 4 ; i++) { 11 | li.add(i+777); 12 | } 13 | for (int i = 0; i < 4; i++) { 14 | System.out.println(li.get(i)); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Implementation/P_Queue.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | /** 5 | * @author Vishal Singh */ 6 | public class P_Queue { 7 | public static void main(String[] args) { 8 | //Queue q = new PriorityQueue(); 9 | Queue l = new LinkedList(); 10 | for (int i = 0; i < 4 ; i++) { 11 | l.add(i+777); 12 | } 13 | System.out.println(l); 14 | for (int i = 0; i < 4; i++) { 15 | System.out.println(l.poll()); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Implementation/P_Stack.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | 3 | import java.util.Stack; 4 | /** 5 | * @author Vishal Singh */ 6 | 7 | public class P_Stack { 8 | public static void main(String[] args) { 9 | Stack s = new Stack(); 10 | for (int i = 0; i < 4 ; i++) { 11 | s.push(i+777); 12 | } 13 | for (int i = 0; i < 4; i++) { 14 | System.out.println(s.pop()); 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Implementation/QuickSort.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Implementation; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class QuickSort { 6 | private int arr[]; 7 | int partition(int low,int high) { 8 | int pivot = arr[high]; 9 | int i = low-1; 10 | for (int j = low; j pq = new PriorityQueue<>((a, b) -> a.data - b.data); 25 | pq.addAll(Arrays.asList(arr)); 26 | Node res = null, curr = null; 27 | while (!pq.isEmpty()) { 28 | Node temp = pq.poll(); 29 | if (res == null) { 30 | res = new Node(temp.data); 31 | curr = res; 32 | } 33 | else { 34 | curr.next = new Node(temp.data); 35 | curr = curr.next; 36 | } 37 | if(temp.next != null) { 38 | pq.add(temp.next); 39 | } 40 | } 41 | return res; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /LinkedList/MiddleOfLinkedList.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.LinkedList; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | class Node1{ 7 | int data; 8 | Node1 next; 9 | Node1(int data){ 10 | this.data = data; 11 | } 12 | } 13 | class List1{ 14 | Node1 head; 15 | /** 16 | * slow references = one node at time 17 | * fast references = two node at time*/ 18 | void insertBegin(int data){ 19 | Node1 temp = new Node1(data); 20 | temp.next = head; 21 | head = temp; 22 | } 23 | void searchMid(Node1 head){ 24 | if (head == null) 25 | return; 26 | Node1 slow = head, fast = head; 27 | while (fast!= null && fast.next != null){ 28 | slow = slow.next; 29 | fast = fast.next.next; 30 | } 31 | System.out.println(slow.data); 32 | } 33 | 34 | } 35 | public class MiddleOfLinkedList { 36 | public static void main(String[] args) { 37 | List1 l = new List1(); 38 | l.insertBegin(4); 39 | l.insertBegin(40); 40 | l.insertBegin(400); 41 | l.insertBegin(500); 42 | l.insertBegin(50); 43 | l.insertBegin(5); 44 | 45 | l.searchMid(l.head); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /LinkedList/NthPointerFromENd.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.LinkedList; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | class Node2{ 7 | int data; 8 | Node2 next; 9 | Node2(int data){ 10 | this.data = data; 11 | } 12 | } 13 | 14 | class List2{ 15 | Node2 head; 16 | void insertBegin(int data){ 17 | Node2 temp = new Node2(data); 18 | temp.next = head; 19 | head = temp; 20 | } 21 | void printList(){ 22 | Node2 curr = head; 23 | while (curr != null){ 24 | System.out.print(curr.data+" "); 25 | curr = curr.next; 26 | } 27 | System.out.println(""); 28 | } 29 | void insertEnd(int data){ 30 | Node2 temp = new Node2(data); 31 | Node2 curr = head; 32 | if (head == null){ 33 | head = temp; 34 | return; 35 | } 36 | while (curr.next != null){ 37 | curr=curr.next; 38 | } 39 | curr.next = temp; 40 | } 41 | } 42 | 43 | public class NthPointerFromENd { 44 | static void printNthNode(Node2 head,int n){ 45 | if (head == null) 46 | return; 47 | Node2 first = head,second = head; 48 | for (int i = 0; i < n; i++) { 49 | if (first == null) 50 | return; 51 | first = first.next; 52 | } 53 | while (first!=null){ 54 | second = second.next; 55 | first = first.next; 56 | } 57 | System.out.println(second.data); 58 | } 59 | public static void main(String[] args) { 60 | List2 list = new List2(); 61 | list.insertEnd(10); 62 | list.insertEnd(20); 63 | list.insertEnd(30); 64 | list.insertEnd(40); 65 | list.insertEnd(50); 66 | list.insertEnd(60); 67 | list.insertEnd(70); 68 | printNthNode(list.head,3); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /LinkedList/RmDuplicateSorted.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.LinkedList; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class RmDuplicateSorted { 7 | static class Node{ 8 | int data; 9 | Node next; 10 | Node(int data){ 11 | this.data = data; 12 | next = null; 13 | } 14 | } 15 | static class List{ 16 | Node head; 17 | Node tail; 18 | void addToTheLast(Node node){ 19 | if(head == null){ 20 | head = node; 21 | tail = node; 22 | } 23 | else{ 24 | tail.next = node; 25 | tail = node; 26 | } 27 | } 28 | void print(){ 29 | Node curr = head; 30 | while(curr != null){ 31 | System.out.print(curr.data+","); 32 | curr = curr.next; 33 | } 34 | System.out.println(""); 35 | } 36 | void removeDuplicates() { 37 | Node curr = head; 38 | while (curr != null && curr.next != null) { 39 | if (curr.data == curr.next.data) { 40 | curr.next = curr.next.next; 41 | } else 42 | curr = curr.next; 43 | } 44 | } 45 | } 46 | public static void main(String[] args) { 47 | List l = new List(); 48 | l.addToTheLast(new Node(2)); 49 | l.addToTheLast(new Node(3)); 50 | l.addToTheLast(new Node(3)); 51 | l.addToTheLast(new Node(4)); 52 | l.addToTheLast(new Node(55)); 53 | l.addToTheLast(new Node(556)); 54 | l.addToTheLast(new Node(556)); 55 | l.print(); 56 | l.removeDuplicates(); 57 | l.print(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /LinkedList/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.LinkedList; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | 7 | class Node{ 8 | int data; 9 | Node next; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | 15 | class List{ 16 | Node head; 17 | void insertBegin(int data){ 18 | Node temp = new Node(data); 19 | temp.next = head; 20 | head = temp; 21 | } 22 | void printList(){ 23 | Node curr = head; 24 | while (curr != null){ 25 | System.out.print(curr.data+" "); 26 | curr = curr.next; 27 | } 28 | System.out.println(""); 29 | } 30 | void insertEnd(int data){ 31 | Node temp = new Node(data); 32 | Node curr = head; 33 | if (head == null){ 34 | head = temp; 35 | return; 36 | } 37 | while (curr.next != null){ 38 | curr=curr.next; 39 | } 40 | curr.next = temp; 41 | } 42 | } 43 | 44 | public class SinglyLinkedList { 45 | public static void main(String[] args) { 46 | List list = new List(); 47 | list.insertBegin(5); 48 | list.insertBegin(15); 49 | list.insertBegin(3); 50 | 51 | list.printList(); 52 | 53 | list.insertEnd(100); 54 | list.insertEnd(105); 55 | list.insertEnd(1); 56 | 57 | list.printList(); 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /LinkedList/SplitAlternatingly.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.LinkedList; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class SplitAlternatingly { 7 | static class Node { 8 | int data; 9 | Node next; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | static class LinkedList{ 15 | Node head; 16 | Node tail; 17 | void insertEnd(int data){ 18 | Node temp = new Node(data); 19 | Node curr = head; 20 | if (head == null){ 21 | head = temp; 22 | tail = temp; 23 | return; 24 | } 25 | while (curr.next != null){ 26 | curr=curr.next; 27 | } 28 | tail = temp; 29 | curr.next = temp; 30 | } 31 | void insertEndArrayOfData(int[] data){ 32 | for (int i = 0; i < data.length; i++) { 33 | insertEnd(data[i]); 34 | } 35 | } 36 | void printList(){ 37 | if (head == null) 38 | return; 39 | Node curr = head; 40 | while (curr != null){ 41 | System.out.print(curr.data+" "); 42 | curr = curr.next; 43 | } 44 | System.out.println(); 45 | } 46 | } 47 | public static Node a; 48 | public static Node b; 49 | static void splitAlternative(Node head){ 50 | LinkedList a = new LinkedList(); 51 | a.head = head; 52 | LinkedList b = new LinkedList(); 53 | 54 | Node curr = head; 55 | while (curr != null && curr.next!= null){ 56 | b.insertEnd(curr.next.data); 57 | curr.next = curr.next.next; 58 | curr = curr.next; 59 | } 60 | a.printList(); 61 | b.printList(); 62 | } 63 | public static void main(String[] args) { 64 | LinkedList l = new LinkedList(); 65 | l.insertEndArrayOfData(new int[]{1,2,3,4,5,6,7}); 66 | splitAlternative(l.head); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Mathematics/LastTermOfGP.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Mathematics; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class LastTermOfGP { 6 | public static void main(String[] args) { 7 | int n1 = 84; 8 | int n2 = 87; 9 | int n = 3; 10 | double r = (double)n2/(double)n1; 11 | System.out.println(n1*Math.pow(r,n-1)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Mathematics/NumberOfDigitsInANumber.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Mathematics; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class NumberOfDigitsInANumber { 6 | public static void main(String[] args) { 7 | long i = 100045224656l; 8 | int numOfDigits = (int) (Math.floor(Math.log10(i))+1); 9 | System.out.println(numOfDigits); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Mathematics/PrimeNumber.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Mathematics; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class PrimeNumber { 6 | static boolean isPrime(int n){ 7 | if (n<=1){ 8 | return false; 9 | } 10 | if (n<=3){ 11 | return true; 12 | } 13 | if (n%2 == 0 || n%3 ==0){ 14 | return false; 15 | } 16 | for (int i = 5; i*i <= n ; i=i+6) { 17 | if (n%i == 0 || n%(i+2) == 0){ 18 | return false; 19 | } 20 | } 21 | return true; 22 | /*if(n<=1){ 23 | return false; 24 | } 25 | if(n<=3){ 26 | return true; 27 | } 28 | if (n%2 == 0 || n%3 ==0){ 29 | return false; 30 | } 31 | int res = 0; 32 | while (Math.sqrt(n)>0){ 33 | res += (n&1); 34 | n = n>>1; 35 | } 36 | if(res == 2 || res == 3){ 37 | return true; 38 | } 39 | return false;*/ 40 | } 41 | public static void main(String[] args) { 42 | for (int i = 0; i < 50 ; i++) { 43 | if (isPrime(i)){ 44 | System.out.println(i+". "+Integer.toBinaryString(i)); 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Matrix/AddMatrix.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Matrix; 2 | /** 3 | * @author Vishal Singh */ 4 | public class AddMatrix { 5 | public static void main(String[] args) { 6 | int[][] arr = { 7 | {1, 2, 3, 4}, 8 | {5, 6, 7, 8}, 9 | }; 10 | int[][] arr1 = { 11 | {9,10,11,12}, 12 | {13,14,15,16}, 13 | }; 14 | for (int i = 0; i < arr.length; i++) { 15 | for (int j = 0; j < arr[i].length; j++) { 16 | System.out.print((arr[i][j]+arr1[i][j])+" "); 17 | } 18 | System.out.println(""); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Matrix/BooleanMatrixProblem.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Matrix; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BooleanMatrixProblem { 6 | public static void main(String[] args) { 7 | int[][] arr ={ 8 | {1 ,0 ,0}, 9 | {1 ,0 ,0}, 10 | {1 ,0 ,0}, 11 | {0 ,0 ,0}, 12 | }; 13 | int r = 4; 14 | int c = 3; 15 | int[] row = new int[r]; 16 | int[] column = new int[c]; 17 | for (int i = 0; i < r; i++) { 18 | for (int j = 0; j < c; j++) { 19 | if (arr[i][j] == 1){ 20 | row[i] = 1; 21 | column[j] = 1; 22 | } 23 | } 24 | } 25 | for (int i = 0; i < r; i++) { 26 | for (int j = 0; j < c; j++) { 27 | if (row[i] == 1 || column[j] == 1){ 28 | arr[i][j] = 1; 29 | } 30 | } 31 | } 32 | System.out.println(Arrays.toString(arr[0])); 33 | System.out.println(Arrays.toString(arr[1])); 34 | System.out.println(Arrays.toString(arr[2])); 35 | System.out.println(Arrays.toString(arr[3])); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Matrix/SearchInMatrix.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Matrix; 2 | /** 3 | * @author Vishal Singh 4 | * Sorted Row Wise 5 | * Sorted Column Wise*/ 6 | public class SearchInMatrix { 7 | static void search(int[][] arr,int m,int n,int elementToSearch){ 8 | int i = 0; 9 | int j = n-1; 10 | while (i < m && j >= 0){ 11 | if (arr[i][j] == elementToSearch){ 12 | System.out.println("Found at: "+(i+1)+" "+(j+1)); 13 | return; 14 | } 15 | else if (arr[i][j] > elementToSearch){ 16 | j--; 17 | } 18 | else { 19 | i++; 20 | } 21 | } 22 | System.out.println("Not Found"); 23 | } 24 | public static void main(String[] args) { 25 | int[][] arr = { 26 | {10,20,30,40}, 27 | {15,25,35,45}, 28 | {27,29,37,48}, 29 | {32,33,39,50} 30 | }; 31 | int elementToSearch = 39; 32 | search(arr,4,4,elementToSearch); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Matrix/SnakePattern.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Matrix; 2 | 3 | 4 | /** 5 | * @author Vishal Singh */ 6 | public class SnakePattern { 7 | static void printSnake(int[][] arr){ 8 | for (int i = 0; i < arr.length; i++) { 9 | if (i%2 == 0){ 10 | for (int j = 0; j < arr[i].length; j++) { 11 | System.out.print(arr[i][j]+" "); 12 | } 13 | } 14 | else { 15 | for (int j = arr[i].length-1; j >= 0; j--) { 16 | System.out.print(arr[i][j]+" "); 17 | } 18 | } 19 | System.out.println(""); 20 | } 21 | } 22 | public static void main(String[] args) { 23 | int[][] arr = { 24 | {1,2,3,4}, 25 | {5,6,7,8}, 26 | {9,10,11,12}, 27 | {13,14,15,16}, 28 | }; 29 | printSnake(arr); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Matrix/SpiralTraversal.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Matrix; 2 | /** 3 | * @author Vishal Singh */ 4 | public class SpiralTraversal { 5 | static void spiralTraversal(int[][] arr,int row,int column){ 6 | int top = 0; 7 | int left = 0; 8 | int right = row-1; 9 | int bottom = column-1; 10 | while (top <= bottom && left <= right){ 11 | for (int i = top; i <=right ; i++) { 12 | System.out.print(arr[top][i]+" "); 13 | } 14 | top++; 15 | for (int i = top; i <=bottom ; i++) { 16 | System.out.print(arr[i][right]+" "); 17 | } 18 | right--; 19 | if (top<=bottom){ 20 | for (int i = right; i >= left; i--) { 21 | System.out.print(arr[bottom][i]+" "); 22 | } 23 | bottom--; 24 | } 25 | if (left<=right){ 26 | for (int i = bottom; i >= top; i--) { 27 | System.out.print(arr[i][left]+" "); 28 | } 29 | left++; 30 | } 31 | } 32 | } 33 | public static void main(String[] args) { 34 | int[][] arr = { 35 | {1,2,3,4}, 36 | {5,6,7,8}, 37 | {9,10,11,12}, 38 | {13,14,15,16}, 39 | }; 40 | spiralTraversal(arr,4,4); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Miscellaneous/FactorialDigits.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Miscellaneous; 2 | 3 | import java.math.BigInteger; 4 | /** 5 | * @author Vishal Singh */ 6 | 7 | public class FactorialDigits { 8 | static BigInteger fact(BigInteger num){ 9 | if (num.compareTo(new BigInteger("0")) == 0){ 10 | return BigInteger.ONE; 11 | } 12 | else if (num.compareTo(new BigInteger("1")) == 0){ 13 | return BigInteger.ONE; 14 | } 15 | else { 16 | return num.multiply(fact(num.subtract(BigInteger.ONE))); 17 | 18 | } 19 | } 20 | public static void main(String[] args) { 21 | BigInteger res = fact(new BigInteger("120")); 22 | System.out.println((int)Math.floor(Math.log10(Double.parseDouble(String.valueOf(res)))+1)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Miscellaneous/NaturalNumbers.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Miscellaneous; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | public class NaturalNumbers { 6 | static int sum(int n){ 7 | if (n==1) 8 | return 1; 9 | return n+sum(n-1); 10 | } 11 | static int formulaSum(int n){ 12 | return (n*(n+1))/2; 13 | } 14 | public static void main(String[] args) { 15 | int n = 3; 16 | System.out.println(sum(n)); 17 | System.out.println(formulaSum(n)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Miscellaneous/QuadraticEquation.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Miscellaneous; 2 | 3 | //User function Template for Java 4 | /** 5 | * @author Vishal Singh */ 6 | 7 | public class QuadraticEquation 8 | { 9 | public static void quadraticRoots(int a,int b,int c) 10 | { 11 | //Your code here 12 | int d = (int) Math.floor(Math.pow(b,2)-(4*a*c)); 13 | if(d < 0){ 14 | System.out.print("Imaginary"); 15 | } 16 | else { 17 | double root2 = (-b + Math.sqrt(d)) / (2 * a); 18 | if(d == 0){ 19 | int r1 = (int) Math.floor(root2); 20 | System.out.print(r1+" "+r1); 21 | } 22 | else{ 23 | int r1 = (int) Math.floor((-b-Math.sqrt(d))/(2*a)); 24 | int r2 = (int) Math.floor(root2); 25 | if(r1>r2){ 26 | System.out.print(r1+" "+r2); 27 | } 28 | else if(r2>r1){ 29 | System.out.print(r2+" "+r1); 30 | } 31 | else{ 32 | System.out.print(r1+" "+r2); 33 | } 34 | } 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | quadraticRoots(1,-2,1); 40 | quadraticRoots(1,-7,12); 41 | quadraticRoots(1,4,8); 42 | quadraticRoots(752,904,164); 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Queue/GenerateNumberGivenDigits.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Queue; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | public class GenerateNumberGivenDigits { 10 | static void printFirstN(int n){ 11 | Queue q = new LinkedList<>(); 12 | /* 13 | * You can enqueu any number here which you want to be in the number printed*/ 14 | q.offer("5"); 15 | q.offer("6"); 16 | for (int i = 0; i < n; i++) { 17 | String curr = q.poll(); 18 | System.out.println(curr); 19 | q.offer(curr+"5"); 20 | q.offer(curr+"6"); 21 | } 22 | } 23 | public static void main(String[] args) { 24 | printFirstN(6); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Queue/QueueAsArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Queue; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class QueueAsArray { 7 | static class Queue{ 8 | int[] arr; 9 | int front, rear; 10 | Queue(int n){ 11 | arr = new int[n]; 12 | } 13 | boolean isEmpty(){ 14 | return (front == rear-1); 15 | } 16 | void enqueue(int data){ 17 | if (!isEmpty()){ 18 | System.out.println("-1"); 19 | }else { 20 | arr[front++] = data; 21 | } 22 | } 23 | } 24 | public static void main(String[] args) { 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Queue/QueueImplementation.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | /** 8 | * @author Vishal Singh 9 | */ 10 | public class QueueImplementation { 11 | public static void main(String[] args) { 12 | 13 | // do not throw exception 14 | Queue q1 = new LinkedList<>(); // 15 | Queue q2 = new ArrayDeque<>(); // prefferred 16 | q1.offer(1); 17 | q1.offer(10); 18 | q1.offer(100); 19 | System.out.println(q1); 20 | q2.offer(11); 21 | q2.offer(111); 22 | System.out.println(q2.peek()); 23 | System.out.println(q2.poll()); 24 | //throw exception 25 | // element add remove 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Queue/ReverseQueue.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Queue; 5 | import java.util.Stack; 6 | 7 | /** 8 | * @author Vishal Singh 9 | */ 10 | public class ReverseQueue { 11 | /* 12 | * Iterative Approach 13 | * Explicitly Using stack 14 | * */ 15 | static void reverse(Queue q){ 16 | Stack s = new Stack<>(); 17 | while (!q.isEmpty()){ 18 | s.push(q.remove()); 19 | } 20 | while (!s.isEmpty()){ 21 | q.offer(s.pop()); 22 | } 23 | } 24 | /* 25 | * Recursice approach 26 | * Functional Stack used internally 27 | * */ 28 | static void reverseRecursive(Queue q){ 29 | if (q.isEmpty()){ 30 | return; 31 | } 32 | int top = q.poll(); 33 | reverseRecursive(q); 34 | q.offer(top); 35 | } 36 | public static void main(String[] args) { 37 | Queue q = new ArrayDeque<>(); 38 | q.offer(3); 39 | q.offer(2); 40 | q.offer(1); 41 | System.out.println(q); 42 | reverse(q); 43 | System.out.println(q); 44 | reverseRecursive(q); 45 | System.out.println(q); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Queue/StackUsingQueue.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Queue; 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | 10 | class Stack{ 11 | Queue q1 = new ArrayDeque<>(); 12 | Queue q2 = new ArrayDeque<>(); 13 | int top(){ 14 | if (q1.isEmpty()){ 15 | return -1; 16 | } 17 | return q1.peek(); 18 | } 19 | int size(){ 20 | return q1.size(); 21 | } 22 | int pop(){ 23 | if (q1.isEmpty()){ 24 | return -1; 25 | } 26 | return q1.poll(); 27 | } 28 | void push(int data){ 29 | while(!q1.isEmpty()){ 30 | q2.offer(q1.peek()); 31 | q1.poll(); 32 | } 33 | q1.offer(data); 34 | while (!q2.isEmpty()){ 35 | q1.offer(q2.peek()); 36 | q2.poll(); 37 | } 38 | } 39 | } 40 | 41 | public class StackUsingQueue { 42 | public static void main(String[] args) { 43 | Stack s = new Stack(); 44 | s.push(1); 45 | s.push(2); 46 | s.push(3); 47 | System.out.println("current size: " + s.size()); 48 | System.out.println(s.top()); 49 | s.pop(); 50 | System.out.println(s.top()); 51 | s.pop(); 52 | System.out.println(s.top()); 53 | 54 | System.out.println("current size: " + s.size()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Recursion/JosephusProblem.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | public class JosephusProblem { 5 | static int kill(int n, int k){ 6 | if (n == 1){ 7 | return 0; 8 | } 9 | return (kill(n-1,k)+k)%n; 10 | } 11 | public static void main(String[] args) { 12 | //System.out.println(kill(7,4)+1); 13 | System.out.println(kill(3,2)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Recursion/PossibleWordsFromPhoneDigits.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | 5 | /*______________________________________________ Incomplete __________________________________*/ 6 | public class PossibleWordsFromPhoneDigits { 7 | static void possibleWords(int a[],int n){ 8 | final String arr[] = { 9 | null,"","abc","def","ghi","jkl", 10 | "mno","pqrs","tuv","wxyz" 11 | }; 12 | for (int i = 0; i < n; i++) { 13 | 14 | } 15 | possibleWords(a,n); 16 | } 17 | public static void main(String[] args) { 18 | possibleWords(new int[]{2,3,4},3); 19 | possibleWords(new int[]{3,4,5},3); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Recursion/RodCutting.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | public class RodCutting { 5 | static int maxCuts(int n,int a,int b,int c){ 6 | 7 | if (n==0){ 8 | return 0; 9 | } 10 | if (n<0){ 11 | return -1; 12 | } 13 | int path1 = maxCuts(n-a, a, b, c); 14 | int path2 = maxCuts(n-b, a, b, c); 15 | int path3 = maxCuts(n-c, a, b, c); 16 | int result = Math.max(Math.max(path1,path2),path3); 17 | if (result<0){ 18 | return -1; 19 | } 20 | return result+1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | System.out.println(maxCuts(5,2,1,5)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Recursion/StringPalindrome.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | public class StringPalindrome { 5 | static boolean isPalindrome(String str,int start,int end){ 6 | if (start>end){ 7 | return true; 8 | } 9 | if (str.charAt(start) != str.charAt(end)){ 10 | return false; 11 | } 12 | return isPalindrome(str,start+1,end-1); 13 | } 14 | public static void main(String[] args) { 15 | String str = "helloolleh"; 16 | System.out.println(isPalindrome(str,0,str.length()-1)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Recursion/SubsetOfString.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | public class SubsetOfString { 5 | static void subset(String str, String curr, int index){ 6 | if (index == str.length()){ 7 | System.out.println(curr); 8 | return; 9 | } 10 | subset(str,curr,index+1); 11 | subset(str,curr+str.charAt(index),index+1); 12 | } 13 | public static void main(String[] args) { 14 | int index = 0; 15 | String curr = ""; 16 | String string = "ABC"; 17 | subset(string,curr,index); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Recursion/SubsetSumArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | public class SubsetSumArray { 5 | static int subSetSum(int[] arr, int n, int sum){ 6 | if (n == 0){ 7 | return (sum == 0) ? 1:0; 8 | } 9 | return subSetSum(arr,n-1,sum)+subSetSum(arr,n-1,sum-arr[n-1]); 10 | } 11 | public static void main(String[] args) { 12 | System.out.println(subSetSum(new int[]{10,20,15},3,25)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Recursion/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Recursion; 2 | /** 3 | * @author Vishal Singh */ 4 | public class TowerOfHanoi { 5 | static void tower(int n,char a,char b,char c){ 6 | if (n == 1){ 7 | System.out.println("Move disk 1 from "+a+" to "+c); 8 | return; 9 | } 10 | tower(n-1,'A','C','B'); 11 | System.out.println("Move disk "+n+" from "+a+" to "+c); 12 | tower(n-1,'A','C','B'); 13 | } 14 | public static void main(String[] args) { 15 | tower(2,'A','B','C'); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Searching/FindFloor.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | /** 3 | * @author Vishal Singh */ 4 | public class FindFloor { 5 | static int findFloor(long[] arr,int n,long element){ 6 | return find(arr,0,n-1,element); 7 | } 8 | static int find(long[] arr,int l,int h,long element){ 9 | if (l>h){ 10 | return -1; 11 | } 12 | if (arr[h] <= element){ 13 | return h; 14 | } 15 | int mid = l + (h-l)/2; 16 | if (arr[mid] == element){ 17 | return mid; 18 | } 19 | if (mid > 0 && arr[mid-1] <= element && arr[mid] > element ){ 20 | return mid-1; 21 | } 22 | if (element < arr[mid]){ 23 | return find(arr,l,mid-1,element); 24 | } 25 | return find(arr,mid+1,h,element); 26 | } 27 | public static void main(String[] args) { 28 | long[] arr = {1, 2, 8, 10, 11, 12, 19}; 29 | long[] testCase = {0,1,2,10,19,13,8}; 30 | 31 | for (long l : testCase) { 32 | int index = findFloor(arr, arr.length, l); 33 | if (index == -1) { 34 | System.out.println("No such element"); 35 | continue; 36 | } 37 | System.out.println("Floor of "+l+" at "+"Index: " + index + " Element: " + arr[index]); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Searching/LeftMostIndex.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | public class LeftMostIndex { 6 | static int leftMostIndex(int[] arr,int elementToSearch){ 7 | return search(arr,0,arr.length-1,elementToSearch)+1; 8 | } 9 | static int search(int[] arr,int low,int high,int elementToSearch){ 10 | if (low>high){ 11 | return -1; 12 | } 13 | int mid = (low+high)/2; 14 | if (arr[mid] == elementToSearch 15 | && ( 16 | mid == 0 || arr[mid-1] != elementToSearch 17 | )) { 18 | return mid; 19 | } 20 | if (arr[mid]>=elementToSearch){ 21 | return search(arr,low,mid-1,elementToSearch); 22 | } 23 | else { 24 | return search(arr,mid+1,high,elementToSearch); 25 | } 26 | } 27 | public static void main(String[] args) { 28 | int[] arr = {0,1,2,2,2,4,5,5,5,5,6,6,6,99}; 29 | /* 30 | * Find leftmost index of the element*/ 31 | System.out.println(leftMostIndex(arr,0)); 32 | System.out.println(leftMostIndex(arr,2)); 33 | System.out.println(leftMostIndex(arr,5)); 34 | System.out.println(leftMostIndex(arr,6)); 35 | System.out.println(leftMostIndex(arr,99)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Searching/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | public class MajorityElement{ 6 | static int findMajorityElement(int[] arr){ 7 | int n = arr.length; 8 | int res = 0; 9 | int count = 1; 10 | for (int i = 1; i < n; i++) { 11 | if(arr[i] == arr[res]){ 12 | count++; 13 | } 14 | else { 15 | count--; 16 | } 17 | if (count == 0){ 18 | res = i; 19 | count = 1; 20 | } 21 | } 22 | count = 0; 23 | for (int i = 0; i < n; i++) { 24 | if (arr[res] == arr[i]) 25 | count++; 26 | } 27 | if (count<=n/2) 28 | res = -1; 29 | return res; 30 | } 31 | public static void main(String[] args) { 32 | int[] arr = {8,7,6,8,6,6,6,6}; 33 | int index = findMajorityElement(arr); 34 | System.out.println("Index: "+index+" Element: "+ arr[index]); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Searching/OccurrenceCountOfElement.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | public class OccurrenceCountOfElement { 6 | static int leftMostIndex(int[] arr,int low,int high,int elementToSearch){ 7 | if (low>high){ 8 | return -1; 9 | } 10 | int mid = (low+high)/2; 11 | if (arr[mid] == elementToSearch && 12 | (mid == 0 || arr[mid-1] != elementToSearch)) { 13 | return mid; 14 | } 15 | if (arr[mid]>=elementToSearch){ 16 | return leftMostIndex(arr,low,mid-1,elementToSearch); 17 | } 18 | else { 19 | return leftMostIndex(arr,mid+1,high,elementToSearch); 20 | } 21 | } 22 | static int rightMostIndex(int[] arr,int low,int high,int n,int elementToSearch){ 23 | if (low>high){ 24 | return -1; 25 | } 26 | int mid = (low+high)/2; 27 | if (arr[mid] == elementToSearch && 28 | (mid == (n-1) || arr[mid+1] != elementToSearch)) { 29 | return mid; 30 | } 31 | if (arr[mid]>elementToSearch){ 32 | return rightMostIndex(arr,low,mid-1,n,elementToSearch); 33 | } 34 | else { 35 | return rightMostIndex(arr,mid+1,high,n,elementToSearch); 36 | } 37 | } 38 | static int noOfOccurrences(int[] arr,int low,int high,int elementToSearch){ 39 | int l = leftMostIndex(arr,low,high,elementToSearch); 40 | int r = rightMostIndex(arr,low,high,arr.length,elementToSearch); 41 | if (l == -1 || r == -1){ 42 | return 0; 43 | } 44 | return (r-l)+1; 45 | } 46 | public static void main(String[] args) { 47 | int[] arr = {0,1,2,2,2,4,5,5,5,5,6,6,6,99}; 48 | /* 49 | *Find the number of occurrence of the searched element*/ 50 | System.out.println(noOfOccurrences(arr,0,arr.length-1,0)); 51 | System.out.println(noOfOccurrences(arr,0,arr.length-1,2)); 52 | System.out.println(noOfOccurrences(arr,0,arr.length-1,6)); 53 | System.out.println(noOfOccurrences(arr,0,arr.length-1,99)); 54 | System.out.println(noOfOccurrences(arr,0,arr.length-1,100)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Searching/PeakElements.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | 6 | public class PeakElements { 7 | static int findPeakElement(int[] arr){ 8 | return search(arr,0,arr.length-1,arr.length); 9 | } 10 | static int search(int[] arr,int low,int high,int n){ 11 | if (low>high){ 12 | return -1; 13 | } 14 | int mid = low + (high-low)/2; 15 | if ( ( (mid == 0) || (arr[mid-1] <= arr[mid]) ) && ( (mid == n-1) || (arr[mid] >= arr[mid+1]) ) ) { 16 | return mid; 17 | } 18 | if (mid > 0 && arr[mid-1]>arr[mid]){ 19 | return search(arr,low,mid-1,n); 20 | } 21 | else { 22 | return search(arr,mid+1,high,n); 23 | } 24 | } 25 | public static void main(String[] args) { 26 | int[] arr = {1,4,10,45,20,9,8,7,6,50}; 27 | System.out.println("Peak Index: "+findPeakElement(arr)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Searching/SortedRotatedArraySearch.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | public class SortedRotatedArraySearch { 6 | static int binarySearch(int arr[],int low,int high,int elementToSearch){ 7 | if (higharr[mid]){ 15 | return binarySearch(arr,mid+1,high,elementToSearch); 16 | } 17 | else { 18 | return binarySearch(arr,low,mid-1,elementToSearch); 19 | } 20 | } 21 | static int findPivot(int[] arr,int low,int high){ 22 | if (highlow) && (arr[mid]>arr[mid+1])){ 33 | return mid; 34 | } 35 | if (arr[low] >= arr[mid]){ 36 | return findPivot(arr,low,mid-1); 37 | } 38 | else { 39 | return findPivot(arr,mid+1,high); 40 | } 41 | } 42 | static int sortedRotatedArraySearch(int[] arr,int elementToSearch){ 43 | int n = arr.length; 44 | int pivot = findPivot(arr, 0, n-1); 45 | if (pivot == -1) { 46 | return binarySearch(arr, 0, n-1, elementToSearch); 47 | } 48 | if (arr[pivot] == elementToSearch) 49 | return pivot; 50 | if (arr[0] <= elementToSearch) 51 | return binarySearch(arr, 0, pivot-1, elementToSearch); 52 | return binarySearch(arr, pivot+1, n-1, elementToSearch); 53 | } 54 | public static void main(String[] args) { 55 | int[] arr = {10,20,40,5,6,7,8}; 56 | int[] arr1 = {10,20,1,2,3,7,8}; 57 | int[] arr2 = {10,20,40,50,60,70,1}; 58 | System.out.println(sortedRotatedArraySearch(arr,100)); 59 | System.out.println(sortedRotatedArraySearch(arr1,10)); 60 | System.out.println(sortedRotatedArraySearch(arr2,1)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Searching/SquareRoot.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | public class SquareRoot { 6 | static long findSquareRoot(long num){ 7 | if (num == 0 || num == 1){ 8 | return num; 9 | } 10 | long start = 1; 11 | long end = num; 12 | long ans = 0; 13 | while (start <= end){ 14 | long mid = (start + end)/2; 15 | if (mid*mid == num) { 16 | return mid; 17 | } 18 | if (mid*mid < num){ 19 | start = mid+1; 20 | ans = mid; 21 | } 22 | else { 23 | end = mid-1; 24 | } 25 | } 26 | return ans; 27 | } 28 | public static void main(String[] args) { 29 | long rootOf = 17054520; 30 | System.out.println(findSquareRoot(rootOf)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Searching/TwoPointerApproach.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Searching; 2 | 3 | /** 4 | * @author Vishal Singh */ 5 | 6 | class PairSum{ 7 | 8 | /* 9 | * Given a sorted array and a sum find if there is a pair with given sum*/ 10 | boolean findPairSumExistence(int[] arr, int sum){ 11 | return searchPair(arr,0,arr.length-1,sum); 12 | } 13 | boolean searchPair(int[]arr, int left,int right,int sum){ 14 | while (leftsum){ 20 | right--; 21 | } 22 | else { 23 | left++; 24 | } 25 | } 26 | return false; 27 | } 28 | } 29 | class TripletSum extends PairSum{ 30 | /* 31 | * Find triplet in an array which gives sum X*/ 32 | boolean findTripletSumExistence(int[] arr,int sum){ 33 | for (int i = 0; i < arr.length ; i++) { 34 | if(searchPair(arr,i+1,arr.length-1,sum-arr[i])){ 35 | System.out.println(arr[i]); 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | } 42 | 43 | public class TwoPointerApproach { 44 | public static void main(String[] args) { 45 | 46 | int[] arr = { 47 | 2,4,8,9,11,12,20,30 48 | }; 49 | int sum1 = 23; 50 | int sum2 = 7; 51 | PairSum pairSum = new PairSum(); 52 | System.out.println("Pair Sum"); 53 | System.out.println(pairSum.findPairSumExistence(arr,sum1)+" with sum "+ sum1); 54 | System.out.println(pairSum.findPairSumExistence(arr,sum2)+" with sum "+ sum2); 55 | 56 | TripletSum tripletSum = new TripletSum(); 57 | System.out.println("Triplet Sum"); 58 | System.out.println(tripletSum.findTripletSumExistence(arr,sum1)+" with sum "+ sum1); 59 | System.out.println(tripletSum.findTripletSumExistence(arr,sum2)+" with sum "+ sum2); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /SegmentTree/BinaryIndexTreeImplementation.java: -------------------------------------------------------------------------------- 1 | package SegmentTree; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 7/24/2021 8 | */ 9 | public class BinaryIndexTreeImplementation { 10 | static class BinaryIndexTree { 11 | int[] tree; 12 | int[] arr; 13 | int n; 14 | BinaryIndexTree(int[] arr) { 15 | int cn = arr.length; 16 | this.n = cn + 1; 17 | tree = new int[n]; 18 | this.arr = arr; 19 | } 20 | public void build() { 21 | Arrays.fill(tree,0); 22 | for (int i = 0; i < arr.length; i++) { 23 | buildUpdate(i,arr[i]); 24 | } 25 | } 26 | public void buildUpdate(int i,int val) { 27 | i = i + 1; 28 | while (i <= n) { 29 | tree[i] += val; 30 | i += (i & (-i)); 31 | } 32 | } 33 | public void update(int i,int val){ 34 | int diff = val - arr[i]; 35 | arr[i] = val; 36 | i = i + 1; 37 | while (i <= n) { 38 | tree[i] += diff; 39 | i += (i & (-i)); 40 | } 41 | } 42 | public int getSum(int i) { 43 | i+=1; 44 | int res = 0; 45 | while (i > 0) { 46 | res += tree[i]; 47 | i = i - (i & (-i)); 48 | } 49 | return res; 50 | } 51 | } 52 | 53 | public static void main(String[] args) { 54 | int[] arr = {10,20,30,40,50,60}; 55 | BinaryIndexTree b = new BinaryIndexTree(arr); 56 | b.build(); 57 | System.out.println(b.getSum(0)); 58 | System.out.println(b.getSum(1)); 59 | System.out.println(b.getSum(2)); 60 | System.out.println(b.getSum(3)); 61 | b.update(0,1000); 62 | System.out.println(b.getSum(0)); 63 | System.out.println(b.getSum(1)); 64 | System.out.println(b.getSum(2)); 65 | System.out.println(b.getSum(3)); 66 | } 67 | } -------------------------------------------------------------------------------- /Sorting/BucketSort.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | 7 | /** 8 | * @author Vishal Singh */ 9 | public class BucketSort { 10 | static void bucketSort(int[] arr,int k){ 11 | int n =arr.length; 12 | int range = arr[0]; 13 | for (int i = 1; i < arr.length; i++) { 14 | range = Math.max(range,arr[i]); 15 | } 16 | range++; 17 | ArrayList> buckets = new ArrayList>(); 18 | for (int i = 0; i < k; i++) { 19 | buckets.add(new ArrayList()); 20 | } 21 | for (int i = 0; i < n; i++) { 22 | int bucketIndex = (k*arr[i])/range; 23 | buckets.get(bucketIndex).add(arr[i]); 24 | } 25 | for (int i = 0; i < k; i++) { 26 | Collections.sort(buckets.get(i)); 27 | } 28 | int index = 0; 29 | for (int i = 0; i < k; i++) { 30 | for (int j = 0; j < buckets.get(i).size(); j++) { 31 | arr[index++] = buckets.get(i).get(j); 32 | } 33 | } 34 | 35 | } 36 | public static void main(String[] args) { 37 | int[] arr = {20,88,10,85,75,99,18}; 38 | int k =5; 39 | bucketSort(arr,k); 40 | System.out.println(Arrays.toString(arr)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Sorting/ChocolateDistribution.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author Vishal Singh */ 7 | public class ChocolateDistribution { 8 | static int minDifference(int[] arr,int n,int m){ 9 | if (m>n){ 10 | return -1; 11 | } 12 | Arrays.sort(arr); 13 | int res = arr[m-1]-arr[0]; 14 | for (int i = 1; (i+m-1) < n ; i++) { 15 | res = Math.min(res,arr[i+m-1]-arr[i]); 16 | } 17 | return res; 18 | } 19 | public static void main(String[] args) { 20 | int[] arr = {7,3,2,4,9,12,56}; 21 | System.out.println("Min Difference: "+minDifference(arr,arr.length,3)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Sorting/CountInversionInArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | /** 3 | * @author Vishal Singh */ 4 | public class CountInversionInArray { 5 | static int countInversion(int[] arr,int left,int right){ 6 | int res = 0; 7 | if (right>left){ 8 | int mid = left + (right-left)/2; // This avoids overflow 9 | res += countInversion(arr,left,mid); 10 | res += countInversion(arr,mid+1,right); 11 | res += merge(arr,left,mid,right); 12 | } 13 | return res; 14 | } 15 | static int merge(int[] arr,int left,int middle,int right){ 16 | int sizeOfArr1 = (middle-left)+1; 17 | int sizeOfArr2 = (right-middle); 18 | int[] arr1 = new int[sizeOfArr1]; 19 | int[] arr2 = new int[sizeOfArr2]; 20 | System.arraycopy(arr,left,arr1,0,sizeOfArr1); 21 | System.arraycopy(arr,middle+1,arr2,0,sizeOfArr2); 22 | 23 | int res = 0; 24 | int i = 0; 25 | int j = 0; 26 | int k = left; 27 | while (i= 0; i--) { 22 | output[count[arr[i]]-1] = arr[i]; 23 | count[arr[i]]--; 24 | } 25 | if (n >= 0) System.arraycopy(output, 0, arr, 0, n); 26 | } 27 | public static void main(String[] args) { 28 | int[] arr = {1,4,4,1,0,1}; 29 | countingSort(arr,arr.length,5); 30 | System.out.println(Arrays.toString(arr)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Sorting/CycleSort.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author Vishal Singh */ 7 | public class CycleSort { 8 | static void swap(int[] arr,int i,int j){ 9 | int temp = arr[i]; 10 | arr[i] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | static void cycleSort(int[] arr,int n){ 14 | for (int i = 0; i < n; i++) { 15 | int item = arr[i]; 16 | int pos = i; 17 | for (int j = i+1; j < n; j++) { 18 | if(arr[j]0 && array1[i-1] == array1[i]){ 16 | i++; 17 | continue; 18 | } 19 | if (array1[i] < array2[j]){ 20 | i++; 21 | } 22 | else if (array1[i] > array2[j]){ 23 | j++; 24 | } 25 | else { 26 | System.out.print(array1[i]+" "); 27 | i++; 28 | j++; 29 | } 30 | } 31 | } 32 | public static void main(String[] args) { 33 | int[] array1 = {2,6,8,13,15}; 34 | int[] array2 = {1,3,8,15,18,20,25}; 35 | intersection(array1,array2,array1.length,array2.length); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Sorting/KthSmallestElement.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | /** 5 | * @author Vishal Singh 6 | * Quick Select Algorithm*/ 7 | public class KthSmallestElement { 8 | static void swap(int[] arr,int i,int j){ 9 | int temp = arr[i]; 10 | arr[i] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | static int lomutoPartition(int[] arr,int l,int h){ 14 | int pivotIndex = arr[h]; 15 | int i = l-1; 16 | for (int j = l; j < h ; j++) { 17 | if (arr[j]<=pivotIndex){ 18 | i++; 19 | swap(arr,i,j); 20 | } 21 | } 22 | swap(arr,i+1,h); 23 | return i+1; 24 | } 25 | static int findMin(int[] arr,int n,int k){ 26 | int l = 0; 27 | int r = n-1; 28 | while (l<=k){ 29 | int pivotValue = lomutoPartition(arr,l,r); 30 | if (pivotValue == k-1){ 31 | return pivotValue; 32 | } 33 | else if (pivotValue > k-1){ 34 | r = pivotValue - 1; 35 | } 36 | else{ 37 | l = pivotValue + 1; 38 | } 39 | } 40 | return -1; 41 | } 42 | public static void main(String[] args) { 43 | int[] arr = {10,4,5,8,11,6,26}; 44 | System.out.println("The Array: "+ Arrays.toString(arr)); 45 | int min = findMin(arr,arr.length,3); 46 | System.out.println("3rd min element: "+arr[min]); 47 | min = findMin(arr,arr.length,4); 48 | System.out.println("4th min element: "+arr[min]); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Sorting/ListTypeArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | 7 | /** 8 | * @author Vishal Singh */ 9 | 10 | class Point1{ 11 | int xPoint,yPoint; 12 | Point1(int xPoint,int yPoint){ 13 | this.xPoint = xPoint; 14 | this.yPoint = yPoint; 15 | } 16 | } 17 | class MySort1 implements Comparator { 18 | public int compare(Point a,Point b){ 19 | //sorts in increasing order of x 20 | return (a.xPoint-b.xPoint); 21 | /* 22 | Sorts in decreasing order of x 23 | return (b.x-a.x); 24 | */ 25 | /* 26 | Sorts acc to y 27 | return (a.y-b.y); 28 | */ 29 | } 30 | } 31 | 32 | public class ListTypeArray { 33 | public static void main(String[] args) { 34 | ArrayList arrayList = new ArrayList<>(); 35 | arrayList.add(10); 36 | arrayList.add(5); 37 | arrayList.add(1); 38 | arrayList.add(27); 39 | Collections.sort(arrayList); 40 | System.out.println(arrayList); 41 | 42 | Collections.sort(arrayList,Collections.reverseOrder()); // Implements Tim sort (Insertion + Merge)Sort 43 | //Can also be written as -> arrayList.sort(Collections.reverseOrder()); 44 | System.out.println(arrayList); 45 | 46 | ArrayList arrayList1 = new ArrayList<>(); 47 | arrayList1.add(new Point(10,20)); 48 | arrayList1.add(new Point(3,12)); 49 | arrayList1.add(new Point(5,7)); 50 | 51 | Collections.sort(arrayList1,new MySort1()); 52 | for (Point p: 53 | arrayList1) { 54 | System.out.print("{"+p.xPoint+" "+p.yPoint+"} "); 55 | } 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Sorting/MergeOverlappingIntervals.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | /** 7 | * @author Vishal Singh */ 8 | public class MergeOverlappingIntervals { 9 | static class Interval{ 10 | int start; 11 | int end; 12 | Interval(int start,int end){ 13 | this.start = start; 14 | this.end = end; 15 | } 16 | @Override 17 | public String toString() { 18 | return "{" + 19 | "Start=" + start + 20 | ", End=" + end + 21 | '}'; 22 | } 23 | } 24 | static class Sort implements Comparator { 25 | @Override 26 | public int compare(Interval t1, Interval t2) { 27 | return t1.start-t2.start; 28 | } 29 | } 30 | static void mergeOverlap(Interval[] arr,int n){ 31 | Arrays.sort(arr,new Sort()); 32 | int resultIndex = 0; // Elements from 0 to resultIndex are the merged part of the array 33 | for (int i = 1; i < n; i++) { 34 | if (arr[resultIndex].end >= arr[i].start){ 35 | arr[resultIndex].end = Math.max(arr[resultIndex].end,arr[i].end); 36 | arr[resultIndex].start = Math.min(arr[resultIndex].start,arr[i].start); 37 | } 38 | else { 39 | resultIndex++; 40 | arr[resultIndex] = arr[i]; 41 | } 42 | } 43 | for (int i = 0; i <= resultIndex; i++) { 44 | System.out.println(arr[i].toString()); 45 | } 46 | } 47 | public static void main(String[] args) { 48 | Interval[] arr = { 49 | new Interval(7,9), 50 | new Interval(6,10), 51 | new Interval(4,5), 52 | new Interval(1,3), 53 | new Interval(2,4), 54 | }; 55 | mergeOverlap(arr,arr.length); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Sorting/NormalArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | 7 | /** 8 | * @author Vishal Singh */ 9 | class Point{ 10 | int xPoint,yPoint; 11 | Point(int xPoint,int yPoint){ 12 | this.xPoint = xPoint; 13 | this.yPoint = yPoint; 14 | } 15 | } 16 | class MySort implements Comparator{ 17 | public int compare(Point a,Point b){ 18 | //sorts in increasing order of x 19 | return (a.xPoint-b.xPoint); 20 | /* 21 | Sorts in decreasing order of x 22 | return (b.x-a.x); 23 | */ 24 | } 25 | } 26 | 27 | public class NormalArray { 28 | public static void main(String[] args) { 29 | int[] arr = {9,8,7,6,5,4,3,1,2}; 30 | Arrays.sort(arr); 31 | System.out.println(Arrays.toString(arr)); 32 | 33 | //Collection.reverseOrder() works only with wrapper class 34 | Integer[] arr1 = {9,8,7,6,5,4,3,1,2}; 35 | Arrays.sort(arr1,Collections.reverseOrder()); 36 | System.out.println(Arrays.toString(arr1)); 37 | 38 | arr = new int[]{9,8,7,6,5,4,3,1,2}; 39 | Arrays.sort(arr,1,3); 40 | System.out.println(Arrays.toString(arr)); 41 | 42 | 43 | //Sorting Point which stores 2d points 44 | Point[] points = { 45 | new Point(10,20), 46 | new Point(3,12), 47 | new Point(5,7), 48 | }; 49 | Arrays.sort(points,new MySort()); 50 | for (Point point : points) { 51 | System.out.print("{"+point.xPoint + "," + point.yPoint+"}"); 52 | System.out.print(" "); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Sorting/QuickSortUsingHoarePartition.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | public class QuickSortUsingHoarePartition { 6 | static void swap(int[] arr,int i,int j){ 7 | int temp = arr[i]; 8 | arr[i] = arr[j]; 9 | arr[j] = temp; 10 | } 11 | static int hoarePartition(int[] arr, int l, int h){ 12 | int pivotIndex = arr[l]; 13 | int i = l - 1; 14 | int j = h + 1; 15 | while (true){ 16 | do { 17 | i++; 18 | }while (arr[i]pivotIndex); 22 | if (i>=j){ 23 | return j; 24 | } 25 | swap(arr,i,j); 26 | } 27 | } 28 | static void quickSort(int[] arr,int l,int h){ 29 | if (l= 0; i--) { 22 | output[count[(arr[i]/exp)%10]-1] = arr[i]; 23 | count[(arr[i]/exp)%10]--; 24 | } 25 | if (n >= 0) System.arraycopy(output, 0, arr, 0, n); 26 | } 27 | static void radixSort(int[] arr,int n){ 28 | //Find the largest elements number of digit 29 | int max = Math.max(arr[0],arr[1]); 30 | for (int i = 2; i < n; i++) { 31 | max = Math.max(max,arr[i]); 32 | } 33 | //max = (int)(Math.log10(max))+1; 34 | for (int exp = 1; max/exp > 0; exp=exp*10) { 35 | countingSort(arr,n,exp); 36 | } 37 | } 38 | public static void main(String[] args) { 39 | int[] arr = {319,212,6,8,100,50}; 40 | int n = arr.length; 41 | radixSort(arr,n); 42 | System.out.println(Arrays.toString(arr)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Sorting/SegregateElementOfThreeType.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * Segregate 0,1,2 in an Array 8 | * Three way partitioning - Value same as pivot together in mid, Less than pivot before pivot, Greater than pivot after pivot 9 | * Partioning around a Range - Value in range together in mid, Less than range before mid, Greater than range after mid 10 | * The algo used to solve this type of question is DUTCH NATIONAL FLAG ALGORITHM 11 | * */ 12 | public class SegregateElementOfThreeType { 13 | static void swap(int[] arr,int i,int j){ 14 | int temp = arr[i]; 15 | arr[i] = arr[j]; 16 | arr[j] = temp; 17 | } 18 | static void segregateZeroOneTwo(int[] arr,int n){ 19 | if (n<=1){ 20 | return; 21 | } 22 | int low = 0; 23 | int mid = 0; 24 | int high = n-1; 25 | while (mid<=high){ 26 | switch (arr[mid]){ 27 | case 0: 28 | swap(arr,mid,low); 29 | low++; 30 | mid++; 31 | break; 32 | case 1: 33 | mid++; 34 | break; 35 | case 2: 36 | swap(arr,mid,high); 37 | high--; 38 | break; 39 | } 40 | } 41 | } 42 | public static void main(String[] args) { 43 | int[] arr = {2,1,0,2,1,1,1,0,2,1,1,0,1,1,0,0}; 44 | segregateZeroOneTwo(arr,arr.length); 45 | System.out.println(Arrays.toString(arr)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Sorting/UnionOfTwoSortedArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Sorting; 2 | /** 3 | * @author Vishal Singh */ 4 | public class UnionOfTwoSortedArray { 5 | /** 6 | * This function find the distinct union of the two arrays 7 | * @param A The first array 8 | * @param B The second array 9 | * @param size1 Size of the first array 10 | * @param size2 Size of the second array*/ 11 | static void union(int[] A,int[] B,int size1,int size2){ 12 | int i = 0; 13 | int j =0; 14 | while (i < size1 && j < size2){ 15 | if (i > 0 && A[i-1] == A[i]) { 16 | i++; 17 | continue; 18 | } 19 | if (j>0 && B[j-1] == B[j]){ 20 | j++; 21 | continue; 22 | } 23 | if (A[i] stack = new Stack<>(); 13 | for (int i = 0; i < str.length(); i++) { 14 | if(str.charAt(i) == '{' || str.charAt(i) == '[' || str.charAt(i) == '('){ 15 | stack.push(str.charAt(i)); 16 | } 17 | else{ 18 | if(stack.isEmpty()){ 19 | return false; 20 | } 21 | else if(check(str.charAt(i),stack.peek())){ 22 | return false; 23 | } 24 | else{ 25 | stack.pop(); 26 | } 27 | } 28 | } 29 | return stack.empty(); 30 | } 31 | public static void main(String[] args) { 32 | String parenthesis = "{[([{}])]}"; // TRUE 33 | String parenthesis1 = "{[}]}"; // FALSE 34 | System.out.println(isBalancedParenthesis(parenthesis)); 35 | System.out.println(isBalancedParenthesis(parenthesis1)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Stack/DeleteMidOfStack.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class DeleteMidOfStack { 9 | static Stack deleteMid(Stacks,int sizeOfStack,int current) { 10 | int mid = (int) Math.ceil(sizeOfStack/2.0); 11 | System.out.println(mid); 12 | if (s.isEmpty() || current == sizeOfStack){ 13 | return s; 14 | } 15 | int x = s.pop(); 16 | deleteMid(s,sizeOfStack,current+1); 17 | if (current != (sizeOfStack/2)){ 18 | s.push(x); 19 | } 20 | return s; 21 | } 22 | public static void main(String[] args) { 23 | Stack s = new Stack<>(); 24 | s.push(1); 25 | s.push(2); 26 | s.push(3); 27 | s.push(4); 28 | System.out.println(deleteMid(s,s.size(),0)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Stack/EvalPostfix.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class EvalPostfix { 9 | static int calculate(char ch, int a, int b){ 10 | if (ch == '/'){ 11 | return a/b; 12 | }else if (ch == '*'){ 13 | return a*b; 14 | }else if (ch == '+'){ 15 | return a+b; 16 | }else{ 17 | return a-b; 18 | } 19 | } 20 | static int evaluatePostFix(String exp){ 21 | Stack temp = new Stack<>(); 22 | int eval = 0; 23 | for (int i = 0; i < exp.length(); i++) { 24 | char currChar = exp.charAt(i); 25 | // Not from these then -1 26 | if ("+-*/".indexOf(currChar) == -1){ 27 | temp.push(Integer.parseInt(String.valueOf(exp.charAt(i)))); 28 | }else { 29 | int first = temp.pop(); 30 | int second =temp.pop(); 31 | int res = calculate(currChar,second,first); 32 | temp.push(res); 33 | } 34 | } 35 | return temp.pop(); 36 | } 37 | public static void main(String[] args) { 38 | String exp = "231*+9-"; 39 | System.out.println(evaluatePostFix(exp)); 40 | } 41 | } -------------------------------------------------------------------------------- /Stack/GetMin.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /* 6 | * @author: Vishal Singh*/ 7 | public class GetMin{ 8 | static class StackGetMin{ 9 | Stack main = new Stack<>(); 10 | Stack aux = new Stack<>(); 11 | void push(int data){ 12 | if (main.isEmpty()) { 13 | main.push(data); 14 | aux.push(data); 15 | System.out.println("Pushed "+data); 16 | }else { 17 | main.push(data); 18 | System.out.println("Pushed "+data); 19 | } 20 | if (aux.peek() >= main.peek()){ 21 | aux.push(data); 22 | } 23 | } 24 | void pop(){ 25 | if (main.peek().equals(aux.peek())) { 26 | aux.pop(); 27 | } 28 | System.out.println("Popped "+main.pop()); 29 | } 30 | void getMin(){ 31 | System.out.println(aux.peek()); 32 | } 33 | } 34 | public static void main(String[] args) { 35 | StackGetMin s = new StackGetMin(); 36 | s.push(3); 37 | s.push(5); 38 | s.getMin(); 39 | s.push(2); 40 | s.push(1); 41 | s.getMin(); 42 | s.pop(); 43 | s.getMin(); 44 | s.pop(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Stack/GetMinAtPop.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class GetMinAtPop { 9 | public static Stack _push(int arr[], int n) 10 | { 11 | Stacks=new Stack<>(); 12 | int min=arr[0]; 13 | for(int i=0;is) 20 | { 21 | while(!s.empty()) 22 | System.out.print(s.pop()+" "); 23 | } 24 | public static void main(String[] args) { 25 | Stack s = _push(new int[]{1, 6, 43, 1, 2, 0, 5},7); 26 | _getMinAtPop(s); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/Histogram1.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /* 6 | *@author: Vishal Singh*/ 7 | 8 | public class Histogram1{ 9 | public static void main(String[] args){ 10 | int[] arr = {6,2,5,4,1,5,6}; 11 | int n = arr.length; 12 | System.out.println(longestRectangularAreaInAHistogram(arr,n)); 13 | } 14 | static int[] prevSmallerIndex(int[] arr,int n){ 15 | int[] temp = new int[n]; 16 | Stack stack = new Stack<>(); 17 | temp[0] = -1; 18 | stack.push(0); 19 | for (int i = 1; i < n ;i++ ){ 20 | while(!stack.isEmpty() && arr[stack.peek()]>= arr[i]){ 21 | stack.pop(); 22 | } 23 | int ps = stack.isEmpty() ?-1:stack.peek(); 24 | temp[i] = ps; 25 | stack.push(i); 26 | } 27 | return temp; 28 | } 29 | static int[] nextSmallerIndex(int[] arr, int n){ 30 | int[] temp = new int[n]; 31 | Stack stack = new Stack<>(); 32 | temp[n-1] = n; 33 | stack.push(n-1); 34 | for (int i = n-2;i >= 0 ;i--) { 35 | while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]){ 36 | stack.pop(); 37 | } 38 | int ns = stack.isEmpty() ? 7 : stack.peek(); 39 | temp[i] = ns; 40 | stack.push(i); 41 | } 42 | return temp; 43 | } 44 | static int longestRectangularAreaInAHistogram(int[] arr,int n){ 45 | int res = 0; 46 | int[] ps = prevSmallerIndex(arr,n); 47 | int[] ns = nextSmallerIndex(arr,n); 48 | for (int i = 0;i < n ;i++ ) { 49 | int curr = arr[i]; 50 | curr+= (i-ps[i]-1)*arr[i]; 51 | curr+= (ns[i]-1-i)*arr[i]; 52 | res = Math.max(res,curr); 53 | } 54 | return res; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Stack/Histogram2.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | /** 3 | * @author: Vishal Singh 4 | * On hold*/ 5 | /* 6 | public class Histogram2{ 7 | public static void main(String[] args){ 8 | int[] arr = {6,2,5,4,1,5,6}; 9 | int n = 7; 10 | 11 | } 12 | static int longestRectangularAreaInAHistogram2(int[] arr, int b){ 13 | 14 | } 15 | } 16 | */ 17 | -------------------------------------------------------------------------------- /Stack/KStackInArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class KStackInArray { 7 | static class KStack{ 8 | int[] arr; 9 | int[] top; 10 | int[] next; 11 | int k, capacity, freeTop; 12 | KStack(int k1, int n){ 13 | k = k1; 14 | capacity = n; 15 | arr = new int[capacity]; 16 | top = new int[k]; 17 | next = new int[capacity]; 18 | freeTop = 0; 19 | for (int i = 0; i < capacity-1; i++) { 20 | next[i] = i+1; 21 | } 22 | next[capacity-1] = -1; 23 | } 24 | void push(int x, int stackNumber){ 25 | int i = freeTop; 26 | freeTop = next[i]; 27 | next[i] = top[stackNumber]; 28 | top[stackNumber] = i; 29 | arr[i] = x; 30 | } 31 | int pop(int stackNumber){ 32 | int i = top[stackNumber]; 33 | top[stackNumber] = next[i]; 34 | next[i] = freeTop; 35 | freeTop = i; 36 | return arr[i]; 37 | } 38 | } 39 | public static void main(String[] args) { 40 | KStack kStack = new KStack(4,4); 41 | kStack.push(101,0); 42 | kStack.push(211,1); 43 | kStack.push(325,2); 44 | kStack.push(444,3); 45 | for (int i = 0; i < 4; i++) { 46 | System.out.println(kStack.pop(i)); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Stack/LinkedListStack.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class LinkedListStack { 7 | static class Node{ 8 | int data; 9 | Node next; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | static class List{ 15 | Node head; 16 | void insertEnd(int data){ 17 | Node temp = new Node(data); 18 | temp.next = head; 19 | head = temp; 20 | } 21 | int pop(){ 22 | if(head == null){ 23 | return -1; 24 | } 25 | int data = head.data; 26 | head = head.next; 27 | return data; 28 | } 29 | void print(){ 30 | Node temp = head; 31 | while(temp != null){ 32 | System.out.print(temp.data+" "); 33 | temp = temp.next; 34 | } 35 | System.out.println(""); 36 | } 37 | } 38 | static class Stack { 39 | private final List list = new List(); 40 | void push(int data){ 41 | list.insertEnd(data); 42 | } 43 | int pop(){ 44 | int temp = list.pop(); 45 | return temp; 46 | } 47 | void print(){ 48 | list.print(); 49 | } 50 | } 51 | 52 | public static void main(String[] args) { 53 | Stack s = new Stack(); 54 | s.push(5); 55 | s.push(4); 56 | s.push(3); 57 | s.push(31); 58 | s.print(); 59 | System.out.println(s.pop()); 60 | System.out.println(s.pop()); 61 | System.out.println(s.pop()); 62 | System.out.println(s.pop()); 63 | s.push(1); 64 | s.print(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Stack/NextGreater.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Stack; 6 | 7 | /** 8 | * @author Vishal Singh 9 | */ 10 | public class NextGreater { 11 | public static void main(String[] args) { 12 | int[] arr = {5,15,10,8,6,12,9,18}; 13 | // {15,18,12,12,12,18,18,-1} 14 | ArrayList list = new ArrayList<>(); 15 | Stack stack = new Stack<>(); 16 | list.add(-1); 17 | stack.push(arr[arr.length-1]); 18 | for (int i = arr.length-2; i >=0; i--) { 19 | while (!stack.isEmpty() && stack.peek()<= arr[i]){ 20 | stack.pop(); 21 | } 22 | int ng = stack.empty()?-1: stack.peek(); 23 | list.add(ng); 24 | stack.push(arr[i]); 25 | } 26 | Collections.reverse(list); 27 | System.out.println(list); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Stack/PreviousGreater.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author Vishal Singh 7 | * 8 | * : -> To find the closest previous greater 9 | */ 10 | public class PreviousGreater { 11 | public static void main(String[] args) { 12 | int[] arr = {15, 10, 18, 12, 4, 6, 2, 8}; 13 | // = {-1, 15 -1 18 12 12 6 12} 14 | Stack previousGreat = new Stack<>(); 15 | previousGreat.push(arr[0]); 16 | System.out.print("-1 "); 17 | for (int i = 1; i < 8; i++) { 18 | while (!previousGreat.isEmpty() && previousGreat.peek() <= arr[i]){ 19 | previousGreat.pop(); 20 | } 21 | int pg = previousGreat.empty() ? -1 : previousGreat.peek(); 22 | System.out.print(pg+" "); 23 | previousGreat.push(arr[i]); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Stack/RemoveConsecutiveDuplicates.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class RemoveConsecutiveDuplicates { 9 | public static String removeConsecutiveDuplicates(String str){ 10 | Stack st = new Stack<>(); 11 | st.push(str.charAt(0)); 12 | StringBuilder temp = new StringBuilder(str.charAt(0) + ""); 13 | for(int i = 1; i < str.length(); i++){ 14 | if(st.peek() != str.charAt(i)){ 15 | st.push(str.charAt(i)); 16 | temp.append(st.peek()); 17 | } 18 | } 19 | return temp.toString(); 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(removeConsecutiveDuplicates("aaaaaabaabccccccc")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Stack/RemoveConsecutiveDuplicates2.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class RemoveConsecutiveDuplicates2 { 9 | public static String removePair(String str){ 10 | Stack st = new Stack<>(); 11 | st.push(str.charAt(0)); 12 | StringBuilder sb = new StringBuilder(""); 13 | for (int i = 1; i < str.length(); i++) { 14 | if (!st.isEmpty() && st.peek() == str.charAt(i)){ 15 | st.pop(); 16 | }else { 17 | st.push(str.charAt(i)); 18 | } 19 | } 20 | for (Character ch : 21 | st) { 22 | sb.append(ch); 23 | } 24 | return st.isEmpty() ? "Empty String" : sb.toString(); 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(removePair("aaabbaaccd")); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Stack/StockSpan.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | public class StockSpan { 10 | public static void main(String[] args) { 11 | int[] arr = {15,13,12,14,16,8,6,4,10,30}; 12 | //Span arr= {1, 1, 1, 3, 5, 1,1,1, 1, 10} 13 | System.out.println(Arrays.toString(arr)); 14 | Stack span = new Stack(); 15 | span.push(0); 16 | System.out.print("1 "); 17 | for (int i = 1; i < 10; i++) { 18 | while (!span.isEmpty() && arr[span.peek()] <= arr[i]){ 19 | span.pop(); 20 | } 21 | int spanSize = span.empty()? (i+1) : (i - span.peek()); 22 | System.out.print(spanSize+" "); 23 | span.push(i); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Stack/TwoStacksInAnArray.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Stack; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class TwoStacksInAnArray { 7 | static class TwoStack{ 8 | int arr[]; 9 | int capacity, top1, top2; 10 | TwoStack(int n){ 11 | capacity = n; 12 | top1 = -1; 13 | top2 = n; 14 | arr = new int[n]; 15 | } 16 | void push1(int x){ 17 | if (top1 < top2-1){ 18 | top1++; 19 | arr[top1] = x; 20 | } 21 | } 22 | void push2(int x){ 23 | if (top1 < top2-1){ 24 | top2--; 25 | arr[top2] = x; 26 | } 27 | } 28 | int pop1(){ 29 | if (top1 >= 0){ 30 | int x = arr[top1]; 31 | top1--; 32 | return x; 33 | }else { 34 | return -1; 35 | } 36 | } 37 | int pop2(){ 38 | if (top2 < capacity){ 39 | int x = arr[top2]; 40 | top2++; 41 | return x; 42 | }else { 43 | return -1; 44 | } 45 | } 46 | } 47 | public static void main(String[] args) { 48 | TwoStack twoStack = new TwoStack(7); 49 | twoStack.push1(1); 50 | twoStack.push1(2); 51 | twoStack.push1(3); 52 | twoStack.push1(4); 53 | 54 | twoStack.push2(40); 55 | twoStack.push2(455); 56 | 57 | for (int i = 0; i < 4; i++) { 58 | System.out.println(twoStack.pop1()); 59 | } 60 | for (int i = 0; i < 2; i++) { 61 | System.out.println(twoStack.pop2()); 62 | } 63 | 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Strings/CheckAnagram.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class CheckAnagram { 9 | /** 10 | * Using Hash map*/ 11 | static boolean checkAnagram(String s1,String s2){ 12 | if (s1.length() != s2.length()){ 13 | return false; 14 | } 15 | HashMap set = new HashMap<>(); 16 | for (int i = 0; i < s1.length(); i++) { 17 | if (set.containsKey(s1.charAt(i))){ 18 | set.put(s1.charAt(i),set.get(s1.charAt(i))+1); 19 | } 20 | else { 21 | set.put(s1.charAt(i),1); 22 | } 23 | } 24 | for (int i = 0; i < s2.length(); i++) { 25 | if (set.containsKey(s2.charAt(i))){ 26 | set.put(s2.charAt(i),set.get(s2.charAt(i))-1); 27 | if (set.get(s2.charAt(i)) == 0){ 28 | set.remove(s2.charAt(i)); 29 | } 30 | } 31 | } 32 | return set.size() == 0; 33 | } 34 | /** 35 | * Using Array*/ 36 | static boolean check(String s1,String s2){ 37 | if (s1.length() != s2.length()){ 38 | return false; 39 | } 40 | int[] count = new int[256]; 41 | for (int i = 0; i < s1.length(); i++) { 42 | count[s1.charAt(i)]++; 43 | count[s2.charAt(i)]--; 44 | } 45 | for (int i = 0; i < 256; i++) { 46 | if (count[i] != 0){ 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | public static void main(String[] args) { 53 | String s1 = "vishal"; 54 | String s2 = "lahsiv"; 55 | System.out.println(checkAnagram(s1,s2)); 56 | System.out.println(check(s1,s2)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Strings/CheckPanagram.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class CheckPanagram { 7 | static boolean checkPan(String str){ 8 | str = str.toLowerCase(); 9 | int[] arr = new int[256]; 10 | int sum = 0; 11 | for (int i = 0; i < str.length(); i++) { 12 | arr[str.charAt(i)]++; 13 | sum+= arr[str.charAt(i)]; 14 | } 15 | for (int i = 97; i <= 122; i++) { 16 | if (!(arr[i] >0)){ 17 | return false; 18 | } 19 | } 20 | return true; 21 | } 22 | public static void main(String[] args) { 23 | String str = "The quick brown fox jumps over the lazy dog"; 24 | System.out.println(checkPan(str)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Strings/IsogramWords.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class IsogramWords { 9 | static void checkIsogramWords(String s){ 10 | int[] arr = new int[256]; 11 | int n = s.length(); 12 | for (int i = 0; i < n; i++) { 13 | arr[s.charAt(i)]++; 14 | } 15 | for (int i = 0; i < 256; i++) { 16 | if (arr[i]>1){ 17 | System.out.println("No it is not an Isogram"); 18 | return; 19 | } 20 | } 21 | System.out.println("Yes it is an Isogram"); 22 | } 23 | public static void main(String[] args)throws IOException { 24 | String s = "Isogram"; 25 | checkIsogramWords(s); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Strings/KeypadTyping.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.HashMap; 7 | 8 | /** 9 | * @author Vishal Singh 10 | */ 11 | public class KeypadTyping { 12 | static void preCompute(HashMap map){ 13 | for (char i = 97; i <= 122; i++) { 14 | if (i<='c'){ 15 | map.put(i,2); 16 | } else if (i<='f'){ 17 | map.put(i,3); 18 | } else if (i<='i'){ 19 | map.put(i,4); 20 | } else if (i<='l'){ 21 | map.put(i,5); 22 | } else if (i<='o'){ 23 | map.put(i,6); 24 | } else if (i<='s'){ 25 | map.put(i,7); 26 | } else if (i<='v'){ 27 | map.put(i,8); 28 | } else { 29 | map.put(i,9); 30 | } 31 | } 32 | } 33 | public static void main(String[] args)throws IOException { 34 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 35 | int test = Integer.parseInt(br.readLine()); 36 | 37 | //Pre Compute 38 | HashMap map = new HashMap<>(); 39 | preCompute(map); 40 | 41 | while (test-->0){ 42 | String s = br.readLine(); 43 | s = s.toLowerCase(); 44 | for (int i = 0; i < s.length(); i++) { 45 | System.out.print(map.get(s.charAt(i))); 46 | } 47 | System.out.println(""); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Strings/LeftMostRepeating.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class LeftMostRepeating { 7 | static int leftmostRepeating(String str,int n){ 8 | int res = Integer.MAX_VALUE; 9 | int[] firstIndex = new int[256]; 10 | for (int i = 0; i < 256; i++) { 11 | firstIndex[i] = -1; 12 | } 13 | for (int i = 0; i < n; i++) { 14 | if (firstIndex[str.charAt(i)] == -1){ 15 | firstIndex[str.charAt(i)] = i; 16 | } 17 | else { 18 | res = Math.min(res,firstIndex[str.charAt(i)]); 19 | } 20 | } 21 | return res == Integer.MAX_VALUE ? -1 : res; 22 | } 23 | public static void main(String[] args) { 24 | String str = "1-malayalam"; 25 | System.out.println(leftmostRepeating(str,str.length())); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Strings/LexicographicRankProblem.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | /** 4 | * @author Vishal Singh 5 | * Reference - Geeks for geeks 6 | */ 7 | public class LexicographicRankProblem { 8 | static int fact(int i){ 9 | if (i == 0 || i == 1){ 10 | return 1; 11 | } 12 | int fact = 1; 13 | for (int j = 2; j <= i; j++) { 14 | fact = fact*j; 15 | } 16 | return fact; 17 | } 18 | static int lexRank(String str){ 19 | int n = str.length(); 20 | int mul = fact(n); 21 | int rank = 1; 22 | int[] count = new int[256]; 23 | for (int i = 0; i < n; i++) { 24 | count[str.charAt(i)]++; 25 | } 26 | for (int i = 1; i < 256; i++) { 27 | count[i] += count[i-1]; 28 | } 29 | for (int i = 0; i < n; i++) { 30 | mul = mul/(n-i); 31 | rank += (count[str.charAt(i)-1]*mul); 32 | for (int j = str.charAt(i); j < 256; j++) { 33 | count[j]--; 34 | } 35 | } 36 | return rank; 37 | } 38 | public static void main(String[] args) { 39 | String str = "string"; 40 | System.out.println("Lex Rank of "+str+" is : "+lexRank(str)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Strings/PermutationOfPatternExist.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author Vishal Singh 7 | */ 8 | public class PermutationOfPatternExist { 9 | static boolean checkPattern(String string,String pattern){ 10 | int n = string.length(); 11 | int m = pattern.length(); 12 | int[] countPattern = new int[256]; 13 | int[] countString = new int[256]; 14 | 15 | for (int i = 0; i < pattern.length(); i++) { 16 | countPattern[pattern.charAt(i)]++; 17 | countString[string.charAt(i)]++; 18 | } 19 | for (int i = m; i < n; i++) { 20 | if (Arrays.equals(countPattern,countString)){ 21 | return true; 22 | } 23 | countString[string.charAt(i)]++; 24 | countString[string.charAt(i-m)]--; 25 | } 26 | return false; 27 | } 28 | public static void main(String[] args) { 29 | String s1 = "malayalam"; 30 | String pattern = "yamal"; //malay 31 | System.out.println(checkPattern(s1,pattern)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Strings/RotationOfStringOrNot.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class RotationOfStringOrNot { 7 | static boolean checkRotation(String s1,String s2){ 8 | if (s1.length() != s2.length()){ 9 | return false; 10 | } 11 | s1 += s1; 12 | return s1.contains(s2); // s1.indexOf(s2)>=0 13 | } 14 | public static void main(String[] args) { 15 | String str1 = "ABCD"; 16 | String str2 = "CDAB"; 17 | System.out.println(checkRotation(str1,str2)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Strings/SumOfNumberInString.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Strings; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class SumOfNumberInString { 7 | public static void main(String[] args) { 8 | String s = "1abc2x30yz67"; 9 | String regex = "[a-zA-Z]"; 10 | String[] arr = s.split(regex); 11 | long sum = 0; 12 | for (String value : arr) { 13 | if (!value.isEmpty()) 14 | sum += Long.parseLong(value); 15 | } 16 | System.out.println(sum); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Tree/BinaryTreeImplementation.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class BinaryTreeImplementation { 7 | static class Node{ 8 | int key; 9 | Node left; 10 | Node right; 11 | Node(int key){ 12 | this.key = key; 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | Node root = new Node(10); 18 | root.left = new Node(20); 19 | root.right = new Node(30); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Tree/HeightOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class HeightOfBinaryTree { 7 | static class Node{ 8 | int key; 9 | Node left,right; 10 | Node(int key){ 11 | this.key = key; 12 | } 13 | } 14 | static int getHeight(Node root){ 15 | if (root == null){ 16 | return 0; 17 | }else { 18 | return Math.max(getHeight(root.left),getHeight(root.right))+1; 19 | } 20 | } 21 | public static void main(String[] args) { 22 | Node root = new Node(10); 23 | root.left = new Node(20); 24 | root.left.left = new Node(60); 25 | root.left.left.left = new Node(70); 26 | root.left.left.left.left= new Node(90); 27 | root.left.left.left.right = new Node(80); 28 | root.left.left.left.right.left = new Node(100); 29 | 30 | root.right = new Node(30); 31 | root.right.left = new Node(40); 32 | root.right.left.left = new Node(500); 33 | root.right.left.left.left = new Node(180); 34 | root.right.left.left.left.left = new Node(280); 35 | root.right.left.left.left.left.right = new Node(500); 36 | 37 | root.right.right = new Node(50); 38 | root.right.right.right = new Node(900); 39 | System.out.println("Height binary tree is: "+ getHeight(root)); 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Tree/LowestCommonAncestor.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | import java.util.ArrayList; 4 | 5 | 6 | /** 7 | * @author Vishal Singh 8 | */ 9 | public class LowestCommonAncestor { 10 | static class Node { 11 | int key; 12 | Node left; 13 | Node right; 14 | 15 | Node(int key) { 16 | this.key = key; 17 | } 18 | } 19 | 20 | static boolean findPath(Node root, ArrayList path, int nm) { 21 | if (root == null) { 22 | return false; 23 | } 24 | path.add(root); 25 | if (root.key == nm) { 26 | return true; 27 | } 28 | if (findPath(root.left, path, nm) || findPath(root.right, path, nm)) { 29 | return true; 30 | } 31 | path.remove(path.size() - 1); 32 | return false; 33 | } 34 | 35 | static Node lowestCommonAncestor(Node root, int n, int m) { 36 | ArrayList path1 = new ArrayList<>(); 37 | ArrayList path2 = new ArrayList<>(); 38 | if (!findPath(root, path1, n) || !findPath(root, path2, m)) { 39 | return null; 40 | } 41 | for (int i = 0; i < path1.size() && i < path2.size(); i++) { 42 | if (path1.get(i + 1) != path2.get(i + 1)) { 43 | return path1.get(i); 44 | } 45 | } 46 | return null; 47 | } 48 | 49 | public static void main(String[] args) { 50 | Node t = new Node(10); 51 | 52 | t.left = new Node(50); 53 | t.right = new Node(60); 54 | 55 | t.left.left = new Node(70); 56 | t.left.right = new Node(20); 57 | 58 | t.left.left.left = new Node(40); 59 | t.left.right.left = new Node(90); 60 | t.left.right.left.left = new Node(30); 61 | 62 | t.left.right.right = new Node(80); 63 | 64 | /* 65 | {10} 66 | / \ 67 | {50} {60} 68 | / \ 69 | {70} {20} 70 | / / \ 71 | {40} {90} {80} 72 | / 73 | {30} 74 | */ 75 | Node lca = lowestCommonAncestor(t,30,80); 76 | if (lca==null) 77 | System.out.println("Not found"); 78 | else 79 | System.out.println(lca.key); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Tree/MaxInBinaryTree.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class MaxInBinaryTree { 7 | static class Node{ 8 | int key; 9 | Node left,right; 10 | Node(int key){ 11 | this.key = key; 12 | } 13 | } 14 | static int getMaxInBinary(Node root){ 15 | if (root == null){ 16 | return Integer.MIN_VALUE; 17 | }else { 18 | return Math.max(root.key, Math.max(getMaxInBinary(root.left),getMaxInBinary(root.right))); 19 | } 20 | } 21 | public static void main(String[] args) { 22 | Node root = new Node(10); 23 | root.left = new Node(20); 24 | root.left.left = new Node(60); 25 | root.left.left.left = new Node(70); 26 | root.left.left.left.left= new Node(90); 27 | root.left.left.left.right = new Node(80); 28 | root.left.left.left.right.left = new Node(100); 29 | 30 | root.right = new Node(30); 31 | root.right.left = new Node(40); 32 | root.right.left.left = new Node(500); 33 | root.right.left.left.left = new Node(180); 34 | root.right.left.left.left.left = new Node(280); 35 | root.right.left.left.left.left.right = new Node(500); 36 | 37 | root.right.right = new Node(50); 38 | root.right.right.right = new Node(900); 39 | 40 | System.out.println("Max in binary tree is: "+ getMaxInBinary(root)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Tree/MorrisTraversal.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | * 7/27/2021 6 | */ 7 | public class MorrisTraversal { 8 | 9 | } -------------------------------------------------------------------------------- /Tree/PrintNodeAtDistK.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class PrintNodeAtDistK { 7 | static class Node{ 8 | int key; 9 | Node left,right; 10 | Node(int key){ 11 | this.key = key; 12 | } 13 | } 14 | /*Recursive*/ 15 | static void printKDist(Node root, int k){ 16 | if (root == null){ 17 | return; 18 | } 19 | if (k == 0){ 20 | System.out.print(root.key+" "); 21 | } 22 | else { 23 | printKDist(root.left,k-1); 24 | printKDist(root.right,k-1); 25 | } 26 | } 27 | public static void main(String[] args) { 28 | Node root = new Node(10); 29 | root.left = new Node(20); 30 | root.left.left = new Node(60); 31 | root.left.left.left = new Node(70); 32 | root.left.left.left.left= new Node(90); 33 | root.left.left.left.right = new Node(80); 34 | root.left.left.left.right.left = new Node(100); 35 | 36 | root.right = new Node(30); 37 | root.right.left = new Node(40); 38 | root.right.left.left = new Node(500); 39 | root.right.left.left.left = new Node(180); 40 | root.right.left.left.left.left = new Node(280); 41 | root.right.left.left.left.left.right = new Node(500); 42 | 43 | root.right.right = new Node(50); 44 | root.right.right.right = new Node(900); 45 | 46 | printKDist(root,4); 47 | System.out.println(); 48 | printKDist(root,5); 49 | System.out.println(); 50 | printKDist(root,1); 51 | System.out.println(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Tree/SizeOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class SizeOfBinaryTree { 7 | static class Node{ 8 | int key; 9 | Node left; 10 | Node right; 11 | Node(int key){ 12 | this.key = key; 13 | } 14 | } 15 | static int getSizeOfBinaryTree(Node root){ 16 | if (root == null){ 17 | return 0; 18 | }else { 19 | return 1+getSizeOfBinaryTree(root.left)+getSizeOfBinaryTree(root.right); 20 | } 21 | } 22 | public static void main(String[] args) { 23 | Node root = new Node(10); 24 | 25 | root.left = new Node(20); 26 | root.left.left = new Node(40); 27 | root.left.right = new Node(50); 28 | 29 | root.right = new Node(30); 30 | 31 | System.out.println("SizeOfBinaryTree: "+getSizeOfBinaryTree(root)); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Tree/TreeTraversal.java: -------------------------------------------------------------------------------- 1 | package SummerTrainingGFG.Tree; 2 | 3 | /** 4 | * @author Vishal Singh 5 | */ 6 | public class TreeTraversal { 7 | static class Node{ 8 | int key; 9 | Node left; 10 | Node right; 11 | Node(int key){ 12 | this.key = key; 13 | } 14 | } 15 | static void inOrder(Node root){ 16 | //Left Root Right 17 | if (root!=null){ 18 | inOrder(root.left); 19 | System.out.print(root.key+" "); 20 | inOrder(root.right); 21 | } 22 | } 23 | static void postOrder(Node root){ 24 | //Left Right Root 25 | if (root!=null){ 26 | postOrder(root.left); 27 | postOrder(root.right); 28 | System.out.print(root.key+" "); 29 | } 30 | } 31 | static void preOrder(Node root){ 32 | //Root Left Right 33 | if (root!=null){ 34 | System.out.print(root.key+" "); 35 | preOrder(root.left); 36 | preOrder(root.right); 37 | } 38 | } 39 | public static void main(String[] args) { 40 | Node root = new Node(10); 41 | 42 | root.left = new Node(20); 43 | root.left.left = new Node(40); 44 | root.left.right = new Node(50); 45 | 46 | root.right = new Node(30); 47 | System.out.println("In Order"); 48 | inOrder(root); 49 | System.out.println("\nPost Order"); 50 | postOrder(root); 51 | System.out.println("\nPre Order"); 52 | preOrder(root); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect -------------------------------------------------------------------------------- /trie/MostFrequentWord.java: -------------------------------------------------------------------------------- 1 | package trie; 2 | 3 | /** 4 | * @author Vishal Singh 5 | * 7/23/2021 6 | * @link https://practice.geeksforgeeks.org/problems/most-frequent-word-in-an-array-of-strings3528/1 7 | */ 8 | public class MostFrequentWord { 9 | class Solution { 10 | class Trie { 11 | int freq; 12 | boolean isEnd; 13 | Trie[] children = new Trie[26]; 14 | } 15 | int max = 0; 16 | String mostFrequent = ""; 17 | void insert(Trie root,String word) { 18 | Trie curr = root; 19 | for (char ch: word.toCharArray()) { 20 | if (curr.children[ch-'a'] == null) { 21 | curr.children[ch-'a'] = new Trie(); 22 | } 23 | curr = curr.children[ch-'a']; 24 | } 25 | curr.isEnd = true; 26 | curr.freq++; 27 | if (curr.freq > max) { 28 | mostFrequent = word; 29 | max = curr.freq; 30 | } 31 | } 32 | public String mostFrequentWord(String arr[], int n) { 33 | max = 0; 34 | mostFrequent = ""; 35 | Trie root = new Trie(); 36 | for (String word: arr) { 37 | insert(root,word); 38 | } 39 | return mostFrequent; 40 | } 41 | } 42 | /* 43 | Corner Test Case: 44 | 17 45 | xejdcj xejdcj lvjpb tmyuiu lvjpb tmyuiu ovoba lvjpb lvjpb fqhyu fqhyu tmyuiu xejdcj tmyuiu fqhyu ovoba xejdcj 46 | * */ 47 | } --------------------------------------------------------------------------------