├── Basic Concepts ├── Algorithms │ ├── Dynamic Programming │ │ ├── Dynamic Programming.gdoc │ │ ├── EditDistance.java │ │ ├── FibonacciNumberDP.java │ │ ├── FibonacciNumberWithRecursion.java │ │ ├── FibonacciSeriesWithRecursion.java │ │ ├── FibonacciSeriesWithoutRecursion.java │ │ └── MinCostPath.java │ ├── Game Theory │ │ └── MiniMax.cpp │ ├── Graph Algorithms │ │ ├── AdjacencyListUndirected.java │ │ ├── AdjacencyMatrixDirected.java │ │ ├── AdjacencyMatrixUndirected.java │ │ ├── BFSDirected.java │ │ ├── BFSUndirected.java │ │ ├── ConnectedComponentsUndirectedGraph.java │ │ ├── DFSDirected.java │ │ ├── DetectCycleInUndirectedGraphUsingUnionFind.java │ │ └── Graph Theory.gdoc │ ├── Greedy Algorithms │ │ ├── GreedyAlgorithms.txt │ │ ├── HuffmanCoding.java │ │ ├── KruskalMST.java │ │ ├── SortedActivitySelectionProblem.java │ │ └── UnsortedActivitySelectionProblem.java │ ├── Mathematics │ │ ├── Combinations.cpp │ │ ├── ModifiedSieveOfEratosthenes.cpp │ │ ├── PrimeFactors.cpp │ │ └── SieveOfEratosthenes.cpp │ ├── Other Algorithms │ │ ├── 3SumProblem.java │ │ └── MaximumElementinBitonic.java │ ├── Recursion │ │ ├── Factorial.java │ │ ├── PermutationsOfAGivenString.java │ │ ├── PermutationsOfAGivenString2.java │ │ ├── RecursionEx1.cpp │ │ └── SelectionSortRecursive.java │ └── Sorting Algorithms │ │ ├── BubbleSort.java │ │ ├── CountingSort.java │ │ ├── InsertionSort.java │ │ ├── IterativeMergeSort.java │ │ ├── IterativeQuickSort.java │ │ ├── MergeSort.java │ │ ├── MergeSortLinkedList.java │ │ ├── QuickSort.java │ │ ├── RadixSort.java │ │ ├── RecursiveInsertionSort.java │ │ ├── RecusiveBubbleSort.java │ │ ├── SelectionSort.java │ │ ├── Sort - practice.java │ │ └── Sorting Algorithms.gdoc ├── Data Structures │ ├── BinaryHeap.java │ ├── Data Structures.gdoc │ ├── DisjointSet.java │ ├── HashTable.java │ ├── LinkedList.java │ ├── LinkedListOperations.java │ ├── StackUsingArray.java │ ├── StackUsingSTL.cpp │ └── TreeDS.java └── Strings.gdoc ├── CodeChef ├── July Cook Off │ ├── Chang and Bitwise OR.java │ └── Chang and the Perfect Function.java └── SeptemberLongChallenge │ ├── ChefAndPickDigit.java │ ├── LittleChefAndSums.java │ ├── MinimumGoodPermutation.java │ └── SerejaAndCommands.java ├── FastIO.cpp ├── FastIO.java ├── GeeksForGeeks └── Algorithms │ ├── CheckForSubsequence.cpp │ ├── DetectCycleInDirectedGraph.java │ ├── EditDistance.java │ ├── FloydTortoiseAndHare.java │ ├── HighestPrime.cpp │ ├── LargestEvenNumber.java │ ├── LargestPrimeFactor.cpp │ ├── LeastPrimeFactor.cpp │ ├── NMeetingsInOneRoom.java │ ├── NodesAtEvenDistance.java │ ├── PalindromeString.java │ ├── PathInMatrix.java │ ├── SortTheArray.java │ ├── SumOfDigitIsPalindromeOrNot.java │ └── XTotalShapes.java ├── HackerEarth ├── CodeMonk │ ├── BasicsOfInputOutput │ │ ├── Anagrams.c │ │ ├── AsciiValue.c │ │ ├── CountDivisors.c │ │ ├── Factorial.c │ │ ├── FindProduct.c │ │ ├── MagicalWord.c │ │ ├── PalindromicString.c │ │ ├── PlayWithNumbers.cpp │ │ ├── PrimeNumber.c │ │ ├── RoyAndProfilePicture.c │ │ ├── SeatingArrangement.c │ │ └── ToggleString.c │ └── BitManipulation │ │ ├── LargestPower.cpp │ │ ├── RajanAndOddFrequency.cpp │ │ └── SubsetsOfGivenSet.cpp ├── HiringChallenges │ ├── FindTheString.java │ ├── FindTheString.py │ ├── FredoAndTwoStrings.cpp │ └── FredoAndTwoStrings.java └── challenges │ ├── AlexAndPriorityQueues.java │ ├── AlexAndRequests.java │ ├── BricksAndBuildings.cpp │ ├── CoinGame.cpp │ ├── CrazyMatrix.java │ ├── CrushingViolence.java │ ├── Decode.java │ ├── DexterAndPoints.png │ ├── DisconnectedGraph.java │ ├── FizzBuzzTest.cpp │ ├── FizzBuzzTest.java │ ├── FredoAndArrayUpdate.java │ ├── InheritancePuzzle.java │ ├── KDevices.java │ ├── KingArthursKingdom.png │ ├── LittleShinoAndCommonFactors.java │ ├── LittleShinoAndNumberOfDivisors.cpp │ ├── MathisonAndTheMedicalFacilities.cpp │ ├── MissingNumber.cpp │ ├── PolicemenAndThieves.c │ ├── PolicemenAndThieves.cpp │ ├── RastaAndTavas.cpp │ ├── RhezoAndBigPowers.java │ ├── RoyAndTrains.java │ ├── RoyAndWobblyNumbers.java │ ├── SherlockAndDates.java │ ├── SumOfSubsets.java │ ├── TheBestPlayer.java │ └── XSquareAndTwoArrays.java ├── HackerRank ├── Algorithms │ ├── Dynamic Programming │ │ ├── FibonacciModified.java │ │ ├── TheCoinChangeProblemDP.java │ │ └── TheCoinChangeProblemRecursive.java │ ├── Graph Theory │ │ ├── JourneyToTheMoon.java │ │ └── RoadsAndLibraries.java │ ├── Recursion │ │ ├── RecursiveDigitSum.java │ │ └── ThePowerSum.java │ ├── Sorting │ │ ├── BigSorting.java │ │ ├── InsertionSort1.java │ │ └── InsertionSort2.java │ ├── Strings │ │ ├── Anagram.java │ │ ├── BeautifulBinaryString.java │ │ ├── GameOfThrones1.java │ │ ├── Gemstones.java │ │ ├── MakingAnagrams.java │ │ ├── MarsExploration.java │ │ ├── TheLoveLetterMystery.java │ │ └── TwoStrings.java │ └── prime.py └── DataStructures │ └── Arrays │ └── SparseArrays.java ├── Interview └── Microsoft │ └── RemoveReduntantPoints.java ├── LeetCode └── Dynamic Programming │ └── ClimbingStairsBruteForce.java ├── TopCoder └── RecusionBasic.java └── readme.md /Basic Concepts/Algorithms/Dynamic Programming/Dynamic Programming.gdoc: -------------------------------------------------------------------------------- 1 | {"url": "https://docs.google.com/open?id=1NM9aT676WnBku2s7JxXcj3DAjCv-blLLrDEMrhhy4LQ", "doc_id": "1NM9aT676WnBku2s7JxXcj3DAjCv-blLLrDEMrhhy4LQ", "email": "deepaksood619@gmail.com", "resource_id": "document:1NM9aT676WnBku2s7JxXcj3DAjCv-blLLrDEMrhhy4LQ"} -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Dynamic Programming/EditDistance.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/ 2 | 3 | /* 4 | Also called as Lavenshtein Distance 5 | The Levenshtein distance, or edit distance, is the amount by which two strings differ. 6 | 7 | Operations - 8 | 1. Insert (Addition) 9 | 2. Remove (Deletion) 10 | 3. Replace (Modification) 11 | 12 | Algorithm - 13 | // if either of the strings 14 | // is empty 15 | levd(i,j) = max(i,j) 16 | 17 | // if the last character of 18 | // both substrings match 19 | // s1[i] == s2[j] 20 | levd(i,j) = min(levd(i-1,j), 21 | levd(i,j-1), 22 | levd(i-1,j-1)) 23 | 24 | // in any other case 25 | levd(i,j) = min(levd(i-1,j)+1, 26 | levd(i,j-1)+1, 27 | levd(i-1,j-1)+1) 28 | 29 | Time Complexity - O(3^m) operations 30 | The worst case happens when none of characters of two strings match. 31 | 32 | Dynamic Programming - Use an auxillary array to store the computed values. 33 | Overlapping Subproblems 34 | - Memoization (Top Down approach) 35 | - Tabulation (Bottom Up approach) 36 | Optimal Substructure 37 | 38 | Solved using Memoization method (Top Down approach) 39 | 40 | Time Complexity: O(m x n) 41 | Auxiliary Space: O(m x n) 42 | 43 | */ 44 | 45 | class EditDistance { 46 | 47 | static int[][] arr; 48 | 49 | public static int min( int x, int y, int z ) { 50 | if ( x < y ) 51 | return x < z ? x : z; 52 | else 53 | return y < z ? y : z; 54 | } 55 | 56 | public static int editDist( String str1, String str2, int m, int n ) { 57 | for(int i = 0; i <= m; i++) { 58 | for(int j = 0; j <= n; j++) { 59 | if(i==0) 60 | arr[i][j] = j; 61 | 62 | else if(j == 0) 63 | arr[i][j] = i; 64 | 65 | else if(str1.charAt(i-1) == str2.charAt(j-1)) 66 | arr[i][j] = arr[i-1][j-1]; 67 | 68 | else 69 | arr[i][j] = 1 + min(arr[i-1][j], arr[i-1][j-1], arr[i][j-1]); 70 | } 71 | } 72 | return arr[m][n]; 73 | } 74 | 75 | public static void main(String[] args) { 76 | String str1 = "sitting"; 77 | String str2 = "kitten"; 78 | 79 | arr = new int[str1.length() + 1][str2.length() + 1]; 80 | 81 | System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) ); 82 | } 83 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Dynamic Programming/FibonacciNumberDP.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ 2 | 3 | /* 4 | We can avoid the repeated work done is the method 1 by storing the Fibonacci numbers calculated so far. 5 | 6 | Time Complexity - O(n) 7 | Space Complexity - O(n) 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | class FibonacciNumberDP { 13 | 14 | static int fib(int n) { 15 | 16 | /* Declare an array to store Fibonacci numbers. */ 17 | int[] f = new int[n + 1]; 18 | int i; 19 | f[0] = 0; 20 | f[1] = 1; 21 | 22 | for(i = 2; i <= n; i++) { 23 | /* Add the previous 2 numbers in the series 24 | and store it */ 25 | f[i] = f[i-1] + f[i-2]; 26 | } 27 | 28 | return f[n]; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Scanner in = new Scanner(System.in); 33 | System.out.print("Enter num - "); 34 | int count = in.nextInt(); 35 | 36 | System.out.println(fib(count)); 37 | } 38 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Dynamic Programming/FibonacciNumberWithRecursion.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ 2 | 3 | /* 4 | In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1. 5 | 6 | There are two ways to write the fibonacci series program in java: 7 | 8 | 1. Fibonacci Series without using recursion 9 | 2. Fibonacci Series using recursion 10 | 11 | Starting element = 0 12 | 13 | Time Complexity - T(n) = T(n-1) + T(n-2) which is exponential. - O(2^N) 14 | Space Complexity - O(n) if we consider the function call stack size, otherwise O(1). 15 | */ 16 | 17 | import java.util.Scanner; 18 | 19 | class FibonacciNumberWithRecursion { 20 | 21 | static int fib(int count) { 22 | if(count <= 0) { 23 | return 0; 24 | } else if(count == 1) { 25 | return 1; 26 | } 27 | else { 28 | return fib(count - 1) + fib(count - 2); 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | Scanner in = new Scanner(System.in); 34 | 35 | System.out.print("Enter num of elements: "); 36 | int count = in.nextInt(); 37 | System.out.println(fib(count)); 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Dynamic Programming/FibonacciSeriesWithRecursion.java: -------------------------------------------------------------------------------- 1 | /* 2 | In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1. 3 | 4 | There are two ways to write the fibonacci series program in java: 5 | 6 | 1. Fibonacci Series without using recursion 7 | 2. Fibonacci Series using recursion 8 | 9 | Starting element = 0 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | class FibonacciSeriesWithRecursion { 15 | 16 | static int n1 = 0, n2 = 1, n3; 17 | 18 | static void printFibonacci(int count) { 19 | if(count > 0) { 20 | n3 = n1 + n2; 21 | n1 = n2; 22 | n2 = n3; 23 | System.out.print(" " + n3); 24 | printFibonacci(count - 1); 25 | } 26 | } 27 | 28 | public static void main(String[] args) { 29 | Scanner in = new Scanner(System.in); 30 | 31 | System.out.print("Enter num of elements: "); 32 | System.out.println(); 33 | int count = in.nextInt(); 34 | if(count <= 1) { 35 | System.out.println("0"); 36 | } 37 | if(count >= 2) { 38 | System.out.print(n1 + " " + n2); 39 | printFibonacci(count - 2); 40 | } 41 | 42 | } 43 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Dynamic Programming/FibonacciSeriesWithoutRecursion.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ 2 | 3 | /* 4 | In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1. 5 | 6 | There are two ways to write the fibonacci series program in java: 7 | 8 | 1. Fibonacci Series without using recursion 9 | 2. Fibonacci Series using recursion 10 | 11 | improvement on the FibonacciNumberDP in terms of space complexity, 12 | since we only need the last two numbers for generating the next number, 13 | we store only last two values. 14 | 15 | Time Complexity - O(n) 16 | Space Complexity - O(1) 17 | */ 18 | 19 | import java.util.Scanner; 20 | 21 | class FibonacciSeriesWithoutRecursion { 22 | 23 | static int fib(int n) { 24 | int n1 = 0, n2 = 1, n3; 25 | if(n == 0) { 26 | return n1; 27 | } 28 | // for printing the series 29 | System.out.print(n2); 30 | 31 | for(int i = 2; i <= n; i++) { 32 | n3 = n1 + n2; 33 | System.out.print(" " + n3); 34 | n1 = n2; 35 | n2 = n3; 36 | } 37 | return n2; 38 | } 39 | 40 | public static void main(String[] args) { 41 | 42 | Scanner in = new Scanner(System.in); 43 | 44 | System.out.print("Enter num of elements to see in fibonacci series -"); 45 | int num = in.nextInt(); 46 | 47 | /* for printing only the nth number */ 48 | //System.out.println(fib(num)); 49 | 50 | /* for printing all the number in series */ 51 | fib(num); 52 | } 53 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Dynamic Programming/MinCostPath.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/ 2 | 3 | /* 4 | Time Complexity - O(mn) 5 | */ 6 | 7 | class MinCostPath { 8 | public static void main(String[] args) { 9 | int[][] cost = new int[][] {{1,2,3},{4,8,2},{1,5,3}}; 10 | int[][] minCostArr = new int[3][3]; 11 | 12 | System.out.println(minCost(cost, minCostArr, 2, 2)); 13 | } 14 | 15 | static int minCost(int[][] cost, int[][] minCostArr, int x, int y) { 16 | if(x < 0 || y < 0) { 17 | return Integer.MAX_VALUE; 18 | } else if(x == 0 && y == 0) { 19 | return cost[x][y]; 20 | } else if(minCostArr[x][y] != 0) { 21 | return minCostArr[x][y]; 22 | } else { 23 | minCostArr[x][y] = cost[x][y] + min(minCost(cost, minCostArr, x-1, y), minCost(cost, minCostArr, x, y-1), minCost(cost, minCostArr, x-1, y-1)); 24 | return minCostArr[x][y]; 25 | } 26 | } 27 | 28 | static int min(int x, int y, int z) { 29 | if(x < y) 30 | return (x < z) ? x : z; 31 | else 32 | return (y < z) ? y : z; 33 | } 34 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Game Theory/MiniMax.cpp: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/ 2 | 3 | // A simple C++ program to find maximum score that 4 | // maximizing player can get. 5 | #include 6 | using namespace std; 7 | 8 | // Returns the optimal value a maximizer can obtain. 9 | // depth is current depth in game tree. 10 | // nodeIndex is index of current node in scores[]. 11 | // isMax is true if current move is of maximizer, else false 12 | // scores[] stores leaves of Game tree. 13 | // h is maximum height of Game tree 14 | int minimax(int depth, int nodeIndex, bool isMax, 15 | int scores[], int h) 16 | { 17 | // Terminating condition. i.e leaf node is reached 18 | if (depth == h) 19 | return scores[nodeIndex]; 20 | 21 | // If current move is maximizer, find the maximum attainable 22 | // value 23 | if (isMax) 24 | return max(minimax(depth+1, nodeIndex*2, false, scores, h), 25 | minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); 26 | 27 | // Else (If current move is Minimizer), find the minimum 28 | // attainable value 29 | else 30 | return min(minimax(depth+1, nodeIndex*2, true, scores, h), 31 | minimax(depth+1, nodeIndex*2 + 1, true, scores, h)); 32 | } 33 | 34 | // A utility function to find Log n in base 2 35 | int log2(int n) { 36 | return (n==1)? 0 : 1 + log2(n/2); 37 | } 38 | 39 | // Driver code 40 | int main() 41 | { 42 | // The number of elements in scores must be 43 | // a power of 2. 44 | int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; 45 | int n = sizeof(scores)/sizeof(scores[0]); 46 | int h = log2(n); 47 | int res = minimax(0, 0, true, scores, h); 48 | cout << "The optimal value is : " << res << endl; 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/AdjacencyListUndirected.java: -------------------------------------------------------------------------------- 1 | /* 2 | Adjacency list for undirected graph 3 | v - vertex, e - edge 4 | */ 5 | 6 | import java.util.Scanner; 7 | import java.util.ArrayList; 8 | 9 | class AdjacencyListUndirected { 10 | public static void main(String[] args) { 11 | 12 | Scanner in = new Scanner(System.in); 13 | 14 | int v = in.nextInt(); 15 | int e = in.nextInt(); 16 | 17 | ArrayList> arr = new ArrayList>(); 18 | 19 | for( int i = 0; i < v; i++) { 20 | ArrayList arrList = new ArrayList<>(); 21 | arr.add(arrList); 22 | } 23 | 24 | for(int i = 0; i < e; i++) { 25 | int m = in.nextInt(); 26 | int n = in.nextInt(); 27 | 28 | ArrayList arrList = arr.get(m); 29 | arrList.add(n); 30 | arr.set(m, arrList); 31 | 32 | ArrayList arrListReverse = arr.get(n); 33 | arrListReverse.add(m); 34 | arr.set(n, arrListReverse); 35 | } 36 | 37 | int k = 0; 38 | for(ArrayList list : arr) { 39 | System.out.print(k + " - "); 40 | for(Integer item : list) { 41 | System.out.print(item + " "); 42 | } 43 | System.out.println(); 44 | k++; 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/AdjacencyMatrixDirected.java: -------------------------------------------------------------------------------- 1 | /* 2 | Adjacency matrix for a directed graph 3 | v - vertex, e - edges 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | class AdjacencyMatrixDirected { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | int i, j; 13 | 14 | int v = in.nextInt(); 15 | int e = in.nextInt(); 16 | 17 | int[][] matrix = new int[v][v]; 18 | 19 | for(i = 0; i < v; i++) { 20 | matrix[i][i] = 1; 21 | } 22 | 23 | for(i = 0; i < v; i++) { 24 | int m = in.nextInt(); 25 | int n = in.nextInt(); 26 | 27 | matrix[m-1][n-1] = 1; 28 | } 29 | 30 | for(i = 0; i < v; i++) { 31 | for(j = 0; j < v; j++) { 32 | System.out.print(matrix[i][j]); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/AdjacencyMatrixUndirected.java: -------------------------------------------------------------------------------- 1 | /* 2 | AdjacencyMatrix for un undirected graph 3 | v = number of vertices 4 | e = number of edges 5 | 3 3 (v,e) 6 | 1 2 (e1, e2) 7 | 2 3 (e1, e2) 8 | 3 1 (e1, e2) 9 | 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | class AdjacencyMatrixUndirected { 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | 18 | int v = in.nextInt(); 19 | int e = in.nextInt(); 20 | 21 | int[][] matrix = new int[v][v]; 22 | for(int i = 0; i < v; i++) { 23 | matrix[i][i] = 1; 24 | } 25 | 26 | for(int i = 0; i < e; i++) { 27 | int m = in.nextInt(); 28 | int n = in.nextInt(); 29 | 30 | matrix[m-1][n-1] = 1; 31 | matrix[n-1][m-1] = 1; 32 | } 33 | 34 | for(int i = 0; i < v; i++) { 35 | for (int j = 0; j < v; j++) { 36 | System.out.print(matrix[i][j] + " "); 37 | } 38 | System.out.println(); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/BFSDirected.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/ 2 | 3 | import java.util.LinkedList; 4 | import java.util.Iterator; 5 | 6 | class BFSDirected { 7 | 8 | int numOfVertices; 9 | LinkedList[] adjacencyList; 10 | 11 | BFSDirected(int numOfVertices) { 12 | this.numOfVertices = numOfVertices; 13 | adjacencyList = new LinkedList[numOfVertices]; 14 | 15 | while(numOfVertices-- > 0) { 16 | adjacencyList[numOfVertices] = new LinkedList<>(); 17 | } 18 | } 19 | 20 | void addEdge(int v, int w) { 21 | adjacencyList[v].add(w); 22 | } 23 | 24 | void bfs(int s) { 25 | 26 | boolean[] visited = new boolean[numOfVertices]; 27 | 28 | LinkedList queue = new LinkedList<>(); 29 | 30 | queue.add(s); 31 | visited[s] = true; 32 | 33 | while(queue.size() != 0) { 34 | 35 | s = queue.poll(); 36 | 37 | System.out.print(s + " "); 38 | 39 | // now get the neighbors and add it to queue 40 | // using iterator 41 | Iterator i = adjacencyList[s].listIterator(); 42 | while(i.hasNext()) { 43 | int n = i.next(); 44 | if(!visited[n]) { 45 | queue.add(n); 46 | visited[n] = true; 47 | } 48 | } 49 | 50 | 51 | // using loop 52 | /*for( int i = 0; i < adjacencyList[s].size(); i++) { 53 | if(!visited[adjacencyList[s].get(i)]) { 54 | queue.add(adjacencyList[s].get(i)); 55 | visited[adjacencyList[s].get(i)] = true; 56 | } 57 | }*/ 58 | } 59 | } 60 | 61 | void print() { 62 | for(int i = 0; i < adjacencyList.length; i++) { 63 | System.out.print(i + " - "); 64 | for(int j = 0; j < adjacencyList[i].size(); j++) { 65 | System.out.print(adjacencyList[i].get(j) + " "); 66 | } 67 | System.out.println(); 68 | } 69 | } 70 | 71 | public static void main(String[] args) { 72 | 73 | BFSDirected bfsDirected = new BFSDirected(4); 74 | bfsDirected.addEdge(0, 1); 75 | bfsDirected.addEdge(0, 2); 76 | bfsDirected.addEdge(1, 2); 77 | bfsDirected.addEdge(2, 0); 78 | bfsDirected.addEdge(2, 3); 79 | bfsDirected.addEdge(3, 3); 80 | 81 | bfsDirected.print(); 82 | 83 | bfsDirected.bfs(2); 84 | 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/BFSUndirected.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/ 2 | 3 | import java.util.LinkedList; 4 | import java.util.Iterator; 5 | 6 | class BFSUndirected { 7 | 8 | int numOfVertices; 9 | 10 | LinkedList adjacencyList[]; 11 | 12 | BFSUndirected(int numOfVertices) { 13 | this.numOfVertices = numOfVertices; 14 | adjacencyList = new LinkedList[numOfVertices]; 15 | while(numOfVertices-- > 0) { 16 | adjacencyList[numOfVertices] = new LinkedList(); 17 | } 18 | } 19 | 20 | void addEdge(int v1, int v2) { 21 | adjacencyList[v1].add(v2); 22 | adjacencyList[v2].add(v1); 23 | } 24 | 25 | void printGraph() { 26 | for(int i = 0; i < adjacencyList.length; i++) { 27 | System.out.print(i + " - "); 28 | for(int j = 0; j < adjacencyList[i].size(); j++) { 29 | System.out.print(adjacencyList[i].get(j) + " "); 30 | } 31 | System.out.println(); 32 | } 33 | } 34 | 35 | void bfs(int s) { 36 | 37 | boolean[] visited = new boolean[numOfVertices]; 38 | 39 | LinkedList queue = new LinkedList<>(); 40 | 41 | visited[s] = true; 42 | queue.add(s); 43 | 44 | while(queue.size() != 0) { 45 | s = queue.poll(); 46 | System.out.print(s + " "); 47 | 48 | // now find the neighbors and add it to queue 49 | 50 | //using Iterator 51 | Iterator i = adjacencyList[s].listIterator(); 52 | while(i.hasNext()) { 53 | int n = i.next(); 54 | if(!visited[n]) { 55 | visited[n] = true; 56 | queue.add(n); 57 | } 58 | } 59 | 60 | // using adjacencyList directly 61 | /* for(int i = 0; i < adjacencyList[s].size(); i++) { 62 | if(!visited[adjacencyList[s].get(i)]) { 63 | queue.add(adjacencyList[s].get(i)); 64 | visited[adjacencyList[s].get(i)] = true; 65 | } 66 | } */ 67 | } 68 | } 69 | 70 | public static void main(String[] args) { 71 | System.out.println("BFS"); 72 | 73 | BFSUndirected bfsUndirected = new BFSUndirected(4); 74 | 75 | bfsUndirected.addEdge(0, 1); 76 | bfsUndirected.addEdge(0, 2); 77 | bfsUndirected.addEdge(1, 2); 78 | bfsUndirected.addEdge(2, 0); 79 | bfsUndirected.addEdge(2, 3); 80 | bfsUndirected.addEdge(3, 3); 81 | 82 | bfsUndirected.printGraph(); 83 | 84 | bfsUndirected.bfs(2); 85 | 86 | } 87 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/ConnectedComponentsUndirectedGraph.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/ 2 | 3 | /* 4 | using bfs 5 | 6 | SpaceComplexity - O(|V|), since at worst case you need to hold all vertices in the queue. 7 | 8 | TimeComplexity - O(|V + E|) where |V| is the number of nodes, you need to traverse all nodes. 9 | */ 10 | 11 | import java.util.LinkedList; 12 | 13 | class ConnectedComponentsUndirectedGraph { 14 | 15 | LinkedList[] arrList; 16 | boolean[] visited; 17 | int numOfVertices; 18 | 19 | ConnectedComponentsUndirectedGraph(int numOfVertices) { 20 | this.numOfVertices = numOfVertices; 21 | arrList = new LinkedList[numOfVertices]; 22 | visited = new boolean[numOfVertices]; 23 | 24 | for(int i = 0; i < numOfVertices; i++) { 25 | arrList[i] = new LinkedList<>(); 26 | } 27 | } 28 | 29 | void addEdge(int v, int w) { 30 | arrList[v].add(w); 31 | arrList[w].add(v); 32 | } 33 | 34 | void print() { 35 | for(int i = 0; i < arrList.length; i++) { 36 | System.out.print(i + " - "); 37 | for(int j = 0; j < arrList[i].size(); j++) { 38 | System.out.print(arrList[i].get(j) + " "); 39 | } 40 | System.out.println(); 41 | } 42 | } 43 | 44 | void connectedComponent() { 45 | for(int i = 0; i < visited.length; i++) { 46 | if(!visited[i]) { 47 | bfs(i); 48 | System.out.println(); 49 | } 50 | } 51 | } 52 | 53 | void bfs(int s) { 54 | LinkedList queue = new LinkedList<>(); 55 | 56 | visited[s] = true; 57 | queue.add(s); 58 | 59 | while(queue.size() != 0) { 60 | s = queue.poll(); 61 | 62 | System.out.print(s + " "); 63 | 64 | for(int i = 0; i < arrList[s].size(); i++) { 65 | if(!visited[arrList[s].get(i)]) { 66 | queue.add(arrList[s].get(i)); 67 | visited[arrList[s].get(i)] = true; 68 | } 69 | } 70 | } 71 | } 72 | 73 | public static void main(String[] args) { 74 | System.out.println("Connected Components in an Undirected Graph"); 75 | 76 | ConnectedComponentsUndirectedGraph object = new ConnectedComponentsUndirectedGraph(5); 77 | object.addEdge(0, 1); 78 | object.addEdge(2, 0); 79 | object.addEdge(3, 4); 80 | 81 | object.print(); 82 | 83 | object.connectedComponent(); 84 | } 85 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/DFSDirected.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph/ 2 | 3 | /* 4 | Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph. 5 | */ 6 | 7 | import java.util.LinkedList; 8 | 9 | class DFSDirected { 10 | 11 | int numOfVertices; 12 | LinkedList[] adjList; 13 | 14 | DFSDirected(int numOfVertices) { 15 | this.numOfVertices = numOfVertices; 16 | 17 | adjList = new LinkedList[numOfVertices]; 18 | 19 | for(int i = 0; i < numOfVertices; i++) { 20 | adjList[i] = new LinkedList(); 21 | } 22 | } 23 | 24 | void addEdge(int u, int v) { 25 | adjList[u].add(v); 26 | } 27 | 28 | void DFSUtil(int v, boolean[] visited) { 29 | visited[v] = true; 30 | System.out.print(v + " "); 31 | 32 | for(int i = 0; i < adjList[v].size(); i++) { 33 | int n = adjList[v].get(i); 34 | if(!visited[n]) { 35 | DFSUtil(n, visited); 36 | } 37 | } 38 | } 39 | 40 | void dfs(int s) { 41 | boolean[] visited = new boolean[numOfVertices]; 42 | 43 | DFSUtil(s, visited); 44 | } 45 | 46 | void dfsAll() { 47 | boolean[] visited = new boolean[numOfVertices]; 48 | 49 | for(int i = 0; i < numOfVertices; i++) { 50 | if(!visited[i]) { 51 | DFSUtil(i, visited); 52 | } 53 | } 54 | } 55 | 56 | void print() { 57 | for(int i = 0; i < numOfVertices; i++) { 58 | System.out.print(i + " - "); 59 | for(int j = 0; j < adjList[i].size(); j++) { 60 | System.out.print(adjList[i].get(j) + " "); 61 | } 62 | System.out.println(); 63 | } 64 | } 65 | 66 | public static void main(String[] args) { 67 | 68 | DFSDirected dfsObject = new DFSDirected(4); 69 | 70 | dfsObject.addEdge(0, 1); 71 | dfsObject.addEdge(0, 2); 72 | dfsObject.addEdge(1, 2); 73 | dfsObject.addEdge(2, 0); 74 | dfsObject.addEdge(2, 3); 75 | dfsObject.addEdge(3, 3); 76 | 77 | dfsObject.print(); 78 | 79 | dfsObject.dfs(2); 80 | System.out.println(); 81 | dfsObject.dfsAll(); 82 | } 83 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/DetectCycleInUndirectedGraphUsingUnionFind.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | import java.util.LinkedList; 4 | 5 | // http://www.geeksforgeeks.org/?p=26350 6 | 7 | /* 8 | Using union find subset algorithm 9 | using path compression 10 | using union by rank 11 | 12 | Time Complexity - O(V log(V)) bcoz if there is a cycle it will return immediately after the Vth edge, 13 | bcoz there can only be V-1 edges in a graph with no cycle 14 | Union - O(log(n)) 15 | Find - O(log(n)) 16 | 17 | Space Complexity - O(V+E) 18 | */ 19 | 20 | class DetectCycleInUndirectedGraphUsingUnionFind { 21 | 22 | public static void main(String[] args) { 23 | Graph graph = new Graph(4); 24 | graph.addEdge(0, 1); 25 | graph.addEdge(1, 2); 26 | graph.addEdge(2, 3); 27 | graph.addEdge(0, 3); 28 | 29 | String sol = graph.findCycle() ? "Yes" : "No"; 30 | System.out.println(sol); 31 | } 32 | } 33 | 34 | class Graph { 35 | int n; 36 | ArrayList> adjList; 37 | int[] parent; 38 | int[] rank; 39 | 40 | Graph(int n) { 41 | this.n = n; 42 | adjList = new ArrayList<>(); 43 | for(int i = 0; i < n; i++) { 44 | adjList.add(new LinkedList<>()); 45 | } 46 | 47 | parent = new int[n]; 48 | rank = new int[n]; 49 | for(int i = 0; i < n; i++) { 50 | parent[i] = i; 51 | } 52 | } 53 | 54 | void addEdge(int x, int y) { 55 | adjList.get(x).add(y); 56 | } 57 | 58 | boolean findCycle() { 59 | for(int i = 0; i < n; i++) { 60 | Iterator iterator = adjList.get(i).iterator(); 61 | 62 | while(iterator.hasNext()) { 63 | int x = iterator.next(); 64 | int parentI = find(i); 65 | int parentX = find(x); 66 | if(parentI != parentX) { 67 | union(i, x); 68 | } else { 69 | return true; 70 | } 71 | } 72 | } 73 | return false; 74 | } 75 | 76 | // path compression 77 | int find(int i) { 78 | if(parent[i] == i) { 79 | return i; 80 | } else { 81 | parent[i] = find(parent[i]); 82 | return parent[i]; 83 | } 84 | } 85 | 86 | // union by rank 87 | void union(int i, int j) { 88 | int irep = find(i); 89 | int jrep = find(j); 90 | 91 | if(irep == jrep) { 92 | return; 93 | } 94 | 95 | int irank = rank[irep]; 96 | int jrank = rank[jrep]; 97 | 98 | if(irank < jrank) { 99 | this.parent[irep] = jrep; 100 | } else if(jrank < irank) { 101 | this.parent[jrep] = irep; 102 | } else { 103 | parent[irep] = jrep; 104 | rank[jrep]++; 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Graph Algorithms/Graph Theory.gdoc: -------------------------------------------------------------------------------- 1 | {"url": "https://docs.google.com/open?id=1GS6SEVPlWzG07zT7MzGYu7myfEg5xMHsFRw5MfFTDY0", "doc_id": "1GS6SEVPlWzG07zT7MzGYu7myfEg5xMHsFRw5MfFTDY0", "email": "deepaksood619@gmail.com", "resource_id": "document:1GS6SEVPlWzG07zT7MzGYu7myfEg5xMHsFRw5MfFTDY0"} -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Greedy Algorithms/GreedyAlgorithms.txt: -------------------------------------------------------------------------------- 1 | http://www.geeksforgeeks.org/greedy-algorithms-set-1-activity-selection-problem/ 2 | 3 | Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem. 4 | 5 | If a Greedy Algorithm can solve a problem, then it generally becomes the best method to solve that problem as the Greedy algorithms are in general more efficient than other techniques like Dynamic Programming. 6 | 7 | Applications - 8 | 1. Activity Selection Problem 9 | 2. Huffman Coding (Loss Less Encoding Algorithm) 10 | 3. Job Sequencing Problem 11 | 4. Fractional Knapsack Problem 12 | 5. Prim's MST 13 | 6. Krushkal's MST 14 | 7. Dijkstra's Shortest Path 15 | -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Greedy Algorithms/HuffmanCoding.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/greedy-algorithms-set-3-huffman-coding/ 2 | 3 | /* 4 | Huffman coding is a lossless data compression algorithm. 5 | The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. 6 | The most frequent character gets the smallest code and the least frequent character gets the largest code. 7 | 8 | The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in such a way that the code assigned to one character is not prefix of code assigned to any other character. 9 | This is how Huffman Coding makes sure that there is no ambiguity when decoding the generated bit stream. 10 | */ -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Greedy Algorithms/KruskalMST.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | // http://www.geeksforgeeks.org/?p=26604 4 | 5 | class KruskalMST { 6 | 7 | public static void main(String[] args) { 8 | int V = 9, E =14; 9 | Graph graph = new Graph(V, E); 10 | 11 | graph.add(0, 0, 1, 4); 12 | graph.add(1, 0, 7, 8); 13 | graph.add(2, 1, 7, 11); 14 | graph.add(3, 1, 2, 8); 15 | graph.add(4, 7, 6, 1); 16 | graph.add(5, 7, 8, 7); 17 | graph.add(6, 2, 8, 2); 18 | graph.add(7, 6, 8, 6); 19 | graph.add(8, 2, 3, 7); 20 | graph.add(9, 2, 5, 4); 21 | graph.add(10, 6, 5, 2); 22 | graph.add(11, 5, 4, 10); 23 | graph.add(12, 5, 3, 14); 24 | graph.add(13, 3, 4, 9); 25 | 26 | graph.FuncKruskalMST(); 27 | 28 | } 29 | 30 | } 31 | 32 | class Graph { 33 | 34 | Edge[] edge; 35 | int V, E; 36 | 37 | Graph(int V, int E) { 38 | this.V = V; 39 | this.E = E; 40 | edge = new Edge[E]; 41 | for(int i = 0; i < E; i++) { 42 | edge[i] = new Edge(); 43 | } 44 | } 45 | 46 | void add(int index, int src, int dest, int weight) { 47 | edge[index].src = src; 48 | edge[index].dest = dest; 49 | edge[index].weight = weight; 50 | } 51 | 52 | int find(subset[] subsets, int i) { 53 | if(subsets[i].parent != i) 54 | subsets[i].parent = find(subsets, subsets[i].parent); 55 | 56 | return subsets[i].parent; 57 | } 58 | 59 | void Union(subset[] subsets, int x, int y) { 60 | int xRoot = x; 61 | int yRoot = y; 62 | 63 | if(subsets[xRoot].rank < subsets[yRoot].rank) { 64 | subsets[xRoot].parent = yRoot; 65 | } else if(subsets[xRoot].rank > subsets[yRoot].rank) { 66 | subsets[yRoot].parent = xRoot; 67 | } else { 68 | subsets[yRoot].parent = xRoot; 69 | subsets[xRoot].rank++; 70 | } 71 | } 72 | 73 | void FuncKruskalMST() { 74 | Edge[] result = new Edge[V-1]; 75 | for(int i = 0; i < V-1; i++) { 76 | result[i] = new Edge(); 77 | } 78 | 79 | Arrays.sort(edge, new Comparator(){ 80 | @Override 81 | public int compare(Edge a, Edge b) { 82 | return Integer.compare(a.weight, b.weight); 83 | } 84 | }); 85 | 86 | System.out.println(Arrays.toString(edge)); 87 | 88 | subset[] subsets = new subset[V]; 89 | 90 | for(int i = 0; i < V; i++) { 91 | subsets[i] = new subset(); 92 | } 93 | 94 | for(int i = 0; i < V; i++) { 95 | subsets[i].parent = i; 96 | subsets[i].rank = 0; 97 | } 98 | 99 | int i = 0; 100 | int e = 0; 101 | 102 | while(e < V-1) { 103 | Edge newEdge = edge[i++]; 104 | 105 | int x = find(subsets, newEdge.src); 106 | int y = find(subsets, newEdge.dest); 107 | 108 | if(x != y) { 109 | result[e++] = newEdge; 110 | Union(subsets, x, y); 111 | } 112 | } 113 | 114 | System.out.println(Arrays.toString(result)); 115 | } 116 | } 117 | 118 | class Edge { 119 | int src; 120 | int dest; 121 | int weight; 122 | 123 | @Override 124 | public String toString() { 125 | return "src- " + src + " dest- " + dest + " weight- " + weight + "\n"; 126 | } 127 | } 128 | 129 | class subset { 130 | int parent; 131 | int rank; 132 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Greedy Algorithms/SortedActivitySelectionProblem.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/greedy-algorithms-set-1-activity-selection-problem/ 2 | 3 | /* 4 | Problem - You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. 5 | 6 | Solution - The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of previously selected activity. 7 | 8 | Algorithmic Approach - Greedy Algorithm 9 | 10 | Assumption - start and finish are sorted according to finish time 11 | 12 | Time Complexity - O(N) 13 | Space Complexity - O(1) 14 | */ 15 | 16 | import java.util.LinkedList; 17 | 18 | class ActivitySelectionProblem { 19 | 20 | public static void main(String[] args) { 21 | int[] start = new int[] {1, 3, 0, 5, 8, 5}; 22 | int[] finish = new int[] {2, 4, 6, 7, 9, 9}; 23 | LinkedList indexList = new LinkedList<>(); 24 | LinkedList activityList = new LinkedList<>(); 25 | 26 | int count = 0; 27 | int last_finish_index = 0; 28 | 29 | if(start.length > 0) { 30 | count++; 31 | indexList.add(0); 32 | activityList.add(new StartFinish(start[0], finish[0])); 33 | } 34 | 35 | for(int i = 1; i < finish.length; i++) { 36 | if(start[i] >= finish[last_finish_index]) { 37 | indexList.add(i); 38 | activityList.add(new StartFinish(start[i], finish[i])); 39 | count++; 40 | last_finish_index = i; 41 | } 42 | } 43 | 44 | System.out.println("Num of activities - " + count); 45 | System.out.print("Index of selected activities - "); 46 | for(Integer i : indexList) { 47 | System.out.print(i + " "); 48 | } 49 | System.out.println(); 50 | System.out.print("Start finish of selected activities - "); 51 | for(StartFinish i : activityList) { 52 | System.out.print("{ " + i.getStart() + ", " + i.getFinish() + " } "); 53 | } 54 | } 55 | } 56 | 57 | class StartFinish { 58 | int start; 59 | int finish; 60 | 61 | StartFinish(int start, int finish) { 62 | this.start = start; 63 | this.finish = finish; 64 | } 65 | 66 | public int getStart() { 67 | return this.start; 68 | } 69 | 70 | public int getFinish() { 71 | return this.finish; 72 | } 73 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Mathematics/Combinations.cpp: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/ 2 | 3 | #include 4 | #include 5 | 6 | void combinationUtil(int*, int*, int, int, int, int); 7 | 8 | void printCombinations(int arr[], int n, int r) { 9 | int data[r]; 10 | 11 | // to handle duplicates 12 | std::sort(arr, arr+n); 13 | 14 | combinationUtil(arr, data, 0, n-1, 0, r); 15 | } 16 | 17 | void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { 18 | if(index == r) { 19 | for(int i = 0; i < r; i++) { 20 | printf("%d ", data[i]); 21 | } 22 | printf("\n"); 23 | return; 24 | } 25 | 26 | for(int i = start; i <= end && end-i+1 >= r-index; i++) { 27 | data[index] = arr[i]; 28 | combinationUtil(arr, data, i+1, end, index+1, r); 29 | 30 | // to handle duplicates 31 | while(arr[i] == arr[i+1]) 32 | i++; 33 | } 34 | } 35 | 36 | int main() { 37 | int arr[] = {1, 2, 1}; 38 | 39 | int r = 2; 40 | 41 | int n = sizeof(arr)/sizeof(arr[0]); 42 | 43 | printCombinations(arr, n, r); 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Mathematics/ModifiedSieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void printSieve(int n) { 5 | bool prime[n+1]; 6 | memset(prime, true, sizeof(prime)); 7 | 8 | for(int i = 2; i <= n; i++) { 9 | if(prime[i]) { 10 | for(int j = i+i; j <= n; j += i) { 11 | prime[j] = false; 12 | } 13 | } 14 | } 15 | 16 | for(int i = 2; i <= n; i++) { 17 | if(prime[i]) 18 | printf("%d ", i); 19 | } 20 | } 21 | 22 | int main() { 23 | int n; 24 | scanf("%d", &n); 25 | 26 | printSieve(n); 27 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Mathematics/PrimeFactors.cpp: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/ 2 | 3 | /* 4 | Time Complexity - O(log(n)) 5 | Space Complexity - O(1) 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | void primeFactors(int n) { 12 | while (n%2 == 0) { 13 | printf("%d ", 2); 14 | n /= 2; 15 | } 16 | 17 | for( int i = 3; i <= sqrt(n); i += 2) { 18 | while(n%i == 0) { 19 | printf("%d ", i); 20 | n /= i; 21 | } 22 | } 23 | 24 | if (n > 2) 25 | printf ("%d ", n); 26 | 27 | } 28 | 29 | int main() { 30 | 31 | int n = 100; 32 | 33 | primeFactors(n); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Mathematics/SieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/sieve-of-eratosthenes/ 2 | 3 | /* 4 | Time Complexity - O(N log (log N)) 5 | Space Complexity - O(n) 6 | */ 7 | 8 | #include 9 | 10 | void printSieve(int n) { 11 | bool prime[n+1]; 12 | memset(prime, true, sizeof(prime)); 13 | 14 | for(int i = 2; i <= n; i++) 15 | if(prime[i]) 16 | for(int j = i+i; j <= n; j+=i) 17 | prime[j] = false; 18 | 19 | for(int i = 2; i <= n; i++) 20 | if(prime[i]) 21 | std::cout << i << " "; 22 | 23 | std::cout << '\n'; 24 | } 25 | 26 | int main() { 27 | int n = 0; 28 | 29 | std::cin >> n; 30 | 31 | printSieve(n); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Other Algorithms/3SumProblem.java: -------------------------------------------------------------------------------- 1 | // Time Complexity - O(n^2) 2 | 3 | class 3SumProblem { 4 | 5 | public static void main(String[] args) { 6 | int[] arr = new int[] {-25, -10, -7, -3, 0, 4, 8, 25}; 7 | 8 | int size = arr.length; 9 | 10 | for (int i = 0; i <= size-3; i++) { 11 | int sum = arr[i] + arr[i+1]; 12 | int index = binarySearch(arr, i+2, size-1, 0-sum); 13 | if (index != -1) { 14 | System.out.println(arr[i] + " " + arr[i+1] + " " + arr[index]); 15 | } 16 | } 17 | } 18 | 19 | public static int binarySearch(int[] arr, int start, int end, int key) { 20 | if (end >= start) { 21 | int mid = (start + end) / 2; 22 | 23 | if (arr[mid] == key) 24 | return mid; 25 | 26 | if (key < arr[mid]) { 27 | return binarySearch(arr, start, mid-1, key); 28 | } 29 | 30 | return binarySearch(arr, mid+1, end, key); 31 | } 32 | return -1; 33 | } 34 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Other Algorithms/MaximumElementinBitonic.java: -------------------------------------------------------------------------------- 1 | // Time Complexity - O(log n) using binary search 2 | 3 | class MaximumElementinBitonic { 4 | 5 | public static int findMaximum(int[] arr, int low, int high) { 6 | 7 | // if only one element is present in arr 8 | if (low == high) 9 | return arr[low]; 10 | 11 | /* If there are two elements and 12 | first is greater then the first 13 | element is maximum */ 14 | if ((high == low + 1) && arr[low] >= arr[high]) 15 | return arr[low]; 16 | 17 | /* If there are two elements and 18 | second is greater then the second 19 | element is maximum */ 20 | if ((high == low + 1) && arr[low] < arr[high]) 21 | return arr[high]; 22 | 23 | /* low + (high - low)/2; for preventing integer overflow for large numbers */ 24 | int mid = (low + high)/2; 25 | 26 | /* If we reach a point where arr[mid] 27 | is greater than both of its adjacent 28 | elements arr[mid-1] and arr[mid+1], 29 | then arr[mid] is the maximum element*/ 30 | if ( arr[mid] > arr[mid + 1] && arr[mid] > arr[mid - 1]) 31 | return arr[mid]; 32 | 33 | /* If arr[mid] is greater than the next 34 | element and smaller than the previous 35 | element then maximum lies on left side 36 | of mid */ 37 | if (arr[mid] > arr[mid + 1] && arr[mid] < arr[mid - 1]) 38 | return findMaximum(arr, low, mid-1); 39 | else 40 | return findMaximum(arr, mid + 1, high); 41 | 42 | } 43 | 44 | public static void main(String[] args) { 45 | int arr[] = {1, 3, 50, 10, 9, 7, 6}; 46 | int n = arr.length; 47 | System.out.println("The maximum element is "+ 48 | findMaximum(arr, 0, n-1)); 49 | } 50 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Recursion/Factorial.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/c-program-factorial-number/ 2 | 3 | /* 4 | Time Complexity - O(n) 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | class Factorial { 10 | 11 | static int fact(int n) { 12 | if(n == 1) { 13 | return 1; 14 | } 15 | return n * fact(n - 1); 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner in = new Scanner(System.in); 20 | int n = in.nextInt(); 21 | 22 | Factorial factorial = new Factorial(); 23 | System.out.println(factorial.fact(n)); 24 | } 25 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Recursion/PermutationsOfAGivenString.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/permutations-of-a-given-string/0 2 | 3 | import java.util.*; 4 | 5 | class PermutationsOfAGivenString { 6 | 7 | public static Vector vec = new Vector(); 8 | 9 | public static void print(char str[],int i,int j) 10 | { 11 | if(i==j) { 12 | String temp=new String(str); 13 | vec.add(temp); 14 | } else { 15 | char a=str[i]; 16 | for(int k=i;k<=j;k++) { 17 | str[i]=str[k]; 18 | str[k]=a; 19 | 20 | print(str,i+1,j); 21 | str[k]=str[i]; 22 | str[i]=a; 23 | } 24 | } 25 | } 26 | 27 | public static void main (String[] args) { 28 | 29 | Scanner sc=new Scanner(System.in); 30 | int t=sc.nextInt(); 31 | 32 | while(t-- > 0) { 33 | 34 | String str=sc.next(); 35 | char arr[]=new char[str.length()]; 36 | arr = str.toCharArray(); 37 | 38 | print(arr,0,str.length()-1); 39 | 40 | for(int i=0;i vec = new Vector(); 9 | 10 | public static void print(char str[],int i,int j) 11 | { 12 | if(i==j) { 13 | System.out.println("str - " + new String(str)); 14 | String temp=new String(str); 15 | vec.add(temp); 16 | } else { 17 | char a=str[i]; 18 | for(int k=i;k<=j;k++) { 19 | str[i]=str[k]; 20 | str[k]=a; 21 | 22 | print(str,i+1,j); 23 | str[k]=str[i]; 24 | str[i]=a; 25 | } 26 | } 27 | } 28 | 29 | public static void sortCharArray(char[] arr) { 30 | 31 | // selection sort 32 | for(int i = 0; i < arr.length; i++) { 33 | int minIndex = i; 34 | for(int j = i; j < arr.length; j++) { 35 | if(arr[minIndex] < arr[j]) { 36 | minIndex = j; 37 | } 38 | } 39 | char t = arr[minIndex]; 40 | arr[i] = arr[minIndex]; 41 | arr[minIndex] = t; 42 | } 43 | } 44 | 45 | public static void main (String[] args) { 46 | 47 | Scanner sc=new Scanner(System.in); 48 | int t=sc.nextInt(); 49 | 50 | while(t-- > 0) { 51 | 52 | String str=sc.next(); 53 | char arr[]=new char[str.length()]; 54 | arr = str.toCharArray(); 55 | 56 | System.out.println("arr input - " + new String(arr)); 57 | 58 | //Arrays.sort(arr); 59 | sortCharArray(arr); 60 | 61 | System.out.println("arr input - " + new String(arr)); 62 | 63 | /* print(arr,0,str.length()-1); 64 | 65 | for(int i=0;i < vec.size();i++) { 66 | System.out.print(vec.get(i)+" "); 67 | } 68 | 69 | System.out.println(); 70 | Collections.sort(vec); 71 | 72 | for(int i=0;i 2 | 3 | void abc(char *s) 4 | { 5 | if(s[0] == '\0') 6 | return; 7 | 8 | abc(s + 1); 9 | abc(s + 1); 10 | printf("%c", s[0]); 11 | } 12 | 13 | int main() 14 | { 15 | abc("xyz"); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Recursion/SelectionSortRecursive.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/practice-questions-for-recursion/ 2 | 3 | class SelectionSortRecursive { 4 | 5 | static void print(int[] arr) { 6 | for(int i = 0; i < arr.length; i++) { 7 | System.out.print(arr[i] + " "); 8 | } 9 | } 10 | 11 | static void selectionSort(int[] arr, int startIndex, int endIndex) { 12 | if(startIndex >= endIndex) { 13 | return; 14 | } 15 | 16 | int min = startIndex; 17 | for(int i = startIndex+1; i < endIndex; i++) { 18 | if(arr[i] < arr[min]) { 19 | min = i; 20 | } 21 | } 22 | 23 | int temp = arr[startIndex]; 24 | arr[startIndex] = arr[min]; 25 | arr[min] = temp; 26 | 27 | selectionSort(arr, startIndex + 1, endIndex); 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] arr = new int[] {4, 2, 1, 3}; 32 | 33 | int n = arr.length; 34 | 35 | print(arr); 36 | System.out.println(); 37 | 38 | // selection sort recursive 39 | selectionSort(arr, 0, n); 40 | 41 | print(arr); 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/BubbleSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/bubble-sort/ 2 | 3 | /* 4 | Optimized Bubble Sort - Stop the algorithm if inner loop didn’t cause any swap. 5 | 6 | Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted. 7 | 8 | Best Case Time Complexity: O(n). Best case occurs when array is already sorted. 9 | 10 | Auxiliary Space: O(1) 11 | 12 | Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted. 13 | 14 | Sorting In Place: Yes 15 | 16 | Stable: Yes 17 | */ 18 | 19 | class BubbleSort { 20 | public static void main(String[] args) { 21 | System.out.println("Bubble Sort"); 22 | 23 | int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8}; 24 | 25 | for(int i = 0; i < arr.length; i++) { 26 | System.out.print(arr[i] + " "); 27 | } 28 | 29 | System.out.println(); 30 | 31 | int n = arr.length; 32 | 33 | boolean swapped = false; 34 | 35 | for(int i = 0; i < n-1; i++) { 36 | for(int j = 0; j < n-i-1; j++) { 37 | if(arr[j] > arr[j+1]) { 38 | swapped = true; 39 | int t = arr[j]; 40 | arr[j] = arr[j+1]; 41 | arr[j+1] = t; 42 | } 43 | } 44 | 45 | if(!swapped) { 46 | System.out.println("Already Sorted"); 47 | break; 48 | } 49 | } 50 | 51 | for(int i = 0; i < arr.length; i++) { 52 | System.out.print(arr[i] + " "); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/CountingSort.java: -------------------------------------------------------------------------------- 1 | // only sorts the 1 digit numbers 2 | 3 | class CountingSort { 4 | public static void main(String[] args) { 5 | System.out.println("CountingSort"); 6 | int[] arr = new int[] {4, 2, 1, 3, 1, 5,6,7,8,9,1,0,2,3,4,5,6,6}; 7 | 8 | int n = arr.length; 9 | 10 | for(int i = 0; i < n; i++) { 11 | System.out.println(arr[i]); 12 | } 13 | 14 | int[] indexArr = new int[10]; 15 | 16 | for(int i = 0; i < n; i++) { 17 | int index = arr[i] % 10; 18 | indexArr[index]++; 19 | } 20 | 21 | for(int i = 0; i < 10; i++) { 22 | for(int j = 0; j < indexArr[i]; j++) { 23 | System.out.println(i); 24 | } 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/InsertionSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/insertion-sort/ 2 | 3 | /* 4 | Time Complexity - O(n^2) 5 | Space Complexity - O(1) 6 | 7 | Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. 8 | And it takes minimum time (Order of n) when elements are already sorted. 9 | 10 | Uses: Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array. 11 | 12 | Algorithmic Paradigm: Incremental Approach 13 | 14 | Sorting In Place: Yes 15 | 16 | Stable: Yes 17 | 18 | Online: Yes 19 | */ 20 | 21 | class InsertionSort { 22 | 23 | static void insertionSort(int[] arr) { 24 | for(int i = 1; i < arr.length; i++) { 25 | int key = arr[i]; 26 | int j = i - 1; 27 | 28 | while(j >= 0 && arr[j] > key) { 29 | arr[j+1] = arr[j]; 30 | j = j-1; 31 | } 32 | 33 | arr[j+1] = key; 34 | } 35 | } 36 | 37 | public static void main(String[] args) { 38 | System.out.println("Insertion Sort"); 39 | 40 | int[] arr = new int[] {5, 2, 4, 3, 1}; 41 | 42 | int n = arr.length; 43 | for(int i = 0; i < n; i++) { 44 | System.out.print(arr[i] + " "); 45 | } 46 | System.out.println(); 47 | 48 | insertionSort(arr); 49 | 50 | for(int i = 0; i < n; i++) { 51 | System.out.print(arr[i] + " "); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/IterativeMergeSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/iterative-merge-sort/ 2 | 3 | /* 4 | Recursive implementation uses function call stack to store intermediate values of l and h. 5 | The function call stack stores other bookkeeping information together with parameters. 6 | Also, function calls involve overheads like storing activation record of the caller function and then resuming execution. 7 | Unlike Iterative QuickSort, the iterative MergeSort doesn’t require explicit auxiliary stack. 8 | 9 | Auxiliary Space: O(n) 10 | 11 | Algorithmic Paradigm: Divide and Conquer 12 | 13 | Sorting In Place: No in a typical implementation 14 | 15 | Stable: Yes 16 | 17 | */ 18 | 19 | class IterativeMergeSort { 20 | 21 | static void merge(int[] arr, int left, int mid, int right) { 22 | int n1 = mid - left + 1; 23 | int n2 = right - mid; 24 | 25 | int[] leftArr = new int[n1]; 26 | int[] rightArr = new int[n2]; 27 | 28 | for(int i = 0; i < n1; i++) { 29 | leftArr[i] = arr[left + i]; 30 | } 31 | for(int j = 0; j < n2; j++) { 32 | rightArr[j] = arr[mid + j + 1]; 33 | } 34 | 35 | int i = 0, j = 0, k = left; 36 | 37 | while(i < n1 && j < n2) { 38 | if(leftArr[i] < rightArr[j]) { 39 | arr[k] = leftArr[i]; 40 | i++; 41 | } else { 42 | arr[k] = rightArr[j]; 43 | j++; 44 | } 45 | k++; 46 | } 47 | 48 | while(i < n1) { 49 | arr[k] = leftArr[i]; 50 | i++; 51 | k++; 52 | } 53 | 54 | while(j < n2) { 55 | arr[k] = rightArr[j]; 56 | j++; 57 | k++; 58 | } 59 | } 60 | 61 | static void mergeSort(int[] arr, int n) { 62 | 63 | int left_index; 64 | int current_size; 65 | 66 | for(current_size = 1; current_size < n-1; current_size = current_size*2) { 67 | for(left_index = 0; left_index < n-1; left_index += 2 * current_size) { 68 | int mid = left_index + current_size - 1; 69 | 70 | int right_index = min(left_index + 2*current_size - 1, n-1); 71 | 72 | merge(arr, left_index, mid, right_index); 73 | } 74 | } 75 | 76 | } 77 | 78 | static int min(int a, int b) { 79 | if(a < b) return a; 80 | else return b; 81 | } 82 | 83 | public static void main(String[] args) { 84 | int[] arr = new int[] {4, 3, 1, 2}; 85 | 86 | mergeSort(arr, arr.length); 87 | 88 | for(int i = 0; i < arr.length; i++) { 89 | System.out.print(arr[i] + " "); 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/IterativeQuickSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/iterative-quick-sort/ 2 | 3 | /* 4 | Problem with recursive Quick Sort - 5 | The function remains recursive and uses function call stack to store intermediate values of l and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls involve overheads like storing activation record of the caller function and then resuming execution. 6 | 7 | Recursive Quick Sort can be easily converted to iterative version with the help of an auxiliary stack. Following is an iterative implementation of the recursive code. 8 | */ 9 | 10 | class IterativeQuickSort { 11 | 12 | static int partition(int[] arr, int low, int high) { 13 | int pivot = arr[high]; 14 | int i = low - 1; 15 | 16 | for(int j = low; j < high; j++) { 17 | if(arr[j] <= pivot) { 18 | i++; 19 | int temp = arr[i]; 20 | arr[i] = arr[j]; 21 | arr[j] = temp; 22 | } 23 | } 24 | int temp = arr[i+1]; 25 | arr[i+1] = arr[high]; 26 | arr[high] = temp; 27 | return i+1; 28 | } 29 | 30 | static void iterativeQuickSort(int[] arr, int low, int high) { 31 | int[] stack = new int[high - low + 1]; 32 | int top = -1; 33 | 34 | stack[++top] = low; 35 | stack[++top] = high; 36 | 37 | while(top >= 0) { 38 | high = stack[top--]; 39 | low = stack[top--]; 40 | 41 | int pi = partition(arr, low, high); 42 | 43 | if(pi-1 > low) { 44 | stack[++top] = low; 45 | stack[++top] = pi - 1; 46 | } 47 | 48 | if(pi + 1 < high) { 49 | stack[++top] = pi + 1; 50 | stack[++top] = high; 51 | } 52 | } 53 | } 54 | 55 | public static void main(String[] args) { 56 | int[] arr = new int[] {3, 1, 4, 2}; 57 | int N = arr.length; 58 | 59 | iterativeQuickSort(arr, 0, N-1); 60 | 61 | for(int i = 0; i < N; i++) { 62 | System.out.print(arr[i] + " "); 63 | } 64 | System.out.println(); 65 | } 66 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/MergeSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/merge-sort/ 2 | 3 | /* 4 | Like QuickSort, Merge Sort is a Divide and Conquer algorithm. 5 | It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves 6 | 7 | Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. 8 | 9 | Time Complexity: 10 | Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation. 11 | T(n) = 2T(n/2) + \Theta(n) 12 | The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is \Theta(nLogn). 13 | Time complexity of Merge Sort is \Theta(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array in two halves and take linear time to merge two halves. 14 | 15 | Auxiliary Space: O(n) 16 | 17 | Algorithmic Paradigm: Divide and Conquer 18 | 19 | Sorting In Place: No in a typical implementation 20 | 21 | Stable: Yes 22 | 23 | Merge sort is generally considered better when data is huge and stored in external storage. 24 | 25 | */ 26 | 27 | class MergeSort { 28 | 29 | // Merges two subarrays of arr[]. 30 | // First subarray is arr[l..m] 31 | // Second subarray is arr[m+1..r] 32 | static void merge(int arr[], int l, int m, int r) 33 | { 34 | // Find sizes of two subarrays to be merged 35 | int n1 = m - l + 1; 36 | int n2 = r - m; 37 | 38 | /* Create temp arrays */ 39 | int L[] = new int [n1]; 40 | int R[] = new int [n2]; 41 | 42 | /*Copy data to temp arrays*/ 43 | for (int i=0; i3->20->5->10->15 125 | */ 126 | li.push(15); 127 | li.push(10); 128 | li.push(5); 129 | li.push(20); 130 | li.push(3); 131 | li.push(2); 132 | System.out.println("Linked List without sorting is :"); 133 | li.printList(li.head); 134 | 135 | // Apply merge Sort 136 | li.head = li.mergeSort(li.head); 137 | System.out.print("\n Sorted Linked List is: \n"); 138 | li.printList(li.head); 139 | } 140 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/QuickSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/quick-sort/ 2 | 3 | /* 4 | Like Merge Sort, QuickSort is a Divide and Conquer algorithm. 5 | It picks an element as pivot and partitions the given array around the picked pivot. 6 | 7 | The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, 8 | put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, 9 | and put all greater elements (greater than x) after x. 10 | All this should be done in linear time. 11 | 12 | Pseudo Code for recursive QuickSort function : 13 | 14 | //low --> Starting index, high --> Ending index 15 | quickSort(arr[], low, high) 16 | { 17 | if (low < high) 18 | { 19 | // pi is partitioning index, arr[p] is now at right place 20 | pi = partition(arr, low, high); 21 | 22 | quickSort(arr, low, pi - 1); // Before pi 23 | quickSort(arr, pi + 1, high); // After pi 24 | } 25 | } 26 | 27 | Worst Case Time Complexity - O(N^2) 28 | Average Time Complexity - W(N*log(N)) 29 | Space Complexity - O(1) 30 | In-place - yes 31 | Stable - yes 32 | 33 | QuickSort is faster in practice, because its inner loop can be efficiently implemented on most architectures, and in most real-world data. QuickSort can be implemented in different ways by changing the choice of pivot, so that the worst case rarely occurs for a given type of data. However, merge sort is generally considered better when data is huge and stored in external storage. 34 | */ 35 | 36 | class QuickSort { 37 | 38 | /* 39 | we start from the leftmost element and keep track of index of smaller (or equal to) elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element. 40 | */ 41 | static int partition(int[] arr, int low, int high) { 42 | int pivot = arr[high]; 43 | 44 | int i = low - 1; 45 | 46 | for(int j = low; j <= high-1; j++) { 47 | if(arr[j] <= pivot) { 48 | i++; 49 | // swap( arr[i], arr[j] ); 50 | int temp = arr[i]; 51 | arr[i] = arr[j]; 52 | arr[j] = temp; 53 | } 54 | } 55 | 56 | // swap( arr[i+1], arr[high] ); 57 | int temp = arr[i+1]; 58 | arr[i+1] = arr[high]; 59 | arr[high] = temp; 60 | return i+1; 61 | } 62 | 63 | static void quickSort(int[] arr, int low, int high) { 64 | if(low < high) { 65 | int pi = partition(arr, low, high); 66 | quickSort(arr, low, pi-1); 67 | quickSort(arr, pi+1, high); 68 | } 69 | } 70 | 71 | public static void main(String[] args) { 72 | int[] arr = new int[] {3, 2, 1, 4}; 73 | 74 | quickSort(arr, 0, arr.length - 1); 75 | 76 | for(int i = 0; i < arr.length; i++) { 77 | System.out.print(arr[i] + " "); 78 | } 79 | } 80 | 81 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/RadixSort.java: -------------------------------------------------------------------------------- 1 | class RadixSort { 2 | public static void main(String[] args) { 3 | System.out.println("RadixSort"); 4 | int[] arr = new int[] {41, 12, 11, 13}; 5 | 6 | int n = arr.length; 7 | 8 | for(int i = 0; i < n; i++) { 9 | System.out.println(arr[i]); 10 | } 11 | 12 | for(int i = 0; i < n-1; i++) { 13 | 14 | } 15 | 16 | for(int i = 0; i < n; i++) { 17 | System.out.println(arr[i]); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/RecursiveInsertionSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/recursive-insertion-sort/ 2 | 3 | /* 4 | Time Complexity - O(n*n) 5 | Space Complexity - O(1) 6 | 7 | in place - yes 8 | Stable - yes 9 | online - yes 10 | */ 11 | 12 | class RecursiveInsertionSort { 13 | 14 | static void recursiveInsertionSort(int[] arr, int n) { 15 | 16 | if(n <= 1) 17 | return; 18 | 19 | recursiveInsertionSort(arr, n-1); 20 | 21 | int key = arr[n-1]; 22 | int j = n - 2; 23 | 24 | while(j >= 0 && arr[j] > key) { 25 | arr[j+1] = arr[j]; 26 | j = j-1; 27 | } 28 | 29 | arr[j+1] = key; 30 | } 31 | 32 | public static void main(String[] args) { 33 | System.out.println("Recursive Insertion Sort"); 34 | 35 | int[] arr = new int[] {5, 2, 4, 3, 1}; 36 | 37 | int n = arr.length; 38 | for(int i = 0; i < n; i++) { 39 | System.out.print(arr[i] + " "); 40 | } 41 | System.out.println(); 42 | 43 | recursiveInsertionSort(arr, arr.length); 44 | 45 | for(int i = 0; i < n; i++) { 46 | System.out.print(arr[i] + " "); 47 | } 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/RecusiveBubbleSort.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/recursive-bubble-sort/ 2 | 3 | /* 4 | Optimized Bubble Sort - Stop the algorithm if inner loop didn’t cause any swap. 5 | 6 | Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted. 7 | 8 | Best Case Time Complexity: O(n). Best case occurs when array is already sorted. 9 | 10 | Auxiliary Space: O(1) 11 | 12 | Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted. 13 | 14 | Sorting In Place: Yes 15 | 16 | Stable: Yes 17 | */ 18 | 19 | class RecursiveBubbleSort { 20 | 21 | static void sort(int[] arr, int n) { 22 | if(n == 1) 23 | return; 24 | 25 | boolean swapped = false; 26 | for(int i = 0; i < n-1; i++) { 27 | if(arr[i] > arr[i+1]) { 28 | swapped = true; 29 | int t = arr[i]; 30 | arr[i] = arr[i+1]; 31 | arr[i+1] = t; 32 | } 33 | } 34 | 35 | if(!swapped) { 36 | return; 37 | } 38 | sort(arr, n-1); 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println("Bubble Sort"); 43 | 44 | int[] arr = new int[] {8, 2, 3, 4, 5, 6, 7, 1}; 45 | 46 | for(int i = 0; i < arr.length; i++) { 47 | System.out.print(arr[i] + " "); 48 | } 49 | System.out.println(); 50 | 51 | sort(arr, arr.length); 52 | 53 | for(int i = 0; i < arr.length; i++) { 54 | System.out.print(arr[i] + " "); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/SelectionSort.java: -------------------------------------------------------------------------------- 1 | class SelectionSort { 2 | public static void main(String[] args) { 3 | System.out.println("Selection Sort"); 4 | 5 | int[] arr = new int[] {4, 2, 1, 3}; 6 | 7 | for(int i = 0; i < arr.length; i++) { 8 | System.out.println(arr[i]); 9 | } 10 | 11 | for(int i = 0; i < arr.length; i++) { 12 | int min = i; 13 | for(int j = i+1; j < arr.length; j++) { 14 | if(arr[j] < arr[min]) { 15 | min = j; 16 | } 17 | } 18 | int t = arr[i]; 19 | arr[i] = arr[min]; 20 | arr[min] = t; 21 | } 22 | 23 | for(int i = 0; i < arr.length; i++) { 24 | System.out.println(arr[i]); 25 | } 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/Sort - practice.java: -------------------------------------------------------------------------------- 1 | class SortPractice { 2 | public static void main(String[] args) { 3 | System.out.println("Bubble Sort"); 4 | 5 | int[] arr = new int[] {4, 2, 1, 3}; 6 | 7 | int n = arr.length; 8 | 9 | for(int i = 0; i < n; i++) { 10 | System.out.println(arr[i]); 11 | } 12 | 13 | for(int i = 0; i < n-1; i++) { 14 | for(int j = 0; j < n-i-1; j++) { 15 | if(arr[j] > arr[j+1]) { 16 | int t = arr[j]; 17 | arr[j] = arr[j+1]; 18 | arr[j+1] = t; 19 | } 20 | } 21 | } 22 | 23 | for(int i = 0; i < n; i++) { 24 | System.out.println(arr[i]); 25 | } 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /Basic Concepts/Algorithms/Sorting Algorithms/Sorting Algorithms.gdoc: -------------------------------------------------------------------------------- 1 | {"url": "https://docs.google.com/open?id=1TnlGDrfkrObBBiZUzZ7oHIkbhvOTy9Ef5cm_EeZmf5c", "doc_id": "1TnlGDrfkrObBBiZUzZ7oHIkbhvOTy9Ef5cm_EeZmf5c", "email": "deepaksood619@gmail.com", "resource_id": "document:1TnlGDrfkrObBBiZUzZ7oHIkbhvOTy9Ef5cm_EeZmf5c"} -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/Data Structures.gdoc: -------------------------------------------------------------------------------- 1 | {"url": "https://docs.google.com/open?id=1qitkM91xbGkNoGTmUaRwIYZ7r6x94jBtMI8E16gPbUM", "doc_id": "1qitkM91xbGkNoGTmUaRwIYZ7r6x94jBtMI8E16gPbUM", "email": "deepaksood619@gmail.com", "resource_id": "document:1qitkM91xbGkNoGTmUaRwIYZ7r6x94jBtMI8E16gPbUM"} -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/DisjointSet.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/disjoint-set-data-structures-java-implementation/ 2 | 3 | /* 4 | Path Compression - It speeds up the data structure by compressing the height of the trees. It can be achieved by inserting a small caching mechanism into the Find operation. 5 | 6 | Union by Rank - minimize the height of the resulting tree 7 | 8 | Time Complexity - 9 | MakeSet - O(1) 10 | Find Operation - O(log(N)) 11 | Union Operation - O(log(N)) 12 | 13 | Space Complexity - 2*O(N) - O(N) 14 | */ 15 | 16 | class DisjointSet { 17 | 18 | int[] parent; 19 | int[] rank; 20 | int n; 21 | 22 | DisjointSet(int n) { 23 | this.n = n; 24 | parent = new int[n]; 25 | rank = new int[n]; 26 | makeSet(); 27 | } 28 | 29 | void makeSet() { 30 | // every element is the parent of itself 31 | for(int i = 0; i < this.n; i++) { 32 | parent[i] = i; 33 | } 34 | } 35 | 36 | int find(int n) { 37 | 38 | // using Path Compression 39 | 40 | if(parent[n] != n) { 41 | parent[n] = find(parent[n]); 42 | } 43 | return parent[n]; 44 | } 45 | 46 | void union(int x, int y) { 47 | 48 | // using Union by Rank 49 | 50 | int xRoot = find(x); 51 | int yRoot = find(y); 52 | 53 | if(xRoot == yRoot) { 54 | return; 55 | } else if(rank[xRoot] < rank[yRoot]) { 56 | parent[xRoot] = yRoot; 57 | } else if(rank[xRoot] > rank[yRoot]) { 58 | parent[yRoot] = xRoot; 59 | } else { 60 | parent[yRoot] = xRoot; 61 | rank[xRoot]++; 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | int n = 5; 67 | DisjointSet dus = 68 | new DisjointSet(n); 69 | 70 | // 0 is a friend of 2 71 | dus.union(0, 2); 72 | 73 | // 4 is a friend of 2 74 | dus.union(4, 2); 75 | 76 | // 3 is a friend of 1 77 | dus.union(3, 1); 78 | 79 | // Check if 4 is a friend of 0 80 | if (dus.find(4) == dus.find(0)) 81 | System.out.println("Yes"); 82 | else 83 | System.out.println("No"); 84 | 85 | // Check if 1 is a friend of 0 86 | if (dus.find(1) == dus.find(0)) 87 | System.out.println("Yes"); 88 | else 89 | System.out.println("No"); 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/HashTable.java: -------------------------------------------------------------------------------- 1 | import java.util.Hashtable; 2 | import java.util.Map; 3 | 4 | class HashTable { 5 | 6 | public static void main(String[] args) { 7 | System.out.println("Hello World"); 8 | 9 | Hashtable hm = new Hashtable(); 10 | 11 | hm.put(100, "Deepak"); 12 | hm.put(102, "Asha"); 13 | hm.put(101, "Manoj"); 14 | hm.put(103, "Anchal"); 15 | 16 | for (Map.Entry m : hm.entrySet()) { 17 | System.out.println(m.getKey() + " " + m.getValue()); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/LinkedList.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/linked-list-set-1-introduction/ 2 | 3 | class LinkedList { 4 | 5 | Node head; 6 | 7 | static class Node { 8 | int data; 9 | Node next; 10 | 11 | Node(int d) { 12 | data = d; 13 | next = null; 14 | } 15 | } 16 | 17 | void printList() { 18 | Node link = head; 19 | while(link != null) { 20 | System.out.print(link.data + " "); 21 | link = link.next; 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println("Linked List"); 27 | 28 | LinkedList linkedList = new LinkedList(); 29 | 30 | linkedList.head = new Node(4); 31 | Node second = new Node(3); 32 | Node third = new Node(1); 33 | 34 | linkedList.head.next = second; 35 | second.next = third; 36 | 37 | linkedList.printList(); 38 | } 39 | } -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/LinkedListOperations.java: -------------------------------------------------------------------------------- 1 | /* 2 | All the basic operations will be performed 3 | 1. insertion 4 | 2. print Linked List 5 | */ 6 | 7 | class LinkedListOperations { 8 | 9 | Node head; 10 | 11 | static class Node { 12 | int data; 13 | Node next; 14 | 15 | Node(int data) { 16 | this.data = data; 17 | this.next = null; 18 | } 19 | } 20 | 21 | void insert(int data) { 22 | Node node = new Node(data); 23 | if(head == null) { 24 | head = node; 25 | } else { 26 | Node endNode = head; 27 | while(endNode.next != null) { 28 | endNode = endNode.next; 29 | } 30 | endNode.next = node; 31 | } 32 | } 33 | 34 | void insertFront(int data) { 35 | Node node = new Node(data); 36 | node.next = head; 37 | head = node; 38 | } 39 | 40 | void insertAt(int data, int index) { 41 | Node current = head; 42 | if(current != null) { 43 | Node node = new Node(data); 44 | System.out.println("insert At"); 45 | int count = 0; 46 | while(current != null) { 47 | if (++count == index) { 48 | System.out.println("count - " + count); 49 | node.next = current.next; 50 | current.next = node; 51 | } else { 52 | current = current.next; 53 | } 54 | } 55 | } else { 56 | insert(data); 57 | } 58 | } 59 | 60 | void deleteFirst() { 61 | Node current = head; 62 | if(current != null) { 63 | head = current.next; 64 | } else { 65 | System.out.println("No items to delete"); 66 | } 67 | } 68 | 69 | void deleteLast() { 70 | Node current = head; 71 | Node temp = current; 72 | if(current == null) { 73 | System.out.println("No items to delete"); 74 | return; 75 | } 76 | 77 | while(current.next != null) { 78 | temp = current; 79 | current = current.next; 80 | } 81 | 82 | temp.next = null; 83 | } 84 | 85 | void deleteAt(int index) { 86 | Node current = head; 87 | Node temp = head; 88 | if(current == null) { 89 | System.out.println("No items to delete"); 90 | return; 91 | } 92 | 93 | int count = 0; 94 | while(current != null) { 95 | if(++count == index) { 96 | System.out.println("count " + count); 97 | temp.next = current.next; 98 | } else { 99 | temp = current; 100 | current = current.next; 101 | } 102 | } 103 | } 104 | 105 | void printList() { 106 | Node current = head; 107 | while(current != null) { 108 | System.out.print(current.data + " "); 109 | current = current.next; 110 | } 111 | System.out.println(); 112 | } 113 | 114 | void printLength() { 115 | int count = 0; 116 | Node current = head; 117 | while(current != null) { 118 | count ++; 119 | current = current.next; 120 | } 121 | System.out.println(count); 122 | } 123 | 124 | void reverseList() { 125 | Node prev = null; 126 | Node current = head; 127 | Node next = null; 128 | while(current != null) { 129 | next = current.next; 130 | current.next = prev; 131 | prev = current; 132 | current = next; 133 | } 134 | head = prev; 135 | } 136 | 137 | public static void main(String[] args) { 138 | LinkedListOperations ll = new LinkedListOperations(); 139 | ll.insert(2); 140 | ll.insert(4); 141 | ll.insert(5); 142 | ll.insert(6); 143 | ll.insertFront(1); 144 | ll.insertAt(3, 3-1); 145 | 146 | ll.printList(); 147 | 148 | ll.printLength(); 149 | 150 | ll.deleteLast(); 151 | ll.deleteFirst(); 152 | ll.deleteAt(2); 153 | 154 | ll.printList(); 155 | 156 | ll.reverseList(); 157 | ll.printList(); 158 | } 159 | } -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/StackUsingArray.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/stack-data-structure-introduction-program/ 2 | 3 | class StackUsingArray { 4 | 5 | int size; 6 | int top; 7 | int[] stackArr; 8 | 9 | StackUsingArray(int size) { 10 | this.size = size; 11 | top = -1; 12 | stackArr = new int[size]; 13 | } 14 | 15 | boolean isEmpty() { 16 | return (top < 0); 17 | } 18 | 19 | boolean push(int num) { 20 | if(top >= size) { 21 | System.out.println("Stack Overflow"); 22 | return false; 23 | } else { 24 | stackArr[++top] = num; 25 | return true; 26 | } 27 | } 28 | 29 | int pop () { 30 | if(top < 0) { 31 | System.out.println("Stack Underflow"); 32 | return 0; 33 | } else { 34 | int x = stackArr[top--]; 35 | return x; 36 | } 37 | } 38 | 39 | void printStack() { 40 | if(top < 0) { 41 | System.out.println("Stack Underflow"); 42 | return; 43 | } else { 44 | for(int i = 0; i <= top; i++) { 45 | System.out.print(stackArr[i] + " "); 46 | } 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | StackUsingArray stack = new StackUsingArray(10); 52 | stack.push(10); 53 | stack.push(15); 54 | stack.push(20); 55 | stack.push(30); 56 | 57 | System.out.println("popped - " + stack.pop()); 58 | stack.push(40); 59 | 60 | stack.printStack(); 61 | } 62 | } -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/StackUsingSTL.cpp: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/stack-in-cpp-stl/ 2 | 3 | #include 4 | #include 5 | 6 | void printStack(std::stack foo) { 7 | std::stack bar = foo; 8 | 9 | while(!bar.empty()) { 10 | std::cout << "\t" << bar.top(); 11 | bar.pop(); 12 | } 13 | 14 | } 15 | 16 | int main() { 17 | 18 | std::stack foo; 19 | 20 | foo.push(10); 21 | foo.push(20); 22 | foo.push(30); 23 | 24 | std::cout << "\n top - " << foo.top(); 25 | std::cout << "\n size - " << foo.size(); 26 | 27 | foo.pop(); 28 | 29 | std::cout << "\n top - " << foo.top(); 30 | std::cout << "\n size - " << foo.size(); 31 | 32 | printStack(foo); 33 | 34 | std::cout << "\n top - " << foo.top(); 35 | std::cout << "\n size - " << foo.size(); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Basic Concepts/Data Structures/TreeDS.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/binary-tree-set-1-introduction/ 2 | 3 | class Node { 4 | int key; 5 | Node left, right; 6 | 7 | Node(int key) { 8 | this.key = key; 9 | left = right = null; 10 | } 11 | } 12 | 13 | class TreeDS { 14 | 15 | Node root; 16 | 17 | TreeDS() { 18 | root = null; 19 | } 20 | 21 | public static void main(String[] args) { 22 | TreeDS tree = new TreeDS(); 23 | 24 | tree.root = new Node(1); 25 | tree.root.left = new Node(2); 26 | tree.root.right = new Node(3); 27 | 28 | tree.root.left.left = new Node(4); 29 | } 30 | } -------------------------------------------------------------------------------- /Basic Concepts/Strings.gdoc: -------------------------------------------------------------------------------- 1 | {"url": "https://docs.google.com/open?id=1jcnZlxztzLKfhiDLk0SlkSeYnp1q8tLeGY5bxOy9DxU", "doc_id": "1jcnZlxztzLKfhiDLk0SlkSeYnp1q8tLeGY5bxOy9DxU", "email": "deepaksood619@gmail.com", "resource_id": "document:1jcnZlxztzLKfhiDLk0SlkSeYnp1q8tLeGY5bxOy9DxU"} -------------------------------------------------------------------------------- /CodeChef/July Cook Off/Chang and Bitwise OR.java: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/COOK84/problems/CHNGOR 2 | 3 | /* 4 | Problem Code: CHNGOR 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | class CHNGOR { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | 13 | int T = in.nextInt(); 14 | 15 | while(T-- > 0) { 16 | int N = in.nextInt(); 17 | int[] arr = new int[N]; 18 | 19 | int sum = 0; 20 | for(int i = 0; i < N; i++) { 21 | arr[i] = in.nextInt(); 22 | sum += arr[i]; 23 | } 24 | System.out.println("sum - " + sum); 25 | for(int i = 0; i < N-1; i++) { 26 | int foo = 0; 27 | for(int j = 0; j < N-1; j++) { 28 | foo += arr[i] | arr[j]; 29 | } 30 | if(foo < sum) { 31 | sum = foo; 32 | } 33 | } 34 | System.out.println(sum); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /CodeChef/July Cook Off/Chang and the Perfect Function.java: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/COOK84/problems/CHNGFUNC 2 | /* 3 | Problem Code: CHNGFUNC 4 | */ 5 | 6 | import java.util.Scanner; 7 | import java.math.*; 8 | 9 | class CHNGFUNC { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | 13 | int A = in.nextInt(); 14 | int B = in.nextInt(); 15 | 16 | int count = 0; 17 | 18 | for(int i = 1; i <= A; i++) { 19 | for(int j = 1; j <= B; j++) { 20 | 21 | if(isPerfectSquare(Math.pow(i, 2) + j)) { 22 | count++; 23 | } 24 | } 25 | } 26 | 27 | System.out.print(count); 28 | } 29 | 30 | static boolean isPerfectSquare(double val) { 31 | double foo = Math.sqrt(val); 32 | int bar = (int) foo; 33 | return val == bar * bar; 34 | } 35 | } -------------------------------------------------------------------------------- /CodeChef/SeptemberLongChallenge/ChefAndPickDigit.java: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/SEPT17/problems/CHEFPDIG 2 | // Problem code - CHEFPDIG 3 | 4 | /* 5 | Time Complexity - O(N) = N for couting sort + 26 for looping from 65 to 90 6 | Space Complexity - O(1) = 10 ints for storing count of digits from 0 to 10 7 | 8 | Test cases 9 | 4 10 | 65 11 | 566 12 | 11 13 | 1623455078 14 | */ 15 | 16 | import java.util.*; 17 | 18 | class ChefAndPickDigit { 19 | 20 | public static void main (String[] args) { 21 | 22 | Scanner in = new Scanner(System.in); 23 | 24 | String strT = in.nextLine(); 25 | 26 | int T = Integer.parseInt(strT); 27 | while(T-- > 0) { 28 | String strN = in.nextLine(); 29 | 30 | int[] arr = new int[10]; 31 | 32 | for(int i = 0; i < strN.length(); i++) { 33 | arr[strN.charAt(i) - 48]++; 34 | } 35 | 36 | for(int i = 65; i <= 90; i++) { 37 | int first = i/10; 38 | int second = i%10; 39 | if(first == second) { 40 | if(arr[first] > 1) { 41 | System.out.print((char)i); 42 | } 43 | } else { 44 | if(arr[first] > 0 && arr[second] > 0) { 45 | System.out.print((char)i); 46 | } 47 | } 48 | } 49 | System.out.println(); 50 | } 51 | 52 | in.close(); 53 | } 54 | } -------------------------------------------------------------------------------- /CodeChef/SeptemberLongChallenge/LittleChefAndSums.java: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/SEPT17/problems/CHEFSUM 2 | // Problem Code - CHEFSUM 3 | 4 | /* 5 | Time Complexity - 3*N = O(N) 6 | Space Complexity - 2*N = O(N) 7 | */ 8 | 9 | import java.util.*; 10 | 11 | class LittleChefAndSums { 12 | 13 | public static void main (String[] args) { 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | int T = in.nextInt(); 18 | while(T-- > 0) { 19 | int N = in.nextInt(); 20 | int[] arr = new int[N]; 21 | for(int i = 0; i < N; i++) { 22 | arr[i] = in.nextInt(); 23 | } 24 | 25 | long min = Long.MAX_VALUE; 26 | int index = 0; 27 | long[] pArr = new long[N]; 28 | long[] sArr = new long[N]; 29 | 30 | pArr[0] = arr[0]; 31 | for(int i = 1; i < N; i++) { 32 | pArr[i] = pArr[i-1] + arr[i]; 33 | } 34 | 35 | sArr[N-1] = arr[N-1]; 36 | for(int i = N-2; i >= 0; i--) { 37 | sArr[i] = sArr[i+1] + arr[i]; 38 | } 39 | 40 | long val; 41 | for(int i = 0; i < N; i++) { 42 | val = pArr[i] + sArr[i]; 43 | if(val < min) { 44 | min = val; 45 | index = i+1; 46 | } 47 | } 48 | 49 | System.out.println(index); 50 | 51 | } 52 | 53 | in.close(); 54 | } 55 | } 56 | 57 | /* 58 | 1st solution - 59 | Time complexity - O(N^2); 60 | Space Complexity - O(1) 61 | 62 | int min = Integer.MAX_VALUE; 63 | int index = 0; 64 | for(int i = 0; i < N; i++) { 65 | 66 | int prefixSum = 0; 67 | for(int j = 0; j <= i; j++) { 68 | prefixSum += arr[j]; 69 | } 70 | 71 | int suffixSum = 0; 72 | for(int j = N; j >= i; j--) { 73 | suffixSum += arr[j]; 74 | } 75 | 76 | int sum = prefixSum + suffixSum; 77 | if(sum < min) { 78 | min = sum; 79 | index = i+1; 80 | } 81 | } 82 | 83 | System.out.println(index); 84 | 85 | 86 | 2nd Solution- 87 | Time Complexity - 3*N = O(N) 88 | Space Complexity - 2*N = O(N) 89 | 90 | long min = Long.MAX_VALUE; 91 | int index = 0; 92 | long[] pArr = new long[N]; 93 | long[] sArr = new long[N]; 94 | 95 | pArr[0] = arr[0]; 96 | for(int i = 1; i < N; i++) { 97 | pArr[i] = pArr[i-1] + arr[i]; 98 | } 99 | 100 | sArr[N-1] = arr[N-1]; 101 | for(int i = N-2; i >= 0; i--) { 102 | sArr[i] = sArr[i+1] + arr[i]; 103 | } 104 | 105 | long val; 106 | for(int i = 0; i < N; i++) { 107 | val = pArr[i] + sArr[i]; 108 | if(val < min) { 109 | min = val; 110 | index = i+1; 111 | } 112 | } 113 | 114 | System.out.println(index); 115 | 116 | 3rd solution 117 | **Not worked for 1st and 2nd test cases, but worked for 3rd test case 118 | Time Complexity - 2*N = O(N) 119 | Space Complexity - 1*N = O(N) 120 | 121 | long[] pArr = new long[N]; 122 | 123 | pArr[0] = arr[0]; 124 | for(int i = 1; i < N; i++) { 125 | pArr[i] = pArr[i-1] + arr[i]; 126 | } 127 | 128 | long val = 0; 129 | long last = arr[N-1]; 130 | long min = pArr[N-1] + last; 131 | int index = N; 132 | long sum; 133 | 134 | for(int i = N-2; i >= 0; i--) { 135 | val = last + arr[i]; 136 | last = val; 137 | 138 | sum = val + pArr[i]; 139 | if(sum <= min) { 140 | min = sum; 141 | index = i; 142 | } 143 | } 144 | 145 | index++; 146 | System.out.println(index); 147 | 148 | */ -------------------------------------------------------------------------------- /CodeChef/SeptemberLongChallenge/MinimumGoodPermutation.java: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/SEPT17/problems/MINPERM 2 | // Problem code - MINPERM 3 | 4 | /* 5 | Time Complexity - O(N) 6 | Space Complexity - O(1) 7 | */ 8 | 9 | import java.util.*; 10 | 11 | class MinimumGoodPermutation { 12 | 13 | public static void main (String[] args) { 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | int T = in.nextInt(); 18 | while(T-- > 0) { 19 | int n = in.nextInt(); 20 | 21 | if(n % 2 == 0) { 22 | // even 23 | int i = 2; 24 | while(i <= n) { 25 | System.out.print(i + " " + (i-1)); 26 | i += 2; 27 | if(i <= n) { 28 | System.out.print(" "); 29 | } 30 | } 31 | } else { 32 | // odd 33 | int i = 2; 34 | while(i <= n-3) { 35 | System.out.print(i + " " + (i-1) + " "); 36 | i += 2; 37 | } 38 | System.out.print(i + " " + (i+1) + " " + (i-1)); 39 | } 40 | System.out.println(); 41 | 42 | } 43 | 44 | in.close(); 45 | } 46 | } -------------------------------------------------------------------------------- /CodeChef/SeptemberLongChallenge/SerejaAndCommands.java: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/SEPT17/problems/SEACO 2 | // Problem Code - SEACO 3 | 4 | /* 5 | 1st test case solved 6 | 2nd test case - WA 7 | 3rd test case - TLE 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class SerejaAndCommands { 13 | 14 | public static void main (String[] args) { 15 | 16 | Scanner in = new Scanner(System.in); 17 | 18 | int T = in.nextInt(); 19 | while(T-- > 0) { 20 | 21 | int n = in.nextInt(); 22 | int m = in.nextInt(); 23 | 24 | Solve solve = new Solve(n, m); 25 | 26 | for( int i = 0; i < m; i++ ) { 27 | int t = in.nextInt(); 28 | int l = in.nextInt(); 29 | int r = in.nextInt(); 30 | --l; 31 | --r; 32 | 33 | solve.addCommand(t, l, r); 34 | } 35 | 36 | solve.runCommands(0, m-1); 37 | 38 | solve.print(); 39 | 40 | } 41 | 42 | in.close(); 43 | } 44 | 45 | static void inc(int[] arr, int l, int r) { 46 | for(int i = l; i <= r; i++) { 47 | arr[i]++; 48 | } 49 | } 50 | } 51 | 52 | class Solve { 53 | // size of arr 54 | int n; 55 | 56 | // num of commands 57 | int m; 58 | 59 | int[] arr; 60 | ArrayList commands; 61 | int[] lastSnapshot; 62 | 63 | Solve(int n, int m) { 64 | this.n = n; 65 | this.m = m; 66 | arr = new int[n]; 67 | commands = new ArrayList<>(m); 68 | lastSnapshot = new int[n]; 69 | } 70 | 71 | public void addCommand(int t, int l, int r) { 72 | commands.add(new Command(t, l, r, n)); 73 | } 74 | 75 | public void runCommands(int l, int r) { 76 | for(int i = l; i <= r; i++) { 77 | Command comm = commands.get(i); 78 | if(comm.t == 1) { 79 | inc(comm.l, comm.r, 1); 80 | } else { 81 | if(!comm.init) { 82 | System.arraycopy(arr, 0, lastSnapshot, 0, n); 83 | runCommands(comm.l, comm.r); 84 | comm.init = true; 85 | for(int k = 0; k < n; k++) { 86 | comm.add[k] = arr[k] - lastSnapshot[k]; 87 | } 88 | 89 | } else { 90 | for(int k = 0; k < n; k++) { 91 | arr[k] += comm.add[k]; 92 | } 93 | } 94 | } 95 | } 96 | } 97 | 98 | public void inc(int l, int r, int add) { 99 | for(int i = l; i <= r; i++) { 100 | arr[i] += add; 101 | } 102 | } 103 | 104 | public void print() { 105 | for(int i = 0; i < n; i++) { 106 | System.out.print(arr[i] + " "); 107 | } 108 | System.out.println(); 109 | } 110 | } 111 | 112 | class Command { 113 | int t; 114 | int l; 115 | int r; 116 | int n; 117 | int[] add; 118 | boolean init; 119 | 120 | Command(int t, int l, int r, int n) { 121 | this.t = t; 122 | this.l = l; 123 | this.r = r; 124 | this.n = n; 125 | if(t == 2) { 126 | add = new int[n]; 127 | } 128 | init = false; 129 | } 130 | } -------------------------------------------------------------------------------- /FastIO.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | ios::sync_with_stdio(0); 9 | cin.tie(NULL); 10 | 11 | cout << "Hello World!\n"; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /FastIO.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.io.IOException; 4 | import java.util.StringTokenizer; 5 | 6 | class test { 7 | 8 | static class FastReader { 9 | BufferedReader br; 10 | StringTokenizer st; 11 | 12 | public FastReader() { 13 | br = new BufferedReader(new InputStreamReader(System.in)); 14 | } 15 | 16 | String next() { 17 | while(st == null || !st.hasMoreElements()) { 18 | try { 19 | st = new StringTokenizer(br.readLine()); 20 | } catch(IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | return st.nextToken(); 25 | } 26 | 27 | int nextInt() { 28 | return Integer.parseInt(next()); 29 | } 30 | 31 | long nextLong() { 32 | return Long.parseLong(next()); 33 | } 34 | 35 | double nextDouble() { 36 | return Double.parseDouble(next()); 37 | } 38 | 39 | String nextLine() { 40 | String str = ""; 41 | try { 42 | str = br.readLine(); 43 | } catch(IOException e){ 44 | e.printStackTrace(); 45 | } 46 | return str; 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | FastReader s = new FastReader(); 52 | int t = s.nextInt(); 53 | 54 | while(t-- > 0) { 55 | int n = s.nextInt(); 56 | s.nextInt(); 57 | String one = s.nextLine(); 58 | String two = s.nextLine(); 59 | Double doub = s.nextDouble(); 60 | 61 | System.out.println(n + " " + one + " " + two + " " + doub); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/CheckForSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/check-for-subsequence/0 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | 9 | ios::sync_with_stdio(0); 10 | cin.tie(0); 11 | 12 | int T; 13 | cin >> T; 14 | 15 | char a[1005], b[1005]; 16 | int i, j = 0; 17 | while(T-- > 0) { 18 | 19 | j = 0; 20 | 21 | cin >> a >> b; 22 | 23 | for(i = 0; i < strlen(b) && j < strlen(a); i++) { 24 | if(a[j] == b[i]) { 25 | j++; 26 | } 27 | } 28 | 29 | cout << (j == strlen(a)) << "\n"; 30 | 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/DetectCycleInDirectedGraph.java: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/?p=18516 2 | // http://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1 3 | 4 | /* 5 | Using DFS 6 | Depth First Traversal can be used to detect cycle in a Graph. 7 | DFS for a connected graph produces a tree. 8 | There is a cycle in a graph only if there is a back edge present in the graph. 9 | A back edge is an edge that is from a node to itself (selfloop) or one of its ancestor in the tree produced by DFS. 10 | 11 | To detect a back edge, we can keep track of vertices currently in recursion stack of function for DFS traversal. 12 | If we reach a vertex that is already in the recursion stack, then there is a cycle in the tree. 13 | The edge that connects current vertex to the vertex in the recursion stack is back edge. 14 | 15 | Time Complexity - O(V+E) 16 | Space Complexity - O(V+E) 17 | */ 18 | 19 | import java.util.Scanner; 20 | import java.util.ArrayList; 21 | import java.util.Iterator; 22 | import java.util.LinkedList; 23 | 24 | class DetectCycleInDirectedGraph { 25 | 26 | public static void main(String[] args) { 27 | Scanner in = new Scanner(System.in); 28 | int T = in.nextInt(); 29 | 30 | while(T-- > 0) { 31 | int N = in.nextInt(); 32 | int M = in.nextInt(); 33 | 34 | Graph graph = new Graph(N); 35 | 36 | for(int i = 0; i < M; i++) { 37 | int u = in.nextInt(); 38 | int v = in.nextInt(); 39 | 40 | graph.addEdge(u, v); 41 | 42 | } 43 | 44 | System.out.println(graph.detectCycle()); 45 | } 46 | } 47 | } 48 | 49 | class Graph { 50 | int N; 51 | ArrayList> adjList; 52 | boolean[] visited; 53 | boolean[] explored; 54 | 55 | Graph(int N) { 56 | this.N = N; 57 | adjList = new ArrayList<>(N); 58 | visited = new boolean[N]; 59 | explored = new boolean[N]; 60 | 61 | for(int i = 0; i < N; i++) { 62 | adjList.add(new LinkedList<>()); 63 | } 64 | } 65 | 66 | void addEdge(int u, int v) { 67 | adjList.get(u).add(v); 68 | } 69 | 70 | boolean detectCycle() { 71 | for(int i = 0; i < N; i++) { 72 | if(dfs(i)) { 73 | return true; 74 | } 75 | } 76 | return false; 77 | } 78 | 79 | boolean dfs(int src) { 80 | if(!visited[src]) { 81 | visited[src] = true; 82 | explored[src] = true; 83 | 84 | Iterator iterator = adjList.get(src).iterator(); 85 | 86 | int vertex = 0; 87 | 88 | while(iterator.hasNext()) { 89 | vertex = iterator.next(); 90 | if(!visited[vertex] || !explored[src]) { 91 | if(dfs(vertex)) { 92 | return true; 93 | } 94 | } else { 95 | return true; 96 | } 97 | } 98 | explored[src] = false; 99 | } 100 | return false; 101 | } 102 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/EditDistance.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/edit-distance/0 2 | 3 | /* 4 | Using Dynamic Programming memoization 5 | 6 | Time Complexity - O(m*n) 7 | Space Complexity - O(m*n) 8 | 9 | 2 10 | 4 5 11 | geek gesek 12 | 6 8 13 | sunday saturday 14 | 15 | 1 16 | 7 6 17 | sitting kitten 18 | */ 19 | 20 | import java.util.Scanner; 21 | 22 | class EditDistance { 23 | public static void main(String[] args) { 24 | Scanner in = new Scanner(System.in); 25 | 26 | int T = in.nextInt(); 27 | 28 | while(T-- > 0) { 29 | int P = in.nextInt(); 30 | int Q = in.nextInt(); 31 | in.nextLine(); 32 | String line = in.nextLine(); 33 | String[] splitLine = line.split(" "); 34 | String str1 = splitLine[0]; 35 | String str2 = splitLine[1]; 36 | 37 | int[][] tab = new int[P+1][Q+1]; 38 | 39 | System.out.println(editDistance(str1, str2, P, Q, tab)); 40 | } 41 | } 42 | 43 | static int editDistance(String str1, String str2, int i, int j, int[][] tab) { 44 | for (int m = 0; m <= i; m++) { 45 | for (int n = 0; n <= j; n++) { 46 | if (m == 0) 47 | tab[m][n] = n; 48 | else if (n == 0) 49 | tab[m][n] = m; 50 | else if (str1.charAt(m-1) == str2.charAt(n-1)) 51 | tab[m][n] = tab[m-1][n-1]; 52 | else 53 | tab[m][n] = 1 + min(tab[m][n-1], tab[m-1][n], tab[m-1][n-1]); 54 | } 55 | } 56 | return tab[i][j]; 57 | } 58 | 59 | static int min(int x, int y, int z) { 60 | if(x < y) 61 | return (x < z) ? x : z; 62 | else 63 | return (y < z) ? y : z; 64 | } 65 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/HighestPrime.cpp: -------------------------------------------------------------------------------- 1 | // http://www.geeksforgeeks.org/find-highest-occurring-digit-prime-numbers-range/ 2 | // http://practice.geeksforgeeks.org/problems/find-the-highest-occurring-digit-in-prime-numbers-in-a-range/0 3 | 4 | #include 5 | 6 | void sieve(bool prime[], int r) { 7 | for(int i = 2; i*i <= r; i++) { 8 | if(prime[i]) 9 | for(int j = i+i; j <= r; j += i) 10 | prime[j] = false; 11 | } 12 | } 13 | 14 | int maxDigitInRange(bool prime[], int l, int r) { 15 | 16 | int freq[10] = {0}; 17 | 18 | for(int i = l; i <= r; i++) 19 | if(prime[i]) { 20 | int p = i; 21 | while(p) { 22 | freq[p%10]++; 23 | p /= 10; 24 | } 25 | } 26 | 27 | int max = freq[0]; 28 | int ans = -1; 29 | 30 | for (int i = 0; i <= 9; i++) { 31 | if(freq[i] != 0 && freq[i] >= max) { 32 | max = freq[i]; 33 | ans = i; 34 | } 35 | } 36 | 37 | return ans; 38 | } 39 | 40 | int main() { 41 | int t; 42 | 43 | std::cin >> t; 44 | 45 | int maxR = 0; 46 | int arr[t][2]; 47 | for(int i = 0; i < t; i++) { 48 | std::cin >> arr[i][0] >> arr[i][1]; 49 | 50 | if(arr[i][1] > maxR) { 51 | maxR = arr[i][1]; 52 | } 53 | } 54 | 55 | bool prime[maxR+1]; 56 | memset(prime, true, sizeof(prime)); 57 | sieve(prime, maxR); 58 | 59 | for(int i = 0; i < t; i++) { 60 | int result = maxDigitInRange(prime, arr[i][0], arr[i][1]); 61 | std::cout << result << '\n'; 62 | } 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/LargestEvenNumber.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/largest-even-number/0 2 | 3 | // 284918227595347128185772596567355423933679973674289434574127522843135379266 4 | 5 | // print largest even number 6 | /* 7 | used counting sort, and then print from largest to smallest 8 | with saving one smallest even number i.e. 8, 6, 4, 2, 0 9 | and then printing the smallest even number at last if present 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | class LargestEvenNumber { 15 | public static void main(String[] args) { 16 | 17 | //code 18 | 19 | Scanner scanner = new Scanner(System.in); 20 | String n1 = scanner.nextLine(); 21 | int n = Integer.parseInt(n1); 22 | 23 | int[] indexArr; 24 | int j, k; 25 | 26 | for(int i = 0; i < n; i++) { 27 | indexArr = new int[10]; 28 | 29 | String input1 = scanner.nextLine(); 30 | char[] arr = input1.toCharArray(); 31 | 32 | for(int p = 0; p < arr.length; p++) { 33 | indexArr[Character.getNumericValue(arr[p])]++; 34 | } 35 | 36 | int even = -1; 37 | // find smallest even number 38 | for(j = 0; j < 10; j++) { 39 | if(indexArr[j] > 0 && j%2 == 0) { 40 | even = j; 41 | break; 42 | } 43 | } 44 | 45 | for(j = 9; j > even; j--) { 46 | for(k = 0; k < indexArr[j]; k++) { 47 | System.out.print(j); 48 | } 49 | } 50 | 51 | if(even != -1) { 52 | for(k = 0; k < indexArr[even]-1; k++) { 53 | System.out.print(even); 54 | } 55 | } 56 | 57 | if(even > 0) { 58 | for(j = even - 1; j >= 0; j--) { 59 | for(k = 0; k < indexArr[j]; k++) { 60 | System.out.print(j); 61 | } 62 | } 63 | } 64 | 65 | if(even != -1) { 66 | System.out.print(even); 67 | } 68 | 69 | System.out.println(); 70 | } 71 | 72 | } 73 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/LargestPrimeFactor.cpp: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/largest-prime-factor/0 2 | 3 | #include 4 | #include 5 | 6 | int largestFactor(int n) { 7 | int largest = 0; 8 | 9 | while(n%2 == 0) { 10 | n /= 2; 11 | largest = 2; 12 | } 13 | 14 | for(int i = 3; i <= sqrt(n); i += 2) { 15 | while(n%i == 0) { 16 | n /= i; 17 | largest = i; 18 | } 19 | } 20 | 21 | if(n > 2) { 22 | largest = n; 23 | } 24 | 25 | return largest; 26 | } 27 | 28 | int main() { 29 | 30 | int t; 31 | 32 | scanf("%d", &t); 33 | 34 | int val = 0; 35 | 36 | for(int i = 0; i < t; i++) { 37 | scanf("%d", &val); 38 | printf("%d\n", largestFactor(val)); 39 | } 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/LeastPrimeFactor.cpp: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/least-prime-factor/0 2 | 3 | // http://www.geeksforgeeks.org/least-prime-factor-of-numbers-till-n/ 4 | 5 | #include 6 | // for memset 7 | #include 8 | 9 | void modifiedSieve(int leastPrimeFactor[], int max) { 10 | leastPrimeFactor[1] = 1; 11 | 12 | for(int i = 2; i <= max; i++) { 13 | if(leastPrimeFactor[i] == 0) { 14 | leastPrimeFactor[i] = i; 15 | for(int j = i+i; j <= max; j += i) { 16 | if(leastPrimeFactor[j] == 0) 17 | leastPrimeFactor[j] = i; 18 | } 19 | } 20 | } 21 | } 22 | 23 | int main() { 24 | int t; 25 | 26 | scanf("%d", &t); 27 | 28 | int arr[t]; 29 | int max = 0; 30 | for(int i = 0; i < t; i++) { 31 | scanf("%d", &arr[i]); 32 | if(arr[i] > max) { 33 | max = arr[i]; 34 | } 35 | } 36 | 37 | int leastPrimeFactor[max+1]; 38 | memset(leastPrimeFactor, 0, sizeof(leastPrimeFactor)); 39 | 40 | modifiedSieve(leastPrimeFactor, max); 41 | 42 | for(int i = 0; i < t; i++) { 43 | for(int j = 1; j <= arr[i]; j++) { 44 | printf("%d ", leastPrimeFactor[j]); 45 | } 46 | printf("\n"); 47 | } 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/NMeetingsInOneRoom.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/n-meetings-in-one-room/0 2 | 3 | /* 4 | Thought process - 5 | Since after sorting the index of the meetings changes, an array with meetings index is saved so that it can be used to give the index of meetings. 6 | 7 | The meetings are sorted in ascending order according to there finish time, if next meeting has a start time greater than or equal to the previous finish time, the meeting is selected. 8 | Greedy approach is used to get the most optimal solution at that time. 9 | 10 | Algorithmic Approach - Greedy Algorithm 11 | 12 | Time Complexity - O(N*log(N)) 13 | Space Complexity - O(N) - extra space for storing index of the meetings 14 | 15 | */ 16 | 17 | import java.util.Scanner; 18 | import java.util.Arrays; 19 | import java.util.Comparator; 20 | 21 | class NMeetingsInOneRoom { 22 | 23 | public static void main(String[] args) { 24 | Scanner in = new Scanner(System.in); 25 | int T = in.nextInt(); 26 | 27 | while(T-- > 0) { 28 | int N = in.nextInt(); 29 | 30 | int[][] arr = new int[N][3]; 31 | 32 | for(int i = 0; i < N; i++) { 33 | arr[i][2] = i+1; 34 | } 35 | 36 | for(int i = 0; i < 2; i++) { 37 | for(int j = 0; j < N; j++) { 38 | int k = in.nextInt(); 39 | arr[j][i] = k; 40 | } 41 | } 42 | 43 | Arrays.sort(arr, new Comparator() { 44 | @Override 45 | public int compare(int[] a, int[] b) { 46 | return Integer.compare(a[1], b[1]); 47 | } 48 | }); 49 | 50 | int count = 0; 51 | int selected_index = 0; 52 | if(arr.length > 0) { 53 | count++; 54 | System.out.print(arr[selected_index][2] + " "); 55 | } 56 | 57 | for(int i = 1; i < arr.length; i++) { 58 | if(arr[i][0] >= arr[selected_index][1]) { 59 | count++; 60 | selected_index = i; 61 | System.out.print(arr[selected_index][2] + " "); 62 | } 63 | } 64 | 65 | System.out.println(); 66 | } 67 | } 68 | } 69 | 70 | /* 71 | Solution using class as an object (Meeting) 72 | 73 | class Test { 74 | public static void main (String[] args) { 75 | Scanner in = new Scanner(System.in); 76 | int T = in.nextInt(); 77 | 78 | while(T-- > 0) { 79 | int n = in.nextInt(); 80 | Meeting[] arr = new Meeting[n]; 81 | for(int i = 0; i < n; i++) { 82 | arr[i] = new Meeting(); 83 | } 84 | for(int i = 0; i < n; i++) { 85 | arr[i].start = in.nextInt(); 86 | arr[i].index = i; 87 | } 88 | for(int i = 0; i < n; i++) { 89 | arr[i].finish = in.nextInt(); 90 | } 91 | 92 | for(int i = 0; i < n; i++) { 93 | System.out.println(arr[i].start + " " + arr[i].finish); 94 | } 95 | 96 | Arrays.sort(arr, new Comparator() { 97 | @Override 98 | public int compare(Meeting a, Meeting b) { 99 | return Integer.compare(a.finish, b.finish); 100 | } 101 | }); 102 | 103 | for(int i = 0; i < n; i++) { 104 | System.out.println(arr[i].start + " " + arr[i].finish); 105 | } 106 | 107 | int last_index = 0; 108 | System.out.print(arr[0].index+1 + " "); 109 | for(int i = 1; i < n-1; i++) { 110 | if(arr[i].start >= arr[last_index].finish) { 111 | System.out.print(arr[i].index+1 + " "); 112 | last_index = i; 113 | } 114 | } 115 | System.out.println(); 116 | } 117 | } 118 | } 119 | 120 | class Meeting { 121 | int start; 122 | int finish; 123 | int index; 124 | } 125 | 126 | */ -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/PalindromeString.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/palindrome-string/0 2 | 3 | /* 4 | 1. one solution is to check from end and front and compare characters till middle 5 | 2. second solution is to reverse the string and compare the reversed and orginal string 6 | 7 | used 1st method, less time complexity 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | class PalindromeString { 13 | public static void main(String[] args) { 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | int t = in.nextInt(); 18 | 19 | while(t-- > 0) { 20 | int len = in.nextInt(); 21 | 22 | String input = in.next(); 23 | boolean isPalindrome = true; 24 | 25 | for(int i = 0; i < len/2; i++) { 26 | if(input.charAt(i) != input.charAt(len - i - 1)) { 27 | isPalindrome = false; 28 | } 29 | } 30 | 31 | String out = isPalindrome ? "Yes" : "No"; 32 | System.out.println(out); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/PathInMatrix.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/path-in-matrix/0 2 | 3 | /* 4 | 5 | Using Dynamic Programming 6 | 7 | Time complexity - O(M*N) 8 | 9 | 1 10 | 2 11 | 348 391 618 193 12 | 13 | 1 14 | 3 15 | 1 2 3 4 8 2 1 5 3 16 | */ 17 | 18 | import java.util.Scanner; 19 | 20 | class PathInMatrix { 21 | public static void main(String[] args) { 22 | Scanner in = new Scanner(System.in); 23 | 24 | int T = in.nextInt(); 25 | 26 | while(T-- > 0) { 27 | int N = in.nextInt(); 28 | int[][] arr = new int[N][N]; 29 | int[][] save = new int[N][N]; 30 | 31 | for(int i = 0; i < N; i++) { 32 | for(int j = 0; j < N; j++) { 33 | arr[i][j] = in.nextInt(); 34 | } 35 | } 36 | 37 | System.out.println(startMaxPath(arr, N, save)); 38 | } 39 | } 40 | 41 | static int startMaxPath(int[][] arr, int N, int[][] save) { 42 | int max = 0; 43 | for(int i = 0; i < N; i++) { 44 | int val = maxPath(arr, 0, i, N, save); 45 | if(val > max) { 46 | max = val; 47 | } 48 | } 49 | return max; 50 | } 51 | 52 | static int maxPath(int[][] arr, int x, int y, int N, int[][] save) { 53 | if(x >= N || y>= N || y < 0) { 54 | return 0; 55 | } else if(x == N-1) { 56 | return arr[x][y]; 57 | } else if(save[x][y] != 0) { 58 | return save[x][y]; 59 | } else { 60 | save[x][y] = arr[x][y] + max(maxPath(arr, x+1, y-1, N, save), maxPath(arr, x+1, y, N, save), maxPath(arr, x+1, y+1, N, save)); 61 | return save[x][y]; 62 | } 63 | } 64 | 65 | static int max(int x, int y, int z) { 66 | if(x > y) 67 | return (x > z) ? x : z; 68 | else 69 | return (y > z) ? y : z; 70 | } 71 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/SortTheArray.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/sort-the-array/0 2 | /* 3 | Used Quick Sort Algorithm 4 | */ 5 | import java.util.Scanner; 6 | 7 | class SortTheArray 8 | { 9 | 10 | static int partition(int[] arr, int low, int high) { 11 | int pivot = arr[high]; 12 | 13 | int i = low -1; 14 | 15 | for(int j = low; j <= high-1; j++) { 16 | if(arr[j] <= pivot) { 17 | i++; 18 | int temp = arr[i]; 19 | arr[i] = arr[j]; 20 | arr[j] = temp; 21 | } 22 | } 23 | int temp = arr[i+1]; 24 | arr[i+1] = arr[high]; 25 | arr[high] = temp; 26 | return i+1; 27 | } 28 | 29 | static void quickSort(int[] arr, int low, int high) { 30 | if(low < high) { 31 | int pi = partition(arr, low, high); 32 | quickSort(arr, low, pi-1); 33 | quickSort(arr, pi+1, high); 34 | } 35 | } 36 | 37 | public static void main (String[] args) 38 | { 39 | Scanner in = new Scanner(System.in); 40 | int T = in.nextInt(); 41 | while(T-- > 0) { 42 | int N = in.nextInt(); 43 | int[] arr = new int[N]; 44 | 45 | for(int i = 0; i < N; i++) { 46 | arr[i] = in.nextInt(); 47 | } 48 | 49 | quickSort(arr, 0, N-1); 50 | 51 | for(int i = 0; i < N; i++) { 52 | System.out.print(arr[i] + " "); 53 | } 54 | System.out.println(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/SumOfDigitIsPalindromeOrNot.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/sum-of-digit-is-pallindrome-or-not/0 2 | 3 | import java.util.Scanner; 4 | 5 | class SumOfDigitIsPalindromeOrNot { 6 | public static void main(String[] args) { 7 | 8 | Scanner in = new Scanner(System.in); 9 | 10 | int T = in.nextInt(); 11 | 12 | /*for(int i = 0; i < T; i++) { 13 | int sum = 0; 14 | String input = in.next(); 15 | for(int j = 0; j < input.length(); j++) { 16 | sum += Character.getNumericValue(input.charAt(j)); 17 | } 18 | 19 | String palindrome = Integer.toString(sum); 20 | 21 | boolean isPalindrome = true; 22 | for(int k = 0; k < palindrome.length()/2; k++) { 23 | if(palindrome.charAt(k) != palindrome.charAt(palindrome.length() - k - 1)) { 24 | isPalindrome = false; 25 | } 26 | } 27 | 28 | if(isPalindrome) { 29 | System.out.println("YES"); 30 | } else { 31 | System.out.println("NO"); 32 | } 33 | }*/ 34 | 35 | // optimized - removed the conversion from every char to int while adding the digits of input String 36 | 37 | while(T-- > 0) { 38 | int input = in.nextInt(); 39 | int sum = 0; 40 | while(input > 0) { 41 | sum += input%10; 42 | input = input / 10; 43 | } 44 | 45 | String palindrome = Integer.toString(sum); 46 | 47 | boolean isPalindrome = true; 48 | for(int k = 0; k < palindrome.length()/2; k++) { 49 | if(palindrome.charAt(k) != palindrome.charAt(palindrome.length() - k - 1)) { 50 | isPalindrome = false; 51 | } 52 | } 53 | 54 | String output = isPalindrome ? "YES" : "NO"; 55 | 56 | System.out.println(output); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Algorithms/XTotalShapes.java: -------------------------------------------------------------------------------- 1 | // http://practice.geeksforgeeks.org/problems/x-total-shapes/0 2 | 3 | 4 | /* 5 | 1 6 | 3 7 7 | OOOXOOO 8 | OXXXXXO 9 | OXOOOXO 10 | */ 11 | import java.util.Scanner; 12 | 13 | class XTotalShapes { 14 | 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | 18 | int T = in.nextInt(); 19 | 20 | while(T-- > 0) { 21 | int N = in.nextInt(); 22 | int M = in.nextInt(); 23 | 24 | String[] arr = new String[N]; 25 | 26 | for(int i = 0; i < N; i++) { 27 | arr[i] = in.next(); 28 | } 29 | 30 | /*for(int i = 0; i < N; i++) { 31 | System.out.print(arr[i] + " "); 32 | } 33 | System.out.println();*/ 34 | 35 | boolean[][] visited = new boolean[N][M]; 36 | 37 | int count = 0; 38 | 39 | for(int i = 0; i < N; i++) { 40 | for(int j = 0; j < M; j++) { 41 | //System.out.println("out i - " + i + "out j - " + j); 42 | if(arr[i].charAt(j) == 'X' && !visited[i][j]) { 43 | count++; 44 | //System.out.println("in i - " + i + " in j - " + j); 45 | markConnectedX(arr, visited, i, j, N, M); 46 | } 47 | } 48 | } 49 | 50 | System.out.println(count); 51 | 52 | /*System.out.println(); 53 | for(int i = 0; i < N; i++) { 54 | for(int j = 0; j < M; j++) { 55 | System.out.print(visited[i][j] + " "); 56 | } 57 | System.out.println(); 58 | } 59 | */ 60 | } 61 | } 62 | 63 | static void markConnectedX(String[] arr, boolean[][] visited, int i, int j, int N, int M) { 64 | //System.out.println("i - " + i + " j - " + j); 65 | if(arr[i].charAt(j) == 'X' && !visited[i][j]) { 66 | visited[i][j] = true; 67 | 68 | if(i + 1 < N) 69 | markConnectedX(arr, visited, i+1, j, N, M); 70 | 71 | if(i - 1 >= 0) 72 | markConnectedX(arr, visited, i-1, j, N, M); 73 | 74 | if(j + 1 < M) 75 | markConnectedX(arr, visited, i, j+1, N, M); 76 | 77 | if(j - 1 >= 0) 78 | markConnectedX(arr, visited, i, j-1, N, M); 79 | } 80 | } 81 | 82 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/Anagrams.c: -------------------------------------------------------------------------------- 1 | /* 2 | 0-9 - 48-57 3 | A-Z - 65-90 4 | a-z - 97-122 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | int main() { 12 | 13 | int t, i, diff; 14 | scanf("%d", &t); 15 | 16 | while(t-- > 0) { 17 | 18 | char a[10001], b[10001]; 19 | scanf("%s %s", a, b); 20 | 21 | int countA[26] = {0}; 22 | int countB[26] = {0}; 23 | 24 | for(i = 0; i < strlen(a); i++) { 25 | countA[a[i]-97]++; 26 | } 27 | 28 | for(i = 0; i < strlen(b); i++) { 29 | countB[b[i]-97]++; 30 | } 31 | 32 | diff = 0; 33 | for(i = 0; i < 26; i++) { 34 | diff += abs(countA[i] - countB[i]); 35 | } 36 | 37 | printf("%d\n", diff); 38 | } 39 | return 0; 40 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/AsciiValue.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | char ch; 5 | scanf("%c", &ch); 6 | printf("%d", ch); 7 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/CountDivisors.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | 5 | int l, r, k; 6 | scanf("%d %d %d", &l, &r, &k); 7 | 8 | int count = 0; 9 | for(int i = l; i <= r; i++) { 10 | if(i%k == 0) 11 | count++; 12 | } 13 | 14 | printf("%d", count); 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/Factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fact(int n) { 4 | int fact = 1; 5 | for(int i = 2; i <= n; i++) { 6 | fact *= i; 7 | } 8 | return fact; 9 | } 10 | 11 | int main() { 12 | 13 | int n; 14 | scanf("%d", &n); 15 | 16 | printf("%d", fact(n)); 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/FindProduct.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int MOD = 1000000007; 4 | 5 | int main() { 6 | 7 | int n; 8 | scanf("%d", &n); 9 | 10 | int val = 0; 11 | long int product = 1; 12 | for(int i = 0; i < n; i++) { 13 | scanf("%d", &val); 14 | product = (product * val)%MOD; 15 | } 16 | printf("%ld", product); 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/MagicalWord.c: -------------------------------------------------------------------------------- 1 | /* 2 | 0-9 - 48-57 3 | A-Z - 65-90 (67, 71, 73, 79, 83, 89) 4 | a-z - 97-122 (97, 101, 103, 107, 109, 113, 127) 5 | */ 6 | 7 | #include 8 | 9 | int main() { 10 | 11 | int t; 12 | scanf("%d", &t); 13 | 14 | int s; 15 | char ch; 16 | while(t-- > 0) { 17 | scanf("%d", &s); 18 | getchar(); 19 | 20 | for(int i = 0; i < s; i++) { 21 | ch = getchar(); 22 | 23 | int val = 0; 24 | 25 | if(ch <= 69) { 26 | val = 67; 27 | } else if(ch <= 72) { 28 | val = 71; 29 | } else if(ch <= 76) { 30 | val = 73; 31 | } else if(ch <= 81) { 32 | val = 79; 33 | } else if(ch <= 86) { 34 | val = 83; 35 | } else if(ch <= 93) { 36 | val = 89; 37 | } else if(ch <= 99) { 38 | val = 97; 39 | } else if(ch <= 102) { 40 | val = 101; 41 | } else if(ch <= 105) { 42 | val = 103; 43 | } else if(ch <= 108) { 44 | val = 107; 45 | } else if(ch <= 111) { 46 | val = 109; 47 | } else { 48 | val = 113; 49 | } 50 | 51 | printf("%c", val); 52 | } 53 | printf("\n"); 54 | } 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/PalindromicString.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void palindrome(char *s) { 4 | // get length of the string 5 | int i = 0; 6 | while(s[i] != '\0') { 7 | i++; 8 | } 9 | i--; 10 | 11 | // check palindrome 12 | int j = 0; 13 | while(j <= i) { 14 | if(s[i] != s[j]) { 15 | printf("NO"); 16 | return; 17 | } 18 | i--; 19 | j++; 20 | } 21 | printf("YES"); 22 | } 23 | 24 | int main() 25 | { 26 | char s[101]; 27 | scanf("%s", s); 28 | 29 | palindrome(s); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/PlayWithNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void fastscan(int &number) 4 | { 5 | //variable to indicate sign of input number 6 | bool negative = false; 7 | register int c; 8 | 9 | number = 0; 10 | 11 | // extract current character from buffer 12 | c = getchar(); 13 | if (c=='-') 14 | { 15 | // number is negative 16 | negative = true; 17 | 18 | // extract the next character from the buffer 19 | c = getchar(); 20 | } 21 | 22 | // Keep on extracting characters if they are integers 23 | // i.e ASCII Value lies from '0'(48) to '9' (57) 24 | for (; (c>47 && c<58); c=getchar()) 25 | number = number *10 + c - 48; 26 | 27 | // if scanned input has a negative sign, negate the 28 | // value of the input number 29 | if (negative) 30 | number *= -1; 31 | } 32 | 33 | int main() { 34 | 35 | int n, q; 36 | fastscan(n); 37 | fastscan(q); 38 | 39 | int arr[n]; 40 | int val; 41 | for(int i = 0; i < n; i++) { 42 | fastscan(val); 43 | arr[i] = val; 44 | } 45 | 46 | int l, r, mean; 47 | for(int i = 0; i < q; i++) { 48 | fastscan(l); 49 | fastscan(r); 50 | mean = 0; 51 | for(int j = l-1; j < r; j++) { 52 | mean += arr[j]; 53 | } 54 | mean /= r-l+1; 55 | printf("%d\n", mean); 56 | } 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/PrimeNumber.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void sieve(int n) { 6 | bool prime[n+1]; 7 | memset(prime, true, n+1); 8 | 9 | for(int i = 2; i <= n; i++) { 10 | if(prime[i]) { 11 | for(int j = i+i; j <= n; j += i) { 12 | prime[j] = false; 13 | } 14 | printf("%d ", i); 15 | } 16 | } 17 | } 18 | 19 | int main() { 20 | 21 | int n; 22 | scanf("%d", &n); 23 | 24 | sieve(n); 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/RoyAndProfilePicture.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | 5 | int l, n; 6 | scanf("%d %d", &l, &n); 7 | 8 | int w, h; 9 | for(int i = 0; i < n; i++) { 10 | scanf("%d %d", &w, &h); 11 | 12 | if(w < l || h < l) { 13 | printf("UPLOAD ANOTHER\n"); 14 | } else if(w == h) { 15 | printf("ACCEPTED\n"); 16 | } else { 17 | printf("CROP IT\n"); 18 | } 19 | 20 | } 21 | 22 | return 0; 23 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/SeatingArrangement.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void showStats(int n) { 4 | switch(n%12) { 5 | case 0: 6 | printf("%d ", n-11); 7 | break; 8 | case 1: 9 | printf("%d ", n+11); 10 | break; 11 | case 2: 12 | printf("%d ", n+9); 13 | break; 14 | case 3: 15 | printf("%d ", n+7); 16 | break; 17 | case 4: 18 | printf("%d ", n+5); 19 | break; 20 | case 5: 21 | printf("%d ", n+3); 22 | break; 23 | case 6: 24 | printf("%d ", n+1); 25 | break; 26 | case 7: 27 | printf("%d ", n-1); 28 | break; 29 | case 8: 30 | printf("%d ", n-3); 31 | break; 32 | case 9: 33 | printf("%d ", n-5); 34 | break; 35 | case 10: 36 | printf("%d ", n-7); 37 | break; 38 | case 11: 39 | printf("%d ", n-9); 40 | break; 41 | } 42 | 43 | switch(n%6) { 44 | case 0: 45 | case 1: 46 | printf("WS\n"); 47 | break; 48 | case 2: 49 | case 5: 50 | printf("MS\n"); 51 | break; 52 | case 3: 53 | case 4: 54 | printf("AS\n"); 55 | break; 56 | } 57 | } 58 | 59 | int main() { 60 | 61 | int t; 62 | scanf("%d", &t); 63 | 64 | int n; 65 | while(t-- > 0) { 66 | scanf("%d", &n); 67 | 68 | showStats(n); 69 | } 70 | 71 | return 0; 72 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BasicsOfInputOutput/ToggleString.c: -------------------------------------------------------------------------------- 1 | // 2 | 3 | /* 4 | 0-9 - 48-57 5 | A-Z - 65-90 6 | a-z - 97-122 7 | */ 8 | 9 | #include 10 | 11 | int main() 12 | { 13 | char s[101]; 14 | 15 | scanf("%s", s); 16 | 17 | int i = 0; 18 | 19 | while(s[i] != '\0') { 20 | if(s[i] >= 65 && s[i] <=90) { 21 | // capital 22 | s[i] += 32; 23 | } else { 24 | // small 25 | s[i] -= 32; 26 | } 27 | i++; 28 | } 29 | 30 | printf("%s", s); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BitManipulation/LargestPower.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long largestPower(long n) { 4 | n = n | (n >> 1); 5 | n = n | (n >> 2); 6 | n = n | (n >> 4); 7 | n = n | (n >> 8); 8 | 9 | return (n+1) >> 1; 10 | } 11 | 12 | int main() { 13 | long n = 15000; 14 | 15 | std::cout << largestPower(n); 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BitManipulation/RajanAndOddFrequency.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | 8 | ios_base::sync_with_stdio(false); 9 | cin.tie(NULL); 10 | 11 | int n; 12 | cin >> n; 13 | 14 | int num = 2*n + 1; 15 | int arr[num]; 16 | int max = 0; 17 | int val; 18 | 19 | // input all numbers and calculate max for creating the count array 20 | for(int i = 0; i < num; i++) { 21 | cin >> val; 22 | arr[i] = val; 23 | if(val > max) { 24 | max = val; 25 | } 26 | } 27 | 28 | int count[max+1]; 29 | memset(count, 0, (max+1)*sizeof(int)); 30 | 31 | // counting all the occurences of number 32 | for(int i = 0; i < num; i++) { 33 | count[arr[i]]++; 34 | } 35 | 36 | // finding the odd occurence and stopping when found 37 | for(int i = 0; i < num; i++) { 38 | if(count[i]%2 != 0) { 39 | cout << i; 40 | break; 41 | } 42 | } 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /HackerEarth/CodeMonk/BitManipulation/SubsetsOfGivenSet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printSubset(char arr[], int n) { 4 | for(int i = 0; i < (1< 0) { 29 | --count[v1][v2]; 30 | } else { 31 | return false; 32 | } 33 | } 34 | 35 | return true; 36 | } 37 | 38 | public static void main(String[] args) throws IOException { 39 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 40 | 41 | int T = Integer.parseInt(br.readLine().trim()); 42 | 43 | while(T-- > 0) { 44 | String foo = br.readLine().trim(); 45 | String[] fooArr = foo.split(" "); 46 | int n = Integer.parseInt(fooArr[0]); 47 | int m = Integer.parseInt(fooArr[1]); 48 | 49 | String[] matrix = new String[n]; 50 | 51 | for(int i = 0; i < n; i++) { 52 | matrix[i] = br.readLine().trim(); 53 | } 54 | 55 | String s = br.readLine().trim(); 56 | 57 | if(canGenerateString(matrix, n, m, s)) { 58 | System.out.println("Yes"); 59 | } else { 60 | System.out.println("No"); 61 | } 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /HackerEarth/HiringChallenges/FindTheString.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """ 4 | 1 5 | 3 3 6 | aba 7 | xyz 8 | bdr 9 | axbaydb 10 | """ 11 | 12 | def canGenerateString(matrix, n, m, s): 13 | count = [[0 for x in range(26)] for y in range(n)] 14 | 15 | for i in range(0, n): 16 | for j in range(0, m): 17 | val = ord(matrix[i][j]) 18 | val -= 97 19 | count[i][val] += 1 20 | 21 | for i in range(0, len(s)): 22 | v1 = i%n 23 | v2 = ord(s[i])-97 24 | if (count[v1][v2] > 0): 25 | count[v1][v2] -= 1 26 | else: 27 | return False 28 | 29 | return True 30 | 31 | t = input() 32 | t = int(t) 33 | 34 | for z in range(0, t): 35 | n, m = [int(x) for x in input().split()] 36 | 37 | matrix = [] 38 | for i in range(0, n): 39 | foo = input() 40 | matrix.append(foo) 41 | 42 | s = input() 43 | 44 | if (canGenerateString(matrix, n, m, s)): 45 | print("Yes") 46 | else: 47 | print("No") -------------------------------------------------------------------------------- /HackerEarth/HiringChallenges/FredoAndTwoStrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | 8 | ios::sync_with_stdio(0); 9 | cin.tie(0); 10 | 11 | char s[10005], t[10005]; 12 | 13 | cin >> s >> t; 14 | 15 | int q, blank; 16 | 17 | cin >> q >> blank; 18 | 19 | int i, j; 20 | int y; 21 | for(int z = 0; z < q; z++) { 22 | cin >> i >> j; 23 | y = 0; 24 | for(int m = 0; m < i-1 && y < strlen(t); m++) { 25 | if(s[m] == t[y]) { 26 | y++; 27 | } 28 | } 29 | for(int m = j; m < strlen(s) && y < strlen(t); m++) { 30 | if(s[m] == t[y]) { 31 | y++; 32 | } 33 | } 34 | 35 | if(y == strlen(t)) { 36 | cout << "Yes\n"; 37 | } else { 38 | cout << "No\n"; 39 | } 40 | } 41 | 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /HackerEarth/HiringChallenges/FredoAndTwoStrings.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.io.IOException; 4 | 5 | class FredoAndTwoStrings { 6 | 7 | public static void main(String[] args) throws IOException { 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | String s = br.readLine().trim(); 10 | String t = br.readLine().trim(); 11 | 12 | String next = br.readLine().trim(); 13 | String[] nextArr = next.split(" "); 14 | int q = Integer.parseInt(nextArr[0]); 15 | 16 | for(int z = 0; z < q; z++) { 17 | String foo = br.readLine().trim(); 18 | String[] fooArr = foo.split(" "); 19 | 20 | int i = Integer.parseInt(fooArr[0]); 21 | int j = Integer.parseInt(fooArr[1]); 22 | 23 | String check = ""; 24 | int y = 0; 25 | for(int m = 0; m < i-1 && y < t.length(); m++) { 26 | if(s.charAt(m) == t.charAt(y)) { 27 | y++; 28 | } 29 | } 30 | for(int m = j; m < s.length() && y < t.length(); m++) { 31 | if(s.charAt(m) == t.charAt(y)) { 32 | y++; 33 | } 34 | } 35 | 36 | if(y == t.length()) { 37 | System.out.println("Yes"); 38 | } else { 39 | System.out.println("No"); 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /HackerEarth/challenges/AlexAndPriorityQueues.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/challenge/hiring/bima-java-hiring-challenge/problems/59441819ed5b46ea86c207f7dfcf6322/ 2 | 3 | /* 4 | 5 | */ 6 | 7 | 8 | import java.util.*; 9 | 10 | class TestClass { 11 | public static void main(String args[] ) throws Exception { 12 | Scanner in = new Scanner(System.in); 13 | 14 | LinkedHashMap priorityMap = new LinkedHashMap<>(); 15 | 16 | int Q = in.nextInt(); 17 | 18 | LinkedList ll = new LinkedList(); 19 | 20 | while(Q-- > 0) { 21 | int type = in.nextInt(); 22 | 23 | switch(type) { 24 | case 1: 25 | int t = in.nextInt(); 26 | int p = in.nextInt(); 27 | priorityMap.put(t, p); 28 | break; 29 | 30 | case 2: 31 | int removeT = in.nextInt(); 32 | priorityMap.remove(removeT); 33 | break; 34 | 35 | case 3: 36 | int min = Integer.MAX_VALUE; 37 | int max = 0; 38 | for(Map.Entry m : priorityMap.entrySet()){ 39 | if((int)m.getValue() < min) { 40 | min = (int) m.getValue(); 41 | } 42 | if((int)m.getValue() > max) { 43 | max = (int) m.getValue(); 44 | } 45 | } 46 | System.out.println(min + " " + max); 47 | break; 48 | 49 | case 4: 50 | int maxKey = 0; 51 | int maxVal = 0; 52 | for(Map.Entry m1: priorityMap.entrySet()) { 53 | if((int)m1.getKey() > maxKey) { 54 | maxKey = (int)m1.getKey(); 55 | maxVal = (int)m1.getValue(); 56 | } 57 | } 58 | System.out.println(maxVal); 59 | break; 60 | 61 | default: 62 | System.out.println("Wrong input"); 63 | } 64 | } 65 | } 66 | } 67 | 68 | /* 69 | class LinkedList { 70 | 71 | Node head; 72 | Node last; 73 | 74 | class Node { 75 | int key; 76 | int val; 77 | Node next; 78 | 79 | Node(int key, int val) { 80 | this.key = key; 81 | this.val = val; 82 | this.next = null; 83 | } 84 | } 85 | 86 | LinkedList { 87 | head = null; 88 | last = null; 89 | } 90 | 91 | void insert(int key, int val) { 92 | Node node = new Node(key, val); 93 | 94 | if(head == null) { 95 | head = node; 96 | return; 97 | } 98 | 99 | Node current = head; 100 | 101 | while(current.next != null && ) { 102 | 103 | } 104 | current.next = node; 105 | 106 | while(current.next != null) { 107 | last = node; 108 | } 109 | } 110 | } 111 | */ -------------------------------------------------------------------------------- /HackerEarth/challenges/AlexAndRequests.java: -------------------------------------------------------------------------------- 1 | //https://www.hackerearth.com/challenge/hiring/bima-java-hiring-challenge/problems/6dfbf24fb7d842158e1e0e68d2b260c6/ 2 | 3 | /* 4 | Alex and Requests 5 | Alex is working in a firm, where he needs to process requests according to their priority. He has 6 | N 7 | N allocation systems. At any instance, 8 | i 9 | t 10 | h 11 | ith system can process only one request with priority 12 | i 13 | i or above. 14 | 15 | For each request, on any eligible system, Alex can also terminate the request with less priority than that of the current request, in order to assign the current request to the system. There will be 16 | Q 17 | Q incoming requests and he needs to tell whether he can assign a system to each request or not. 18 | 19 | Alex needs to assign each request to the system optimally, such that he can assign maximum number of incoming requests. The number of requests (which are already assigned) terminated by Alex, doesn't matter here. 20 | 21 | Note: 22 | If not terminated explicitly, consider the processing time of every request as infinite. 23 | 24 | Input Format: 25 | 26 | First line of the input contains 27 | N 28 | N, denoting the number of allocation systems. 29 | 30 | Next line contains one integer 31 | Q 32 | Q, which denotes the number of incoming requests. 33 | 34 | In next 35 | Q 36 | Q lines, each line contains one integer 37 | X 38 | X, denoting the priority of the request. 39 | 40 | Output Format: 41 | 42 | For each incoming request, in new line print 43 | Y 44 | E 45 | S 46 | YES, if Alex can assign a system to the request, else print 47 | N 48 | O 49 | NO . 50 | */ 51 | 52 | import java.util.Scanner; 53 | 54 | class AlexAndRequests { 55 | public static void main(String args[] ) throws Exception { 56 | 57 | Scanner in = new Scanner(System.in); 58 | 59 | int N = in.nextInt(); 60 | 61 | int[] allocationArr = new int[N+1]; 62 | 63 | int Q = in.nextInt(); 64 | 65 | for(int i = 0; i < Q; i++) { 66 | 67 | int request = in.nextInt(); 68 | 69 | boolean allocated = false; 70 | 71 | if(request >= N) { 72 | if(allocationArr[N] < request) { 73 | allocationArr[N] = request; 74 | allocated = true; 75 | } else { 76 | for(int j = N-1; j >= 1; j--) { 77 | if(allocationArr[j] < request) { 78 | allocationArr[j] = request; 79 | allocated = true; 80 | break; 81 | } 82 | } 83 | } 84 | } else { 85 | if(allocationArr[request] < request) { 86 | allocationArr[request] = request; 87 | allocated = true; 88 | } else { 89 | for(int j = request; j >= 1; j--) { 90 | if(allocationArr[j] < request) { 91 | allocationArr[j] = request; 92 | allocated = true; 93 | break; 94 | } 95 | } 96 | } 97 | } 98 | 99 | String out = allocated ? "YES" : "NO"; 100 | System.out.println(out); 101 | } 102 | 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /HackerEarth/challenges/BricksAndBuildings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int n; 5 | scanf("%d", &n); 6 | 7 | int buildings[n]; 8 | 9 | for(int i = 0; i < n; i++) { 10 | scanf("%d", &buildings[i]); 11 | } 12 | 13 | // eliminate duplicate buildings % operation 14 | int buildingCount[100009]; 15 | for(int i = 0; i < 100009; i++) 16 | buildingCount[i] = 0; 17 | 18 | for(int i = 0; i < n; i++) { 19 | buildingCount[buildings[i]]++; 20 | } 21 | 22 | int q; 23 | scanf("%d", &q); 24 | 25 | // save answer to the query k in array, 26 | // if already solved then return the answer 27 | int ans[100009]; 28 | for(int i = 0; i < 100009; i++) 29 | ans[i] = -1; 30 | 31 | for(int i = 0; i < q; i++) { 32 | int k; 33 | scanf("%d", &k); 34 | 35 | if(ans[k] == -1) { 36 | int count = 0; 37 | for(int i = 0; i <= 100000; i++) { 38 | if(i%k == 0) { 39 | count += buildingCount[i]; 40 | } 41 | } 42 | ans[k] = count; 43 | } 44 | 45 | printf("%d\n", ans[k]); 46 | } 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/CoinGame.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int main() 5 | { 6 | int t; 7 | scanf("%d", &t); 8 | 9 | while(t-- > 0) { 10 | int n; 11 | 12 | scanf("%d", &n); 13 | 14 | int count = 0; 15 | int val = 0; 16 | for(int i = 0; i < n; i++) { 17 | scanf("%d", &val); 18 | while(val%2 == 0) { 19 | count++; 20 | val /= 2; 21 | } 22 | } 23 | 24 | if(count%2 == 0) { 25 | printf("Alan\n"); 26 | } else { 27 | printf("Charlie\n"); 28 | } 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /HackerEarth/challenges/CrazyMatrix.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/crazy-matrix/ 2 | 3 | import java.util.*; 4 | 5 | /* 6 | 4 7 | 0 0 0 1 8 | 2 0 1 0 9 | 0 2 1 2 10 | 0 1 2 0 11 | */ 12 | 13 | class CrazyMatrix { 14 | 15 | public static void main(String[] args) { 16 | 17 | Scanner in = new Scanner(System.in); 18 | 19 | int N = in.nextInt(); 20 | int[][] arr = new int[N][N]; 21 | 22 | for(int i = 0; i < N; i++) { 23 | for(int j = 0; j < N; j++) { 24 | arr[i][j] = in.nextInt(); 25 | } 26 | } 27 | 28 | boolean flag1 = false, flag2 = false; 29 | 30 | for(int j = 0; j < N; j++) { 31 | if(arr[0][j] == 1) { 32 | boolean visited[][] = new boolean[N][N]; 33 | flag1 = dfs(arr, 0, j, 1, N, visited); 34 | if(flag1) 35 | break; 36 | } 37 | } 38 | 39 | for(int i = 0; i < N; i++) { 40 | if(arr[i][0] == 2) { 41 | boolean[][] visited = new boolean[N][N]; 42 | flag2 = dfs(arr, i, 0, 2, N, visited); 43 | if(flag2) 44 | break; 45 | } 46 | } 47 | 48 | if(flag1 && flag2) 49 | System.out.println("AMBIGUOUS"); 50 | else if(flag1) { 51 | System.out.println("1"); 52 | } else if(flag2) { 53 | System.out.println("2"); 54 | } else { 55 | System.out.println("0"); 56 | } 57 | } 58 | 59 | static boolean dfs(int[][] arr, int i, int j, int flag, int N, boolean[][] visited) { 60 | if(i < 0 || j < 0 || i >= N || j >= N) 61 | return false; 62 | 63 | if(arr[i][j] != flag || visited[i][j]) 64 | return false; 65 | 66 | if(i == N-1 && flag == 1) 67 | return true; 68 | 69 | if(j == N-1 && flag == 2) 70 | return true; 71 | 72 | visited[i][j] = true; 73 | 74 | if(dfs(arr, i-1, j-1, flag, N, visited)) return true; 75 | if(dfs(arr, i, j-1, flag, N, visited)) return true; 76 | if(dfs(arr, i+1, j-1, flag, N, visited)) return true; 77 | if(dfs(arr, i+1, j, flag, N, visited)) return true; 78 | if(dfs(arr, i+1, j+1, flag, N, visited)) return true; 79 | if(dfs(arr, i, j+1, flag, N, visited)) return true; 80 | if(dfs(arr, i-1, j+1, flag, N, visited)) return true; 81 | 82 | return false; 83 | } 84 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/CrushingViolence.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Competitive-Programming/09df254323c88fa1d0c35bc5071d6b1cb6134320/HackerEarth/challenges/CrushingViolence.java -------------------------------------------------------------------------------- /HackerEarth/challenges/Decode.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Decode { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner in = new Scanner(System.in); 8 | 9 | String test = in.nextLine(); 10 | 11 | int t = Integer.parseInt(test); 12 | 13 | while(t-- > 0) { 14 | String enc = in.nextLine(); 15 | decode(enc); 16 | } 17 | } 18 | 19 | static void decode(String enc) { 20 | int len = enc.length(); 21 | 22 | StringBuilder sb = new StringBuilder(enc); 23 | 24 | int j = (len-1)/2; 25 | // for flipping between +x and -x 26 | boolean flag = true; 27 | int count = 1; 28 | 29 | if(len != 0) { 30 | sb.setCharAt(j, enc.charAt(0)); 31 | } 32 | 33 | if(len%2 == 0) { 34 | // even 35 | 36 | for(int i = 1; i < len; i++) { 37 | if(flag) { 38 | flag = false; 39 | int val = j+count; 40 | sb.setCharAt(val, enc.charAt(i)); 41 | } else { 42 | flag = true; 43 | int val = j-count; 44 | sb.setCharAt(val, enc.charAt(i)); 45 | count++; 46 | } 47 | } 48 | 49 | } else { 50 | // odd 51 | 52 | for(int i = 1; i < len; i++) { 53 | if(flag) { 54 | flag = false; 55 | sb.setCharAt(j-count, enc.charAt(i)); 56 | } else { 57 | flag = true; 58 | sb.setCharAt(j+count, enc.charAt(i)); 59 | count++; 60 | } 61 | } 62 | } 63 | 64 | System.out.println(sb.toString()); 65 | 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/DexterAndPoints.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepaksood619/Competitive-Programming/09df254323c88fa1d0c35bc5071d6b1cb6134320/HackerEarth/challenges/DexterAndPoints.png -------------------------------------------------------------------------------- /HackerEarth/challenges/DisconnectedGraph.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/codearena/ring/326dc67/ 2 | 3 | import java.util.*; 4 | 5 | class TestClass { 6 | 7 | public static void main(String args[] ) throws Exception { 8 | Scanner in = new Scanner(System.in); 9 | 10 | int N = in.nextInt(); 11 | 12 | ArrayList> adjList = new ArrayList<>(N); 13 | 14 | for(int i = 0; i < N; i++) { 15 | adjList.add(new LinkedList()); 16 | } 17 | 18 | int M = in.nextInt(); 19 | 20 | for(int i = 0; i < M; i++) { 21 | int a = in.nextInt(); 22 | int b = in.nextInt(); 23 | --a; 24 | --b; 25 | adjList.get(a).add(b); 26 | adjList.get(b).add(a); 27 | } 28 | 29 | for(int i = 0; i < N; i++) { 30 | System.out.print("i - " + i + " - "); 31 | for(int j = 0; j < adjList.get(i).size(); j++) { 32 | System.out.print(" " + adjList.get(i).get(j)); 33 | } 34 | System.out.println(); 35 | } 36 | 37 | int sum = 0; 38 | 39 | for(int i = 0; i < N; i++) { 40 | sum += N - adjList.get(i).size() - 1; 41 | } 42 | 43 | System.out.println(sum/2); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /HackerEarth/challenges/FizzBuzzTest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(void) { 5 | for (int i = 1; i <= 100; i++) { 6 | if(i%3 == 0 && i%5 == 0) { 7 | cout << "FizzBuzz" << endl; 8 | } else if(i%3 == 0) { 9 | cout << "Fizz" << endl; 10 | } else if(i%5 == 0) { 11 | cout << "Buzz" << endl; 12 | } else { 13 | cout << i << endl; 14 | } 15 | } 16 | return 0; 17 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/FizzBuzzTest.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/problem/algorithm/fizzbuzz/ 2 | 3 | class FizzBuzzTest { 4 | public static void main(String args[] ) throws Exception { 5 | for(int i = 1; i <= 100; i++) { 6 | if(i%3 == 0 && i%5 == 0) { 7 | System.out.println("FizzBuzz"); 8 | } else if(i%3 == 0) { 9 | System.out.println("Fizz"); 10 | } else if(i%5 == 0) { 11 | System.out.println("Buzz"); 12 | } else { 13 | System.out.println(i); 14 | } 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /HackerEarth/challenges/FredoAndArrayUpdate.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/challenge/test/programming-practice-challenge/algorithm/38fe887021c8434ca51f5046912b51e9/ 2 | 3 | /* 4 | Time Complexity - O(1) 5 | Space Complexity - O(1) 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | class FredoAndArrayUpdate { 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | 14 | int N = in.nextInt(); 15 | int sum = 0; 16 | 17 | for(int i = 0; i < N; i++) { 18 | sum += in.nextInt(); 19 | } 20 | 21 | int ans = (int)(sum/N) + 1; 22 | 23 | System.out.println(ans); 24 | } 25 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/InheritancePuzzle.java: -------------------------------------------------------------------------------- 1 | class ABC 2 | { 3 | public int i = 0; 4 | 5 | public ABC(String text) { 6 | i = 1; 7 | } 8 | } 9 | 10 | class XYZ extends ABC { 11 | 12 | public XYZ(String text) { 13 | // super(text); 14 | i = 2; 15 | } 16 | 17 | public static void main(String args[]) 18 | { 19 | XYZ sub = new XYZ("Hi"); 20 | System.out.println(sub.i); 21 | } 22 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/KDevices.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | 4 | class KDevices { 5 | 6 | static int max(int i, int j) { 7 | if(i <= j) { 8 | return i; 9 | } else { 10 | return j; 11 | } 12 | } 13 | 14 | public static void main(String args[] ) throws Exception { 15 | Scanner in = new Scanner(System.in); 16 | 17 | /* 18 | int N = in.nextInt(); 19 | int K = in.nextInt(); 20 | 21 | int[] X = new int[N]; 22 | int[] Y = new int[N]; 23 | for(int i = 0; i 15 | #include 16 | #include 17 | #include 18 | 19 | const int mod = 1000000007; 20 | 21 | void sieve(std::vector &prime, int k) { 22 | bool arr[k]; 23 | memset(arr, true, sizeof(arr)); 24 | 25 | for(int i = 2; i < k; i++) { 26 | if(arr[i]) { 27 | for(int j = i+i; j < k; j += i) { 28 | arr[j] = false; 29 | } 30 | prime.push_back(i); 31 | } 32 | } 33 | } 34 | 35 | long long int divisors(long long int n) { 36 | long long int p = 1; 37 | 38 | for(int i = 2; i <= n; i++) { 39 | if(n%i == 0) { 40 | p = ((p%mod) * i)%mod; 41 | printf("new p - %lld ,i - %d\n", p, i); 42 | } 43 | } 44 | 45 | return p; 46 | } 47 | 48 | long long int numDivisors(long long int p) { 49 | long long int num = 1; 50 | 51 | for(int i = 2; i <= p; i++) { 52 | if(p%i == 0) { 53 | num = num + 1; 54 | printf("num - %lld \n", num); 55 | } 56 | } 57 | 58 | return num; 59 | } 60 | 61 | int main() { 62 | 63 | int x; 64 | scanf("%d", &x); 65 | 66 | int arr[x]; 67 | for(int i = 0; i < x; i++) { 68 | scanf("%d", &arr[i]); 69 | } 70 | 71 | int k = 6; 72 | if(x >= 6) { 73 | k = x * log ( x * log(x)); 74 | } 75 | // printf("k - %d\n", k); 76 | 77 | std::vector prime; 78 | 79 | sieve(prime, k); 80 | 81 | // printf("size - %lu\n", prime.size()); 82 | // for(std::vector::iterator i = prime.begin(); i != prime.end(); i++) { 83 | // std::cout << *i << " "; 84 | // } 85 | 86 | // printf("size - %lu\n", prime.size()); 87 | 88 | long long int n = 1; 89 | for(int i = 0; i < x; i++) { 90 | n = ((n%mod) * ((long long int)pow(prime.at(i), arr[i])%mod))%mod; 91 | } 92 | 93 | printf("n - %lld\n", n); 94 | long long int p = divisors(n); 95 | printf("divisors - %lld\n", p); 96 | 97 | long long int num = numDivisors(p); 98 | num = num%mod; 99 | printf("%lld", num); 100 | 101 | return 0; 102 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/MathisonAndTheMedicalFacilities.cpp: -------------------------------------------------------------------------------- 1 | // approximate problem 2 | 3 | /* 4 | 4 2 5 5 | 10 51 45 24 6 | 50 77 98 12 7 | 23 62 33 65 8 | 89 41 36 78 9 | 17 23 76 54 10 | 40 50 10 30 11 | 12 | 4 3 5 13 | 10 51 45 24 14 | 50 77 98 12 15 | 23 62 33 65 16 | 89 41 36 78 17 | 17 23 76 54 18 | 40 50 10 30 19 | */ 20 | 21 | #include 22 | 23 | int* solve(int n, int m, int k, int* clients, int facilityCost[]) { 24 | int* ans = new int[k]; 25 | 26 | for(int i = 0; i <= n-k; i++) { 27 | for(int j = i+k-1; j <= n-1; j++) { 28 | 29 | printf("%d %d, ", i, j); 30 | } 31 | printf("\n"); 32 | } 33 | 34 | for(int i = 0; i < k; i++) { 35 | ans[i] = i; 36 | } 37 | 38 | return ans; 39 | } 40 | 41 | int main() { 42 | int n, k, m; 43 | 44 | scanf("%d %d %d", &n, &k, &m); 45 | int clients[m][n]; 46 | 47 | for(int i = 0; i < m; i++) { 48 | for(int j = 0; j < n; j++) { 49 | scanf("%d", &clients[i][j]); 50 | 51 | } 52 | } 53 | 54 | int facilityCost[n]; 55 | for(int i = 0; i < n; i++) { 56 | scanf("%d", &facilityCost[i]); 57 | } 58 | 59 | int* ans; 60 | ans = solve(n, m, k, (int *)clients, facilityCost); 61 | 62 | for(int i = 0; i < k; i++) { 63 | printf("%d ", *(ans+i)); 64 | } 65 | printf("\n"); 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/MissingNumber.cpp: -------------------------------------------------------------------------------- 1 | // National Instruments Hiring 2 | // Marks - 100/100 3 | // Test cases passed - 6/6 4 | 5 | #include 6 | #include 7 | 8 | int main() { 9 | int t; 10 | scanf("%d", &t); 11 | 12 | while(t-- > 0) { 13 | int n; 14 | scanf("%d", &n); 15 | 16 | int arr[n]; 17 | 18 | for(int i = 0; i < n; i++) { 19 | scanf("%d", &arr[i]); 20 | } 21 | 22 | std::sort(arr, arr+n); 23 | 24 | int max = 0; 25 | for(int i = 0; i < n; i++) { 26 | if(arr[i] > max) { 27 | if(arr[i]%2 == 1) { 28 | if(arr[i]-1 > max) { 29 | max += 2; 30 | } 31 | } else { 32 | max += 2; 33 | } 34 | } 35 | } 36 | 37 | printf("%d\n", max+2); 38 | 39 | } 40 | return 0; 41 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/PolicemenAndThieves.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int solution (char** matrix, int k, int n) { 6 | int count = 0; 7 | for(int i = 0; i < n; i++) { 8 | for(int j = 0; j < n; j++) { 9 | if(matrix[i][j] == 'P') { 10 | // check k left starting from farthest to maximize 11 | bool leftFlag = true; 12 | for(int m = k; m >= 1; m--) { 13 | if(j-m >= 0 && matrix[i][j-m] == 'T') { 14 | matrix[i][j-m] = 'X'; 15 | matrix[i][j] = 'Y'; 16 | count++; 17 | leftFlag = false; 18 | break; 19 | } 20 | } 21 | 22 | // check k right starting from nearest to maximize 23 | if(leftFlag) { 24 | for(int m = 1; m <= k; m++) { 25 | if(j+m < n && matrix[i][j+m] == 'T') { 26 | matrix[i][j+m] = 'X'; 27 | matrix[i][j] = 'Y'; 28 | count++; 29 | break; 30 | } 31 | } 32 | } 33 | } 34 | } 35 | } 36 | return count; 37 | } 38 | 39 | int main() { 40 | int T; 41 | scanf("%d", &T); 42 | for(int t_i=0; t_i 6 | #include 7 | 8 | int main() { 9 | 10 | int t; 11 | std::cin >> t; 12 | 13 | while(t-- > 0) { 14 | int n, k; 15 | std::cin >> n >> k; 16 | 17 | char matrix[n][n]; 18 | 19 | for(int i = 0; i < n; i++) { 20 | for(int j = 0; j < n; j++) { 21 | std::cin >> matrix[i][j]; 22 | } 23 | } 24 | 25 | /*int count = 0; 26 | for(int i = 0; i < n; i++) { 27 | for(int j = 0; j < n; j++) { 28 | if(matrix[i][j] == 'P') { 29 | // check k left starting from farthest to maximize 30 | bool leftFlag = true; 31 | for(int m = k; m >= 1; m--) { 32 | if(j-m >= 0 && matrix[i][j-m] == 'T') { 33 | matrix[i][j-m] = 'X'; 34 | matrix[i][j] = 'Y'; 35 | count++; 36 | leftFlag = false; 37 | break; 38 | } 39 | } 40 | 41 | // check k right starting from nearest to maximize 42 | if(leftFlag) { 43 | for(int m = 1; m <= k; m++) { 44 | if(j+m < n && matrix[i][j+m] == 'T') { 45 | matrix[i][j+m] = 'X'; 46 | matrix[i][j] = 'Y'; 47 | count++; 48 | break; 49 | } 50 | } 51 | } 52 | } 53 | } 54 | }*/ 55 | 56 | stack holder; 57 | int count = 0; 58 | for(int i = 0; i < n; i++) { 59 | for(int j = 0; j < n; j++) { 60 | 61 | } 62 | } 63 | 64 | std::cout << count << '\n'; 65 | } 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/RastaAndTavas.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | 5 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/RhezoAndBigPowers.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/practice-problems/algorithm/rhezo-and-big-powers-1/description/ 2 | 3 | /* 4 | Rhezo likes numbers of the form A^B. 5 | 6 | Input: 7 | First line of input contains a single integer A, 8 | Second line contains the integer B 9 | 10 | Output: 11 | Help Rhezo find A^B As this number can be large, print it modulo 10^9+7 12 | */ 13 | 14 | import java.util.Scanner; 15 | import java.math.BigInteger; 16 | 17 | class RhezoAndBigPowers { 18 | 19 | public static void main(String args[] ) throws Exception { 20 | Scanner in = new Scanner(System.in); 21 | 22 | BigInteger mod = new BigInteger("1000000007"); 23 | 24 | BigInteger bigA = in.nextBigInteger(); 25 | BigInteger bigB = in.nextBigInteger(); 26 | BigInteger val = bigA.modPow(bigB, mod); 27 | 28 | System.out.println(val); 29 | } 30 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/RoyAndTrains.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class test { 4 | 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | 8 | int T = in.nextInt(); 9 | while(T-- > 0) { 10 | 11 | int T0 = in.nextInt(); 12 | int T1 = in.nextInt(); 13 | int T2 = in.nextInt(); 14 | int V1 = in.nextInt(); 15 | int V2 = in.nextInt(); 16 | int D = in.nextInt(); 17 | 18 | int trainT1Time = (int) Math.ceil(((double)D/V1) * 60); 19 | int trainT2Time = (int) Math.ceil(((double)D/V2) * 60); 20 | 21 | int totalT1 = trainT1Time + T1; 22 | int totalT2 = trainT2Time + T2; 23 | 24 | if(T0 > T1 && T0 > T2) { 25 | System.out.println("-1"); 26 | } else if(T0 <= T1 && T0 > T2) { 27 | // only train1 can be caught 28 | System.out.println(totalT1); 29 | } else if(T0 > T1 && T0 <= T2) { 30 | // only train2 can be caught 31 | System.out.println(totalT2); 32 | } else { 33 | // both train can be caught 34 | int minTime = totalT1 <= totalT2 ? totalT1 : totalT2; 35 | System.out.println(minTime); 36 | } 37 | } 38 | } 39 | } 40 | 41 | /* 42 | 1 43 | 5 5 8 100 90 320 44 | */ -------------------------------------------------------------------------------- /HackerEarth/challenges/RoyAndWobblyNumbers.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/problem/algorithm/roy-and-wobbly-numbers/description/ 2 | 3 | import java.util.*; 4 | 5 | class TestClass { 6 | public static void main(String args[] ) throws Exception { 7 | Scanner in = new Scanner(System.in); 8 | 9 | int[] arr = new int[81]; 10 | int a = 1; 11 | int b; 12 | int i = 0; 13 | while(a < 10) { 14 | b = 0; 15 | while(b < 10) { 16 | if(a != b) { 17 | arr[i++] = a*10 + b; 18 | } 19 | b++; 20 | } 21 | a++; 22 | } 23 | 24 | int T = in.nextInt(); 25 | while(T-- > 0) { 26 | int N = in.nextInt(); 27 | int K = in.nextInt(); 28 | 29 | if(K > 81) { 30 | System.out.print("-1"); 31 | } else { 32 | int val = arr[K-1]; 33 | while(N >= 2) { 34 | System.out.print(val); 35 | N = N - 2; 36 | if(N == 1) { 37 | System.out.print(val / 10); 38 | } 39 | } 40 | } 41 | System.out.println(); 42 | } 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /HackerEarth/challenges/SherlockAndDates.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/sherlock-and-dates/description/ 2 | 3 | /* 4 | Working but not fully optimized. 5 | Time out for last 3 test cases 6 | */ 7 | 8 | import java.util.*; 9 | 10 | import java.text.ParseException; 11 | 12 | import java.lang.*; 13 | import java.text.SimpleDateFormat; 14 | import java.time.format.DateTimeFormatter; 15 | 16 | class SherlockAndDates { 17 | 18 | public static void main (String[] args) { 19 | 20 | Scanner in = new Scanner(System.in); 21 | 22 | String date = "31:05:0457 17:04:9231"; // 968 23 | // String date = "30:03:1199 30:03:1204"; // 2 24 | // String date = "27:03:5208 27:03:5215"; // 6 25 | // String date = "01:01:0001 01:02:0003"; // 1 26 | 27 | String[] dateArr = date.split(" "); 28 | 29 | SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy"); 30 | try { 31 | Calendar cal1 = Calendar.getInstance(); 32 | cal1.setTime(sdf.parse(dateArr[0])); 33 | 34 | Calendar cal2 = Calendar.getInstance(); 35 | cal2.setTime(sdf.parse(dateArr[1])); 36 | 37 | int count = 0; 38 | 39 | int val = cal1.compareTo(cal2); 40 | 41 | while(val <= 0) { 42 | 43 | int year = cal1.get(Calendar.YEAR) % 100; 44 | 45 | if(year >= 2) { 46 | if(year <= 13) { 47 | // System.out.println("year sat - " + cal1.getTime()); 48 | int mon = cal1.get(Calendar.MONTH) + 2; 49 | if(mon > year) { 50 | // System.out.println("year sat - " + cal1.getTime()); 51 | cal1.add(Calendar.YEAR, 1); 52 | cal1.set(Calendar.MONTH, 0); 53 | } else if(mon < year) { 54 | // System.out.println("mon inc - " + cal1.getTime()); 55 | cal1.add(Calendar.MONTH, 1); 56 | cal1.set(Calendar.DATE, 1); 57 | } else { 58 | mon -= 2; 59 | int dateInt = cal1.get(Calendar.DATE); 60 | if(dateInt > mon) { 61 | cal1.add(Calendar.MONTH, 1); 62 | cal1.set(Calendar.DATE, 1); 63 | } else if(dateInt == mon) { 64 | // System.out.println("Date - " + cal1.getTime()); 65 | count++; 66 | cal1.add(Calendar.DATE, 1); 67 | } else { 68 | cal1.add(Calendar.DATE, 1); 69 | } 70 | } 71 | } else { 72 | cal1.add(Calendar.YEAR, 102 - year); 73 | cal1.set(Calendar.MONTH, 0); 74 | } 75 | } else { 76 | // System.out.println(cal1.get(Calendar.YEAR)); 77 | cal1.add(Calendar.YEAR, 1); 78 | cal1.set(Calendar.MONTH, 0); 79 | } 80 | 81 | val = cal1.compareTo(cal2); 82 | } 83 | System.out.println(count); 84 | 85 | } catch(ParseException e) { 86 | e.printStackTrace(); 87 | } 88 | 89 | 90 | 91 | } 92 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/SumOfSubsets.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/codearena/ring/d58bbe2/ 2 | 3 | /* 4 | Problem Statement - 5 | Limak is an old brown bear. He often goes bowling with his friends. 6 | 7 | For rolling a ball one gets a score - a non-negative integer number of points. Score for the i-th roll is multiplied by i and scores are summed up. For example, for rolls with scores 7, 10, 5 the total score is equal to 7×1 + 10×2 + 5×3 = 42. 8 | 9 | Limak made N rolls and got a score Ai for the i-th of them. 10 | 11 | Unfortunately, the bowling club's computer system isn't stable today. Any rolls can be erased! Then, the total score is calculated as if there were only non-erased rolls. There are 2N possible sequences of remaining (non-erased) rolls. Limak is curious about various statistics of this situation. 12 | 13 | He asks you for one thing. Find the sum of total scores of all 2N possible sequences of remaining rolls. Print it modulo 109+7. 14 | 15 | Input format 16 | 17 | The first line contains a single integer N. 18 | 19 | The second line contains N non-negative integers A1, A2, ..., AN. 20 | 21 | Output format 22 | 23 | In a single line print modulo 109+7 the sum of total scores of possible remaining sequences. 24 | 25 | Constraints 26 | 27 | 1 ≤ N ≤ 200,000 28 | 0 ≤ Ai ≤ 109 29 | 30 | 31 | Test case - 32 | 3 33 | 6 12 8 34 | 35 | Solution - 160 36 | */ 37 | 38 | import java.util.Scanner; 39 | import java.math.BigInteger; 40 | 41 | class SumOfSubsets { 42 | public static void main(String args[] ) throws Exception { 43 | 44 | Scanner in = new Scanner(System.in); 45 | 46 | int N = in.nextInt(); 47 | 48 | int[] arr = new int[N]; 49 | 50 | for(int i = 0; i < N; i++) { 51 | arr[i] = in.nextInt(); 52 | } 53 | 54 | BigInteger sum = new BigInteger("0"); 55 | BigInteger modVal = new BigInteger("1000000007"); 56 | 57 | for(int i = 0; i < (1< 0) { 61 | 62 | rolNum++; 63 | BigInteger rolNumBig = BigInteger.valueOf(rolNum); 64 | BigInteger arrValBig = BigInteger.valueOf(arr[j]); 65 | 66 | sum = sum.add(rolNumBig.multiply(arrValBig)); 67 | } 68 | } 69 | } 70 | 71 | sum = sum.mod(modVal); 72 | 73 | System.out.println(sum); 74 | 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /HackerEarth/challenges/TheBestPlayer.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/practice-problems/algorithm/the-best-player-1/ 2 | 3 | /* 4 | 3 2 5 | surbhi 3 6 | surpanakha 3 7 | shreya 5 8 | 9 | Output- 10 | shreya 11 | surbhi 12 | */ 13 | 14 | import java.util.*; 15 | 16 | class TheBestPlayer { 17 | public static void main(String args[] ) throws Exception { 18 | Scanner in = new Scanner(System.in); 19 | 20 | String l1 = in.nextLine(); 21 | String[] larr = l1.split(" "); 22 | int N = Integer.parseInt(larr[0]); 23 | int T = Integer.parseInt(larr[1]); 24 | 25 | ArrayList fansArr = new ArrayList<>(N); 26 | 27 | while(N-- > 0) { 28 | String val = in.nextLine(); 29 | String[] varArr = val.split(" "); 30 | fansArr.add(new Fans(varArr[0], Integer.parseInt(varArr[1]))); 31 | } 32 | 33 | Collections.sort(fansArr, new Comparator() { 34 | @Override 35 | public int compare(Fans a, Fans b) { 36 | int i = Integer.compare(b.quotient, a.quotient); 37 | if(i == 0) { 38 | int j = a.name.compareTo(b.name); 39 | return j; 40 | } 41 | return i; 42 | } 43 | }); 44 | 45 | for(int k = 0; k < T; k++) { 46 | System.out.println(fansArr.get(k).name); 47 | } 48 | 49 | in.close(); 50 | 51 | } 52 | } 53 | 54 | class Fans { 55 | String name; 56 | int quotient; 57 | 58 | Fans(String name, int quotient) { 59 | this.name = name; 60 | this.quotient = quotient; 61 | } 62 | } -------------------------------------------------------------------------------- /HackerEarth/challenges/XSquareAndTwoArrays.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/xsquare-and-two-arrays/ 2 | 3 | /* 4 | 5 | Question variables and there input taking and storing is kept out of complexity analysis 6 | 7 | Time Complexity - O(R - L)*Q 8 | Space Complexity - O(1) for storing ans 9 | 10 | */ 11 | 12 | import java.util.*; 13 | 14 | class TestClass { 15 | public static void main(String args[] ) throws Exception { 16 | Scanner in = new Scanner(System.in); 17 | int N = in.nextInt(); 18 | int Q = in.nextInt(); 19 | 20 | int[] A = new int[N]; 21 | int[] B = new int[N]; 22 | 23 | for(int i = 0; i < N; i++) { 24 | A[i] = in.nextInt(); 25 | } 26 | for(int i = 0; i < N; i++) { 27 | B[i] = in.nextInt(); 28 | } 29 | 30 | for(int i = 0; i < Q; i++) { 31 | int type = in.nextInt(); 32 | int L = in.nextInt(); 33 | int R = in.nextInt(); 34 | 35 | long ans = 0; 36 | 37 | if(type == 1) { 38 | for(int j = L-1; j < R; j++) { 39 | ans += A[j]; 40 | j++; 41 | if(j < R) { 42 | ans += B[j]; 43 | } 44 | } 45 | } else { 46 | for(int j = L-1; j < R; j++) { 47 | ans += B[j]; 48 | j++; 49 | if(j < R) { 50 | ans += A[j]; 51 | } 52 | } 53 | } 54 | System.out.println(ans); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /HackerRank/Algorithms/Dynamic Programming/FibonacciModified.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/fibonacci-modified 2 | 3 | /* 4 | Time Complexity - O(N) 5 | Space Complexity - O(1) 6 | */ 7 | 8 | import java.util.Scanner; 9 | import java.math.BigInteger; 10 | 11 | class FibonacciModified { 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | int t1 = in.nextInt(); 17 | int t2 = in.nextInt(); 18 | 19 | int n = in.nextInt(); 20 | 21 | BigInteger fib0 = BigInteger.valueOf(t1); 22 | BigInteger fib1 = BigInteger.valueOf(t2); 23 | BigInteger fib2 = null; 24 | 25 | for(int i = 0; i < n-2; i++) { 26 | fib2 = fib0.add(fib1.multiply(fib1)); 27 | 28 | fib0 = fib1; 29 | fib1 = fib2; 30 | } 31 | 32 | System.out.println(fib2); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Dynamic Programming/TheCoinChangeProblemDP.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/coin-change 2 | 3 | /* 4 | Dynamic Programming Problem - 5 | 1. Overlapping Subproblem 6 | 2. Optimal Substructure 7 | 8 | Storing Values - 9 | 1. Memoization (Top Down) 10 | 2. Tabulation (Bottom Up) 11 | 12 | Time Complexity - O(M*N) 13 | Space Complexity - O(N) 14 | */ 15 | 16 | class TheCoinChangeProblemDP { 17 | 18 | static int count(int[] arr, int num, int sum) { 19 | 20 | int[] table = new int[sum+1]; 21 | 22 | table[0] = 1; 23 | 24 | for(int i = 0; i < num; i++) { 25 | for(int j = arr[i]; j <= sum; j++) { 26 | table[j] += table[j - arr[i]]; 27 | } 28 | } 29 | 30 | return table[sum]; 31 | } 32 | 33 | public static void main(String[] args) { 34 | 35 | int arr[] = new int[] {1, 2, 3}; 36 | int m = 4; 37 | 38 | System.out.println(count(arr, arr.length, m)); 39 | } 40 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Dynamic Programming/TheCoinChangeProblemRecursive.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/coin-change 2 | 3 | /* 4 | Time complexity - O(N^N) 5 | */ 6 | 7 | class TheCoinChangeProblemRecursive { 8 | 9 | static int count(int[] arr, int num, int sum) { 10 | // if sum is 0 then do not include any coin 11 | if (sum == 0) 12 | return 1; 13 | 14 | // is sum < 0 then no solution exists 15 | if (sum < 0) 16 | return 0; 17 | 18 | //if there are no coins and sum is greater then 1 then no solution exists 19 | if(num <= 0 && sum >= 1) 20 | return 0; 21 | 22 | // count is sum of solutions that does not contain the mth coin including arr[m-1] 23 | // summation with those that does not contain arr[m-1]th coin 24 | return count(arr, num-1, sum) + count(arr, num, sum - arr[num-1]); 25 | } 26 | 27 | public static void main(String[] args) { 28 | 29 | int arr[] = new int[] {1, 2, 3}; 30 | int m = 4; 31 | 32 | System.out.println(count(arr, arr.length, m)); 33 | } 34 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Graph Theory/JourneyToTheMoon.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/journey-to-the-moon 2 | 3 | /* 4 | 5 | Initial Solution - Using DFS find the connected components and number of vertices in each connected components 6 | 7 | Equation - No of permutations in connected components 8 | (a*b) + (a+b)*c + (a+b+c)*d + ... 9 | 10 | Time Complexity - O(|V + E|) as in the connected components for an undirected graph 11 | Space Complexity - O(|V|) as at worst case hold all the vertices 12 | 13 | Test Case 1 - 14 | 5 3 15 | 0 1 16 | 2 3 17 | 0 4 18 | 19 | Test Case 2 - 20 | 10 7 21 | 0 2 22 | 1 8 23 | 1 4 24 | 2 8 25 | 2 6 26 | 3 5 27 | 6 9 28 | 29 | Test Case 3 - 30 | 4 1 31 | 0 2 32 | 33 | Large Test Case - 34 | 100000 2 35 | 1 2 36 | 3 4 37 | */ 38 | 39 | import java.util.Scanner; 40 | import java.util.ArrayList; 41 | import java.util.LinkedList; 42 | 43 | class JourneyToTheMoon { 44 | 45 | public static void main(String[] args) { 46 | Scanner in = new Scanner(System.in); 47 | 48 | int N = in.nextInt(); 49 | int P = in.nextInt(); 50 | 51 | Graph graph = new Graph(N); 52 | 53 | for(int i = 0; i < P; i++) { 54 | int a = in.nextInt(); 55 | int b = in.nextInt(); 56 | 57 | graph.addEdge(a, b); 58 | } 59 | 60 | //graph.print(); 61 | 62 | System.out.println(graph.connectedComponents()); 63 | } 64 | } 65 | 66 | class Graph { 67 | int numOfVertices; 68 | 69 | ArrayList> adjList; 70 | 71 | Graph(int numOfVertices) { 72 | this.numOfVertices = numOfVertices; 73 | adjList = new ArrayList<>(numOfVertices); 74 | 75 | for(int i = 0; i < numOfVertices; i++) { 76 | adjList.add(new LinkedList<>()); 77 | } 78 | } 79 | 80 | void addEdge(int a, int b) { 81 | adjList.get(a).add(b); 82 | adjList.get(b).add(a); 83 | } 84 | 85 | void print() { 86 | for(int i = 0; i < numOfVertices; i++) { 87 | System.out.print(i + " - "); 88 | for(int j = 0; j < adjList.get(i).size(); j++) { 89 | System.out.print(adjList.get(i).get(j) + " "); 90 | } 91 | System.out.println(); 92 | } 93 | } 94 | 95 | long connectedComponents() { 96 | boolean[] visited = new boolean[numOfVertices]; 97 | 98 | ArrayList numOfVerticesComponents = new ArrayList<>(); 99 | long permutations = 0; 100 | 101 | for(int i = 0; i < numOfVertices; i++) { 102 | if(!visited[i]) { 103 | 104 | visited[i] = true; 105 | int num = 1; 106 | num = dfs(i, visited, num); 107 | numOfVerticesComponents.add(num); 108 | 109 | if(numOfVerticesComponents.size() > 1) { 110 | int sum = 0; 111 | int j = 0; 112 | for(j = 0; j < numOfVerticesComponents.size()-1; j++) { 113 | sum += numOfVerticesComponents.get(j); 114 | } 115 | permutations += sum * numOfVerticesComponents.get(j); 116 | } 117 | } 118 | } 119 | return permutations; 120 | } 121 | 122 | int dfs(int s, boolean[] visited, int num) { 123 | for(int i = 0; i < adjList.get(s).size(); i++) { 124 | int n = adjList.get(s).get(i); 125 | if(!visited[n]) { 126 | num++; 127 | visited[n] = true; 128 | num = dfs(n, visited, num); 129 | } 130 | } 131 | return num; 132 | } 133 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Graph Theory/RoadsAndLibraries.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/torque-and-development 2 | 3 | /* 4 | Concept - if cLib <= cRoad, then simply create library at each vertex and return the cost. 5 | if cLib > cRoad, then create library in each connected components and 6 | then find the minimum number of edges, multiply it with the cost of road (cRoad) 7 | and return the sum. 8 | 9 | minimum number of edges in a connected graph = numOfVertices - 1 10 | 11 | for connectedComponents and numOfVertices BFS is used 12 | 13 | Equation - for each component (cLib + cRoad * (numOfVertices - 1)) 14 | 15 | SpaceComplexity - O(|V|), since at worst case we need to hold all vertices in the queue. 16 | 17 | TimeComplexity - O(|V|) where |V| is the number of nodes, we need to traverse all nodes. 18 | */ 19 | 20 | import java.util.Scanner; 21 | import java.util.LinkedList; 22 | 23 | class RoadsAndLibraries { 24 | 25 | static long connectedComponents(boolean[] visited1, LinkedList[] arrList1, long cLib1, long cRoad1) { 26 | int numOfComponents = 0; 27 | long sum = 0; 28 | 29 | for(int i = 0; i < visited1.length; i++) { 30 | if(!visited1[i]) { 31 | int numOfVertices = bfs(i, visited1, arrList1); 32 | sum += cLib1 + (cRoad1 * (numOfVertices - 1)); 33 | } 34 | } 35 | return sum; 36 | } 37 | 38 | static int bfs(int s, boolean[] visited2, LinkedList[] arrList2) { 39 | LinkedList queue = new LinkedList<>(); 40 | int numOfVertices = 0; 41 | queue.add(s); 42 | visited2[s] = true; 43 | 44 | while(queue.size() != 0) { 45 | s = queue.poll(); 46 | numOfVertices++; 47 | for(int j = 0; j < arrList2[s].size(); j++) { 48 | if(!visited2[arrList2[s].get(j)]) { 49 | queue.add(arrList2[s].get(j)); 50 | visited2[arrList2[s].get(j)] = true; 51 | } 52 | } 53 | } 54 | return numOfVertices; 55 | } 56 | 57 | public static void main(String[] args) { 58 | Scanner in = new Scanner(System.in); 59 | 60 | int q = in.nextInt(); 61 | 62 | while(q-- > 0) { 63 | int n = in.nextInt(); 64 | int m = in.nextInt(); 65 | long cLib = in.nextLong(); 66 | long cRoad = in.nextLong(); 67 | 68 | LinkedList[] arrList = new LinkedList[n]; 69 | boolean[] visited = new boolean[n]; 70 | 71 | for(int i = 0; i < n; i++) { 72 | arrList[i] = new LinkedList<>(); 73 | } 74 | 75 | for(int i = 0; i < m; i++) { 76 | int u = in.nextInt(); 77 | int v = in.nextInt(); 78 | u--; 79 | v--; 80 | arrList[u].add(v); 81 | arrList[v].add(u); 82 | } 83 | 84 | long cost = 0; 85 | if(cLib <= cRoad) { 86 | cost += n*cLib; 87 | } else { 88 | cost = connectedComponents(visited, arrList, cLib, cRoad); 89 | } 90 | System.out.println("cost - " + cost); 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Recursion/RecursiveDigitSum.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/recursive-digit-sum/problem 2 | 3 | import java.util.Scanner; 4 | import java.math.BigInteger; 5 | 6 | class RecursiveDigitSum { 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | String input = in.nextLine(); 11 | String inArr[] = input.split(" "); 12 | int k = Integer.parseInt(inArr[1]); 13 | 14 | StringBuilder sb = new StringBuilder(); 15 | for(int i = 0; i < k; i++) { 16 | sb.append(inArr[0]); 17 | } 18 | 19 | String str = sb.toString(); 20 | 21 | System.out.println(superDigit(str)); 22 | } 23 | 24 | static String superDigit(String str) { 25 | if(str.length() == 1) { 26 | return str; 27 | } 28 | 29 | BigInteger val = new BigInteger("0"); 30 | for(int i = 0; i < str.length(); i++) { 31 | BigInteger newVal = new BigInteger(Character.toString(str.charAt(i))); 32 | val = val.add(newVal); 33 | } 34 | return superDigit(val.toString()); 35 | } 36 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Recursion/ThePowerSum.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/the-power-sum/problem 2 | 3 | import java.util.*; 4 | 5 | class ThePowerSum { 6 | 7 | static int numOfSolutions; 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | int X = in.nextInt(); 13 | int N = in.nextInt(); 14 | 15 | powerSum(X, N, 0, 1); 16 | System.out.println(numOfSolutions); 17 | } 18 | 19 | static void powerSum(int X, int N, int currSum, int currNum) { 20 | if(currSum == X) { 21 | numOfSolutions++; 22 | return; 23 | } 24 | 25 | for(int i = currNum; (currSum + (int) Math.pow(i, N)) <= X; i++) { 26 | powerSum(X, N, currSum + (int) Math.pow(i, N), i+1); 27 | } 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Sorting/BigSorting.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/big-sorting/problem 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | import java.util.Comparator; 6 | 7 | class BigSorting { 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | 11 | int n = in.nextInt(); 12 | 13 | String[] unsorted = new String[n]; 14 | 15 | for(int i = 0; i < n; i++) { 16 | unsorted[i] = in.next(); 17 | } 18 | 19 | Arrays.sort(unsorted, new Comparator() { 20 | @Override 21 | public int compare(String a, String b) { 22 | return StringAsIntegerCompare(a, b); 23 | } 24 | }); 25 | 26 | for(int i = 0; i < n; i++) { 27 | System.out.println(unsorted[i]); 28 | } 29 | } 30 | 31 | static int StringAsIntegerCompare(String s1, String s2) { 32 | if(s1.length() > s2.length()) { 33 | return 1; 34 | } 35 | if(s1.length() < s2.length()) { 36 | return -1; 37 | } 38 | for(int i = 0; i < s1.length(); i++) { 39 | if((int)s1.charAt(i) > (int)s2.charAt(i)) { 40 | return 1; 41 | } 42 | if((int)s1.charAt(i) < (int)s2.charAt(i)) { 43 | return -1; 44 | } 45 | } 46 | return 0; 47 | } 48 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Sorting/InsertionSort1.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/insertionsort1 2 | 3 | /* 4 | Time Complexity - O(n^2) 5 | Space Complexity - O(1) 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | class InsertionSort1 { 11 | 12 | static void print(int[] arr) { 13 | for(int i = 0; i < arr.length; i++) { 14 | System.out.print(arr[i] + " "); 15 | } 16 | System.out.println(); 17 | } 18 | 19 | public static void main(String[] args) { 20 | Scanner in = new Scanner(System.in); 21 | 22 | int size = in.nextInt(); 23 | 24 | int[] arr = new int[size]; 25 | 26 | for(int i = 0; i < size; i++) { 27 | arr[i] = in.nextInt(); 28 | } 29 | 30 | int key = arr[size-1]; 31 | 32 | int i = size - 2; 33 | while(i >= 0 && arr[i] > key) { 34 | arr[i+1] = arr[i]; 35 | i--; 36 | print(arr); 37 | } 38 | arr[i+1] = key; 39 | print(arr); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Sorting/InsertionSort2.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/insertionsort2 2 | 3 | /* 4 | Time Complexity - O(n^2) 5 | Space Complexity - O(1) 6 | 7 | Test Case 1 8 | 6 9 | 1 4 3 5 6 2 10 | 11 | */ 12 | 13 | import java.util.Scanner; 14 | 15 | class InsertionSort2 { 16 | 17 | public static void insertionSortPart2(int[] ar) 18 | { 19 | int len = ar.length; 20 | 21 | for(int i = 1; i < len; i++) { 22 | int key = ar[i]; 23 | int j = i - 1; 24 | 25 | while(j >=0 && key < ar[j]) { 26 | ar[j+1] = ar[j]; 27 | j--; 28 | } 29 | ar[j+1] = key; 30 | printArray(ar); 31 | } 32 | 33 | } 34 | 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | int s = in.nextInt(); 38 | int[] ar = new int[s]; 39 | for(int i=0;i stringArr2[i]) { 41 | count += stringArr1[i] - stringArr2[i]; 42 | } 43 | } 44 | 45 | return count; 46 | } else { 47 | return -1; 48 | } 49 | } 50 | 51 | public static void main(String[] args) { 52 | Scanner in = new Scanner(System.in); 53 | 54 | int T = in.nextInt(); 55 | 56 | while(T-- > 0) { 57 | String input = in.next(); 58 | 59 | //System.out.println(); 60 | System.out.println(countAnagramDiff(input)); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/BeautifulBinaryString.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/beautiful-binary-string 2 | 3 | /* 4 | First Solution - Replace all 010 substring with special character 5 | and count the number of special characters; 6 | 7 | Second Solution - Split the string with delimeter 010 and count number of partitions; 8 | 9 | Third Solution - read character one by one and check if we get the substring 010 10 | 11 | Fourth Solution - using replaceAll 12 | */ 13 | 14 | import java.util.Scanner; 15 | 16 | public class BeautifulBinaryString { 17 | public static void main(String[] args) { 18 | Scanner scanner = new Scanner(System.in); 19 | 20 | int n = scanner.nextInt(); 21 | 22 | String input = scanner.next(); 23 | 24 | System.out.println((input.length() - input.replaceAll("010", "").length())/3); 25 | } 26 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/GameOfThrones1.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/game-of-thrones 2 | 3 | /* 4 | 0 - 9 = 48 - 57 5 | A - Z = 65 - 90 6 | a - z = 97 - 122 7 | Initial Thought - Since the max length of string can be 10^5 which is large, 8 | Count the characters and use counting sort techinque to find 9 | all the characters numbers 10 | Now, if every character is even then the string's anagram is palindrome 11 | or if every character is even number and only one is 1, then also the string's anagram is palindrome 12 | 13 | Time Complexity - O(n), n for parsing the string + 26 for parsing the countArr 14 | Space Complexity - O(1) for arr of size 26 15 | */ 16 | 17 | import java.util.Scanner; 18 | 19 | class GameOfThrones1 { 20 | 21 | public static boolean checkPalindrome(int[] countArr) { 22 | boolean palindrome = true; 23 | for(int i = 0; i < 26; i++) { 24 | if(countArr[i] % 2 == 1) { 25 | 26 | if(!palindrome) { 27 | return false; 28 | } 29 | palindrome = false; 30 | 31 | } 32 | } 33 | return true; 34 | } 35 | 36 | public static void main(String[] args) { 37 | Scanner in = new Scanner(System.in); 38 | 39 | String s = in.next(); 40 | 41 | int len = s.length(); 42 | int[] countArr = new int[26]; 43 | 44 | for(int i = 0; i < len; i++) { 45 | countArr[s.charAt(i) - 97]++; 46 | } 47 | 48 | String ans = checkPalindrome(countArr) ? "YES" : "NO"; 49 | System.out.println(ans); 50 | } 51 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/Gemstones.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/gem-stones 2 | 3 | /* 4 | Initial Thought - create an array representing 26 alphabets, 5 | increment for each unique character and 6 | if the number of characters are equal to number of string 7 | then its a gem element 8 | 9 | Second Thought - Question if ambiguous, what if there are 2 same gem element present 10 | in each rock, if that is the case then we should create 3 arrays, 11 | each representing one rock. 12 | 13 | Input - 14 | 3 15 | abcdde 16 | baccd 17 | eeabg 18 | 19 | */ 20 | 21 | import java.util.Scanner; 22 | 23 | class Gemstones { 24 | public static void main(String[] args) { 25 | Scanner in = new Scanner(System.in); 26 | 27 | int N = in.nextInt(); 28 | 29 | 30 | int[][] countArr = new int[N][26]; 31 | 32 | for(int j = 0; j < N; j++) { 33 | String input = in.next(); 34 | 35 | int inputLen = input.length(); 36 | 37 | for(int i = 0; i < inputLen; i++) { 38 | int index = (int)input.charAt(i) - 97; 39 | 40 | countArr[j][index]++; 41 | } 42 | } 43 | 44 | int numOfGems = 0; 45 | 46 | for(int i = 0; i < 26; i++) { 47 | int min = 101; 48 | for(int j = 0; j < N; j++) { 49 | if(countArr[j][i] < min) { 50 | min = countArr[j][i]; 51 | } 52 | } 53 | numOfGems += min; 54 | } 55 | 56 | System.out.println(numOfGems); 57 | } 58 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/MakingAnagrams.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/making-anagrams 2 | 3 | /* 4 | Logic - count the number of each type of character present in each string, 5 | subtract the larger with smaller count to get the number of deletions. 6 | 7 | Space Complexity = O(26 + 26) = O(1) 8 | 26 = to store the count of characters in 1st string 9 | 26 = to store the count of characters in 2nd string 10 | 11 | Time Complexity = O(n1 + n2 + 26) = O(n), where n = length of string 12 | n1 = length of 1st string 13 | n2 = length of 2nd string 14 | 26 = to iterate and get difference in both string each character count 15 | */ 16 | 17 | import java.util.Scanner; 18 | import java.lang.Math.*; 19 | 20 | class MakingAnagrams { 21 | 22 | static int makingAnagrams(String s1, String s2) { 23 | int[] countS1 = new int[26]; 24 | int[] countS2 = new int[26]; 25 | 26 | for(int i = 0; i < s1.length(); i++) { 27 | countS1[(int)s1.charAt(i) - 97]++; 28 | } 29 | 30 | for(int i = 0; i < s2.length(); i++) { 31 | countS2[(int)s2.charAt(i) -97]++; 32 | } 33 | 34 | int count = 0; 35 | for(int i = 0; i < 26; i++) { 36 | count += Math.abs(countS1[i] - countS2[i]); 37 | } 38 | 39 | return count; 40 | } 41 | 42 | public static void main(String[] args) { 43 | Scanner in = new Scanner(System.in); 44 | 45 | String s1 = in.next(); 46 | String s2 = in.next(); 47 | 48 | int result = makingAnagrams(s1, s2); 49 | System.out.println(result); 50 | } 51 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/MarsExploration.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/mars-exploration 2 | 3 | import java.util.Scanner; 4 | 5 | class MarsExploration { 6 | public static void main(String[] args) { 7 | 8 | Scanner in = new Scanner(System.in); 9 | 10 | String input = in.next(); 11 | 12 | int altered = 0; 13 | for(int i = 0; i < input.length(); i++) { 14 | 15 | if((i-1)%3 == 0) { 16 | if(input.charAt(i) != 'O') { 17 | altered++; 18 | } 19 | } else { 20 | if(input.charAt(i) != 'S') { 21 | altered++; 22 | } 23 | } 24 | 25 | } 26 | 27 | System.out.println(altered); 28 | } 29 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/TheLoveLetterMystery.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/the-love-letter-mystery 2 | 3 | /* 4 | Also can use Math.abs(first - second) to calculate the difference 5 | without checking for less than or greater than 6 | and only checking != 7 | if(first != second) 8 | steps += Math.abs(first - second); 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | class TheLoveLetterMystery { 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | 17 | int T = in.nextInt(); 18 | while(T-- > 0) { 19 | String input = in.next(); 20 | 21 | int len = input.length(); 22 | int steps = 0; 23 | 24 | for(int i = 0; i < len/2; i++) { 25 | 26 | int first = (int) input.charAt(i); 27 | int second = (int) input.charAt(len - i - 1); 28 | 29 | if(first < second) { 30 | steps += second - first; 31 | } else if(first > second) { 32 | steps += first - second; 33 | } 34 | } 35 | 36 | System.out.println(steps); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/Strings/TwoStrings.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/two-strings 2 | 3 | /* 4 | Initial Solution - run through both the strings and check if any alphabet exists in the other string. 5 | 6 | Time Complexity - O(n^2) 7 | Space Complexity - O(1) 8 | 9 | Optimization 1 - check the smaller string with larger string 10 | 11 | Optimization 2 - create two boolean array for each string and check if that alphabet exists and save it in array 12 | if both alphabets are present in each boolean arrays than substring present and break the loop 13 | 14 | Time Complexity - O(N) - O(MAX(n1, n2)) 15 | Space Complexity - O(1) - O(26 + 26) 16 | */ 17 | 18 | import java.util.Scanner; 19 | 20 | class TwoStrings { 21 | 22 | static String twoStrings(String s1, String s2){ 23 | // Complete this function 24 | int i = 0, j = 0; 25 | boolean substringFound = false; 26 | boolean[] arr1 = new boolean[26]; 27 | boolean[] arr2 = new boolean[26]; 28 | 29 | for(i = 0; i < s1.length(); i++) { 30 | arr1[s1.charAt(i) - 97] = true; 31 | } 32 | 33 | for(i = 0; i < s2.length(); i++) { 34 | arr2[s2.charAt(i) - 97] = true; 35 | } 36 | 37 | for(i = 0; i < 26; i++) { 38 | if(arr1[i] && arr2[i]) { 39 | substringFound = true; 40 | break; 41 | } 42 | } 43 | 44 | return substringFound ? "YES" : "NO"; 45 | } 46 | 47 | public static void main(String[] args) { 48 | Scanner in = new Scanner(System.in); 49 | int q = in.nextInt(); 50 | for(int a0 = 0; a0 < q; a0++){ 51 | String s1 = in.next(); 52 | String s2 = in.next(); 53 | String result = twoStrings(s1, s2); 54 | System.out.println(result); 55 | } 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /HackerRank/Algorithms/prime.py: -------------------------------------------------------------------------------- 1 | def gen_primes(): 2 | """ Generate an infinite sequence of prime numbers. 3 | """ 4 | # Maps composites to primes witnessing their compositeness. 5 | # This is memory efficient, as the sieve is not "run forward" 6 | # indefinitely, but only as long as required by the current 7 | # number being tested. 8 | # 9 | D = {} 10 | 11 | # The running integer that's checked for primeness 12 | q = 2 13 | 14 | while True: 15 | if q not in D: 16 | # q is a new prime. 17 | # Yield it and mark its first multiple that isn't 18 | # already marked in previous iterations 19 | # 20 | yield q 21 | D[q * q] = [q] 22 | else: 23 | # q is composite. D[q] is the list of primes that 24 | # divide it. Since we've reached q, we no longer 25 | # need it in the map, but we'll mark the next 26 | # multiples of its witnesses to prepare for larger 27 | # numbers 28 | # 29 | for p in D[q]: 30 | D.setdefault(p + q, []).append(p) 31 | del D[q] 32 | 33 | q += 1 34 | 35 | primes = gen_primes() 36 | 37 | 38 | x = set() 39 | y = 0 40 | a = gen_primes() 41 | while y < 10000: 42 | x |= set([a.next()]) 43 | y+=1 44 | 45 | print "x contains {:,d} primes".format(len(x)) 46 | print "largest is {:,d}".format(sorted(x)[-1]) -------------------------------------------------------------------------------- /HackerRank/DataStructures/Arrays/SparseArrays.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.io.PrintWriter; 4 | import java.io.IOException; 5 | 6 | public class SparseArrays { 7 | 8 | public static void main(String[] args) throws IOException { 9 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 10 | PrintWriter wr = new PrintWriter(System.out); 11 | 12 | int n = Integer.parseInt(br.readLine().trim()); 13 | 14 | String[] arr = new String[n]; 15 | for(int i = 0; i < n; i++) { 16 | arr[i] = br.readLine(); 17 | } 18 | 19 | int q = Integer.parseInt(br.readLine().trim()); 20 | 21 | int count; 22 | for(int i = 0; i < q; i++) { 23 | count = 0; 24 | String input = br.readLine(); 25 | for(int j = 0; j < n; j++) { 26 | if(arr[j].equals(input)) { 27 | count++; 28 | } 29 | } 30 | System.out.println(count); 31 | } 32 | 33 | wr.close(); 34 | br.close(); 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /Interview/Microsoft/RemoveReduntantPoints.java: -------------------------------------------------------------------------------- 1 | // 0,20 -> 10,20 -> 10,15 -> 10,10 -> 20,10 -> 20,0 -> 25,0 -> 30,0 2 | 3 | /* 4 | Test cases - 5 | 8 6 | 0 20 10 20 10 15 10 10 20 10 20 0 25 0 30 0 7 | 8 | Num of nodes - 6 9 | Solution - 0,20 -> 10,20 -> 10,10 -> 20,10 -> 20,0 -> 30,0 10 | 11 | Horizontal test case - 12 | 4 13 | 20 10 25 10 30 10 35 10 14 | */ 15 | 16 | import java.util.Scanner; 17 | 18 | class RemoveReduntantPoints { 19 | 20 | public static void main(String[] args) { 21 | 22 | Scanner in = new Scanner(System.in); 23 | 24 | System.out.println("Enter number of nodes - "); 25 | int numOfNodes = in.nextInt(); 26 | 27 | LinkedList linkedList = new LinkedList(); 28 | 29 | while(numOfNodes-- > 0) { 30 | int X = in.nextInt(); 31 | int Y = in.nextInt(); 32 | 33 | Node node = new Node(X, Y); 34 | linkedList.add(node); 35 | } 36 | 37 | linkedList.print(); 38 | 39 | linkedList.removeRedundants(); 40 | 41 | linkedList.print(); 42 | 43 | } 44 | 45 | } 46 | 47 | class LinkedList { 48 | 49 | Node head; 50 | 51 | LinkedList() { 52 | head = null; 53 | } 54 | 55 | public void add(Node node) { 56 | if(head == null) { 57 | head = node; 58 | return; 59 | } 60 | 61 | Node current = head; 62 | 63 | while(current.next != null) { 64 | current = current.next; 65 | } 66 | 67 | current.next = node; 68 | } 69 | 70 | public void removeRedundants() { 71 | if(head == null) { 72 | return; 73 | } 74 | 75 | Node current = head; 76 | Node next = current.next; 77 | int count = 0; 78 | 79 | while(next.next != null && current.Y == next.Y) { 80 | count++; 81 | next = next.next; 82 | } 83 | 84 | if(count > 1) { 85 | current.next = next; 86 | } 87 | 88 | } 89 | 90 | public void print() { 91 | Node current = head; 92 | 93 | while(current != null) { 94 | System.out.print(" -> " + current.X + "," + current.Y); 95 | current = current.next; 96 | } 97 | System.out.println(); 98 | } 99 | } 100 | 101 | class Node { 102 | int X; 103 | int Y; 104 | Node next; 105 | 106 | Node(int X, int Y) { 107 | this.X = X; 108 | this.Y = Y; 109 | next = null; 110 | } 111 | 112 | } -------------------------------------------------------------------------------- /LeetCode/Dynamic Programming/ClimbingStairsBruteForce.java: -------------------------------------------------------------------------------- 1 | // Problem - https://leetcode.com/problems/climbing-stairs/ 2 | // Solution - https://leetcode.com/problems/climbing-stairs/#/solution 3 | 4 | import java.util.Scanner; 5 | 6 | class ClimbingStairsBruteForce { 7 | 8 | static int n1 = 0, n2 = 1, n3; 9 | 10 | static void recurseFibonacciSeries(int count) { 11 | if(count > 0) { 12 | n3 = n1 + n2; 13 | n1 = n2; 14 | n2 = n3; 15 | System.out.print(" " + n3); 16 | recurseFibonacciSeries(count - 1); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner in = new Scanner(System.in); 22 | 23 | System.out.print("Enter n - "); 24 | int n = in.nextInt(); 25 | 26 | System.out.print(n1 + " " + n2); 27 | recurseFibonacciSeries(n-2); 28 | } 29 | } -------------------------------------------------------------------------------- /TopCoder/RecusionBasic.java: -------------------------------------------------------------------------------- 1 | // https://www.topcoder.com/community/data-science/data-science-tutorials/an-introduction-to-recursion-part-1/ 2 | // https://www.topcoder.com/community/data-science/data-science-tutorials/an-introduction-to-recursion-part-2/ 3 | 4 | class RecusionBasic { 5 | 6 | static int N; 7 | 8 | public static void main(String[] args) { 9 | 10 | N = 4; 11 | int[][] arr = new int[][] {{-1, 0, 0, 1}, {0, 0, -1, 0}, {0, -1, 0, 0}, {2, 0, -1, 0}}; 12 | boolean[][] visited = new boolean[N][N]; 13 | 14 | for(int i = 0; i < N; i++) { 15 | for(int j = 0; j < N; j++) { 16 | System.out.print(arr[i][j]); 17 | } 18 | System.out.println(); 19 | } 20 | 21 | // we have to find if we can reach from 1 to 2 22 | // visited[0][3] = true; 23 | System.out.println(checkPath(arr, visited, 0, 3)); 24 | 25 | for(int i = 0; i < N; i++) { 26 | for(int j = 0; j < N; j++) { 27 | System.out.print(visited[i][j]); 28 | } 29 | System.out.println(); 30 | } 31 | 32 | } 33 | 34 | static boolean checkPath(int[][] arr, boolean[][] visited, int i , int j) { 35 | if(i < N && j < N && i > -1 && j > -1) { 36 | System.out.println("i - " + i + " j - " + j); 37 | if(arr[i][j] == 2) { 38 | return true; 39 | } 40 | 41 | if(arr[i][j] == -1) { 42 | visited[i][j] = true; 43 | return false; 44 | } 45 | 46 | // check for visited 47 | if(!visited[i][j]) { 48 | visited[i][j] = true; 49 | System.out.println("Visit - i - " + i + " j - " + j); 50 | if(checkPath(arr, visited, i-1, j)) return true; 51 | if(checkPath(arr, visited, i+1, j)) return true; 52 | if(checkPath(arr, visited, i, j-1)) return true; 53 | if(checkPath(arr, visited, i, j+1)) return true; 54 | } 55 | } 56 | return false; 57 | } 58 | } --------------------------------------------------------------------------------