├── Adhoc Problems ├── CircularListOfStudents.cpp ├── InterestingSequences.cpp ├── LightUpTheBulbs.cpp └── WinningStrategy.cpp ├── Advance Graphs ├── AIRPORTS.cpp ├── Bottom.cpp ├── ConnectedHorse.cpp ├── ConnectedHorses.cpp ├── Dominos.cpp ├── EdgesInMST.cpp ├── FILLMTR.cpp ├── KingdomOfMonkeys.cpp ├── MonkAndTheIslands.cpp ├── NewYearTransportation.cpp └── PermutationSwaps.cpp ├── Advance Recursion ├── MergeSortCode.cpp ├── PrintKeypadCombinationsCode.cpp ├── QuickSortCode.cpp ├── RemoveDuplicatesRecusively.cpp ├── ReplaceCharacterRecursively.cpp └── ReturnKeypadCode.cpp ├── Assignment - Backtracking , Binary Search And Merge Sort Problems ├── CollectingTheBalls.cpp ├── FindPowerOfNumber.cpp ├── SortingTheSkills.cpp └── SudokuSolver.cpp ├── BackTracking ├── CrosswordProblem.cpp ├── N_QueenProblem.cpp └── RatInAMazeProblem.cpp ├── Basics of Recursion ├── Allindices.cpp ├── CheckNumber.cpp ├── FirstIndexOfNumber.cpp ├── LastIndex.cpp ├── NumOfDigits.cpp ├── Power.cpp ├── PrintNumbers.cpp └── SumOfArray.cpp ├── Bit Manipulation ├── ClearAllBitsFromMSB.cpp ├── FindFirstSetBit.cpp ├── Set_ith_Bit.cpp ├── TurnOff1stSetBit.cpp └── Unset_ith_Bit.cpp ├── Dynamic Programming - 1 ├── AdjacentBitCounts.cpp ├── AlphaCode-Question.cpp ├── AlyonaAndSpreadsheet.cpp ├── AngryChildren.cpp ├── Boredom.cpp ├── CoinChangeProblem.cpp ├── CountBSTs.cpp ├── HasanAndTrip.cpp ├── JonSnowAndHisFavouriteNumber.cpp ├── LargestBitonicSubarray.cpp ├── LootHouses.cpp ├── MagicGridProblem.cpp ├── MaximumSquareMatrixWithAllZeros.cpp ├── MinimumCount.cpp ├── MinimumNumberofChocolates.cpp ├── RoyAndCoinBoxes.cpp ├── StairCaseProblem.cpp └── VanyaAndGCD.cpp ├── Dynamic Programming - 2 ├── BalikaVadhu.cpp ├── CharlieAndPilots.cpp ├── DistinctSubsequences.cpp ├── EditDistance.cpp ├── Knapsnack.cpp ├── LCS.cpp ├── MiserMan.cpp ├── PARTY.cpp ├── ShortestSubsequence.cpp ├── SmallestSuperSequence.cpp ├── SquareBrackets.cpp ├── SubsetSum.cpp └── TraderProfit.cpp ├── Graphs 1 ├── 3Cycle.cpp ├── AllConnectedComponents.cpp ├── BFSTraversal.cpp ├── CodingNinjas.cpp ├── ConnectingDots.cpp ├── GetPathBFS.cpp ├── GetPathDFS.cpp ├── HasPath.cpp ├── IsConnected.cpp ├── Islands.cpp └── LargestPiece.cpp ├── Graphs 2 ├── Dijkstra'sAlgorithm.cpp ├── Kruskal'sAlgorithm.cpp └── Prim'sAlgorithm.cpp ├── Greedy Problems ├── ActivitySelection.cpp ├── FractionalKnapsack.cpp ├── Min.AbsoluteDifferenceInArray.cpp ├── NikunjAndDonuts.cpp ├── PerimeterWithConditions.cpp ├── ProblemDiscussion.cpp ├── WeightedJobScheduling.cpp └── WinningLottery.cpp ├── Language Tools + Time and Complexity Assignment ├── DuplicateinArray.cpp ├── FindTheUniqueElement.cpp ├── LongestConsecutiveSequence.cpp ├── PairSumto0.cpp ├── RotateArray.cpp ├── SumMeUp.cpp └── TripletSum.cpp ├── Language Tools ├── DifferentNames.cpp ├── ExtractUniqueChar.cpp ├── LoveForChar.cpp ├── TellThePositions.cpp └── WarmReception.cpp ├── Modulo Arithmetic └── NumberOfBalancedBTs.cpp ├── Prerequisites ├── Even&Odd_Indexes.cpp ├── OscillatingPricesofChakri.cpp ├── PRE4.cpp ├── TargetMarbles.cpp └── TotalSum_Boundaries&Diagonals.cpp ├── README.md ├── Searching & Sorting Applications ├── AggressiveCowsProblem.cpp ├── DistributeCandies.cpp ├── InversionCount.cpp ├── MomosMarket.cpp ├── Murder.cpp └── TajMahalEntry.cpp ├── Segment Tree ├── 2VS3.cpp ├── Counting Even_Odd.cpp ├── HorribleQueries.cpp ├── MaximumPairSum.cpp ├── MaximumSumInSubarray.cpp ├── MinimumInSubArray.cpp ├── SumOfSquares.cpp └── VasyaVSRhezo.cpp └── String Algorithms └── StringSearch.cpp /Adhoc Problems/CircularListOfStudents.cpp: -------------------------------------------------------------------------------- 1 | Circular List of Students 2 | Send Feedback 3 | You are given a circular list of students as follows: 4 | 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 5 | This list is circular, means that 11 will follow 0 again. You will be given the student number ‘i’ and some position ‘p’. You will have to tell that if the list will start from (i+1)th student, then which student will be at pth position. 6 | Input Format: 7 | First line will have an integer ‘t’, denoting the number of test cases. 8 | Next line will have two space separated integers denoting the value of ‘i’ and ‘p’ respectively. 9 | Output Format: 10 | Print ‘t’ lines containing single integer denoting the student number. 11 | Constraints: 12 | 1 <= t <= 10^5 13 | 0 <= i <= 11 14 | 1 <= p <= 12 15 | Sample Input: 16 | 2 17 | 2 3 18 | 5 8 19 | Sample Output: 20 | 5 21 | 1 22 | Explanation: 23 | First, list will start at 3. 3 -> 4 -> 5. Hence, 5 will be at third position. 24 | Second, list will start at 6. 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 0 -> 1. Hence, 1 will be at 8th position. 25 | 26 | 27 | /********************************************************* SOLUTION ***************************************************/ 28 | 29 | 30 | #include 31 | using namespace std; 32 | 33 | int main() { 34 | 35 | int t; 36 | cin>>t; 37 | 38 | while(t-->0) { 39 | 40 | int i,p; 41 | cin>>i>>p; 42 | 43 | cout<<(i+p)%12< 50 | 51 | using namespace std; 52 | 53 | int go(int i, int p){ 54 | int ans = (i+p)%12; 55 | return ans; 56 | } 57 | 58 | 59 | int main( int argc , char ** argv ) 60 | { 61 | ios_base::sync_with_stdio(false) ; 62 | cin.tie(NULL) ; 63 | 64 | int t; 65 | cin>>t; 66 | 67 | while(t--){ 68 | int i, p; 69 | cin>>i>>p; 70 | 71 | cout << go(i, p) << '\n'; 72 | } 73 | 74 | 75 | return 0 ; 76 | 77 | 78 | 79 | } 80 | 81 | */ 82 | -------------------------------------------------------------------------------- /Advance Graphs/Dominos.cpp: -------------------------------------------------------------------------------- 1 | Dominos 2 | Send Feedback 3 | Domino 4 | Dominos are lots of fun. Children like to stand the tiles on their side in long lines. When one domino falls, it knocks down the next one, which knocks down the one after that, all the way down the line. 5 | However, sometimes a domino fails to knock the next one down. In that case, we have to knock it down by hand to get the dominos falling again. 6 | Your task is to determine, given the layout of some domino tiles, the minimum number of dominos that must be knocked down by hand in order for all of the dominos to fall. 7 | Input 8 | The first line of input contains one integer specifying the number of test cases to follow.Each test case begins with a line containing two integers,each no larger than 100 000. The first integer n is the number of domino tiles and the second integer m is the number of lines to follow in the test case. The domino tiles are numbered from 1 to n. 9 | Each of the following lines contains two integers x and y indicating that if domino number x falls, it will cause domino number y to fall as well. 10 | Output 11 | For each test case, output a line containing one integer, the minimum number of dominos that must be knocked over by hand in order for all the dominos to fall. 12 | Sample Input 13 | 1 14 | 3 2 15 | 1 2 16 | 2 3 17 | Sample Output 18 | 1 19 | 20 | 21 | /************************************************** SOLUTION ***********************************************/ 22 | 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | stack st; 31 | vector adjList[100010]; 32 | bool visited[100010]; 33 | 34 | 35 | void dfs2(int index){ 36 | visited[index]=true; 37 | for(unsigned int j=0;j 50 | #include 51 | #include 52 | using namespace std; 53 | //////////////////////////////////////// 54 | const int N = 1e5 + 5; 55 | bool error; 56 | int col[N]; 57 | vector> adj[N]; 58 | //////////////////////////////////////// 59 | void dfs(int start) 60 | { 61 | for (auto edge : adj[start]) 62 | { 63 | int next = edge.first; 64 | if (col[next] == -1) 65 | { 66 | col[next] = col[start] ^ edge.second; 67 | dfs(next); 68 | } 69 | else if (col[next] != col[start] ^ edge.second) 70 | { 71 | error = true; 72 | } 73 | } 74 | } 75 | //////////////////////////////////////// 76 | int main() 77 | { 78 | int t; 79 | cin >> t; 80 | while (t--) 81 | { 82 | int n, m; 83 | cin >> n >> m; 84 | error = false; 85 | for (int i = 1; i <= n; i++) 86 | { 87 | adj[i].clear(); 88 | col[i] = -1; 89 | } 90 | while (m--) 91 | { 92 | int a, b, c; 93 | cin >> a >> b >> c; 94 | adj[a].push_back(make_pair(b, c)); 95 | adj[b].push_back(make_pair(a, c)); 96 | } 97 | for (int i = 1; i <= n; i++) 98 | { 99 | if (col[i] == -1) 100 | { 101 | col[i] = 0; 102 | dfs(i); 103 | } 104 | } 105 | if (error) 106 | cout << "no" << endl; 107 | else 108 | cout << "yes" << endl; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /Advance Graphs/MonkAndTheIslands.cpp: -------------------------------------------------------------------------------- 1 | Monk and the Islands 2 | Send Feedback 3 | MONK AND THE ISLAND 4 | Monk visits the land of Islands. There are a total of N islands numbered from 1 to N. Some pairs of islands are connected to each other by Bidirectional bridges running over water. 5 | Monk hates to cross these bridges as they require a lot of efforts. He is standing at Island #1 and wants to reach the Island #N. Find the minimum the number of bridges that he shall have to cross, if he takes the optimal route. 6 | Input: 7 | First line contains T. T testcases follow. 8 | First line of each test case contains two space-separated integers N, M. 9 | Each of the next M lines contains two space-separated integers X and Y , denoting that there is a bridge between Island X and Island Y. 10 | Output: 11 | Print the answer to each test case in a new line. 12 | Constraints: 13 | 1 ≤ T ≤ 10 14 | 1 ≤ N ≤ 10000 15 | 1 ≤ M ≤ 100000 16 | 1 ≤ X, Y ≤ N 17 | SAMPLE INPUT 18 | 2 19 | 3 2 20 | 1 2 21 | 2 3 22 | 4 4 23 | 1 2 24 | 2 3 25 | 3 4 26 | 4 2 27 | SAMPLE OUTPUT 28 | 2 29 | 2 30 | 31 | 32 | /************************************************** SOLUTION ***********************************************/ 33 | 34 | 35 | #include 36 | using namespace std; 37 | #define pencho ios_base::sync_with_stdio(0);cin.tie(0); 38 | #define mod 1000000007 39 | int n; 40 | int dp[10001]; 41 | int solve(vectoradj[]) 42 | { 43 | queueq; 44 | dp[1]=0; 45 | q.push(1); 46 | while(!q.empty()) 47 | { 48 | int idx=q.front(); 49 | q.pop(); 50 | for(int i=0;i>t; 66 | while(t--) 67 | { 68 | cin>>n>>m; 69 | memset(dp,-1,sizeof(dp)); 70 | vectoradj[n+1]; 71 | while(m--) 72 | { 73 | int x,y; 74 | cin>>x>>y; 75 | adj[x].push_back(y); 76 | adj[y].push_back(x); 77 | } 78 | cout< 35 | using namespace std; 36 | 37 | int main(){ 38 | int n, t; 39 | cin >> n >> t; 40 | 41 | // int **graph = new int*[n]; 42 | // for(int i = 0; i < n; i++){ 43 | // graph[i] = new int[n]; 44 | // for(int j = 0; j < n; j++) graph[i][j] = 0; 45 | // } 46 | 47 | int position = 0; 48 | 49 | for(int i = 0; i < n-1; i++){ 50 | if(position == t-1){ 51 | cout << "YES" << endl; 52 | return 0; 53 | } 54 | int a; 55 | cin >> a; 56 | // graph[i][i+a] = 1; 57 | if(i == position) position += a; 58 | } 59 | 60 | cout << "NO" << endl; 61 | } 62 | -------------------------------------------------------------------------------- /Advance Recursion/MergeSortCode.cpp: -------------------------------------------------------------------------------- 1 | Merge Sort Code 2 | Send Feedback 3 | Sort an array A using Merge Sort. 4 | Change in the input array itself. So no need to return or print anything. 5 | Input format : 6 | Line 1 : Integer n i.e. Array size 7 | Line 2 : Array elements (separated by space) 8 | Output format : 9 | Array elements in increasing order (separated by space) 10 | Constraints : 11 | 1 <= n <= 10^3 12 | Sample Input 1 : 13 | 6 14 | 2 6 8 5 4 3 15 | Sample Output 1 : 16 | 2 3 4 5 6 8 17 | Sample Input 2 : 18 | 5 19 | 2 1 5 2 3 20 | Sample Output 2 : 21 | 1 2 2 3 5 22 | 23 | 24 | /**************************************** SOLUTION *************************************/ 25 | 26 | 27 | void merge(int input1[], int size1, int input2[], int size2, int output[]){ 28 | int i = 0, j = 0, k = 0; 29 | while(i < size1 && j < size2){ 30 | if(input1[i] < input2[j]){ 31 | output[k] = input1[i]; 32 | k++; 33 | i++; 34 | } 35 | else{ 36 | output[k] = input2[j]; 37 | j++; 38 | k++; 39 | } 40 | } 41 | while( i < size1){ 42 | output[k] = input1[i]; 43 | k++; 44 | i++; 45 | } 46 | while(j < size2){ 47 | output[k] = input2[j]; 48 | j++; 49 | k++; 50 | } 51 | } 52 | void mergeSort(int input[], int size){ 53 | if(size <= 1){ 54 | return; 55 | } 56 | int mid = size / 2; 57 | int part1[500], part2[500]; 58 | int size1 = mid, size2 = size - mid; 59 | for(int i = 0; i < mid; i++){ 60 | part1[i] = input[i]; 61 | } 62 | int k = 0; 63 | for(int i = mid ; i < size; i++){ 64 | part2[k] = input[i]; 65 | k++; 66 | } 67 | mergeSort(part1, size1); 68 | mergeSort(part2, size2); 69 | merge(part1, size1, part2, size2, input); 70 | } 71 | -------------------------------------------------------------------------------- /Advance Recursion/PrintKeypadCombinationsCode.cpp: -------------------------------------------------------------------------------- 1 | Print Keypad Combinations Code 2 | Send Feedback 3 | Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n. 4 | Note : The order of strings are not important. Just print different strings in new lines. 5 | Input Format : 6 | Integer n 7 | Output Format : 8 | All possible strings in different lines 9 | Constraints : 10 | 1 <= n <= 10^6 11 | Sample Input: 12 | 23 13 | Sample Output: 14 | ad 15 | ae 16 | af 17 | bd 18 | be 19 | bf 20 | cd 21 | ce 22 | cf 23 | 24 | 25 | /**************************************** SOLUTION *************************************/ 26 | 27 | 28 | #include 29 | #include 30 | using namespace std; 31 | 32 | void printKeypadHelper(int num,string output,string options[10]){ 33 | if(num==0){ 34 | cout< 30 | using namespace std; 31 | int partitionArray(int input[], int start, int end) { 32 | // Chose pivot 33 | int pivot = input[start]; 34 | // Count elements smaller than pivot and swap 35 | int count = 0; 36 | for(int i = start+1; i <= end; i++) { 37 | if(input[i] <= pivot) { 38 | count++; 39 | } 40 | } 41 | int pivotIndex = start + count; 42 | int temp = input[start]; 43 | input[start] = input[pivotIndex]; 44 | input[pivotIndex] = temp; 45 | // ensure left half contains elements smaller than pivot // and right half larger 46 | int i = start, j = end; 47 | while(i <= pivotIndex && j >= pivotIndex) { 48 | while(input[i] <= pivot) { 49 | i++; 50 | } 51 | while(input[j] > pivot) { 52 | j--; 53 | } 54 | if(i < pivotIndex && j > pivotIndex) { 55 | int temp = input[i]; 56 | input[i] = input[j]; 57 | input[j] = temp; 58 | i++; 59 | j--; 60 | } 61 | } 62 | return pivotIndex; 63 | } 64 | void quickSort(int input[], int start, int end) { 65 | if(start >= end) { 66 | return; 67 | } 68 | int pivotIndex = partitionArray(input, start, end); 69 | quickSort(input, start, pivotIndex-1); 70 | quickSort(input, pivotIndex+1, end); 71 | } 72 | void quickSort(int input[], int n) { 73 | quickSort(input, 0, n - 1); 74 | } 75 | -------------------------------------------------------------------------------- /Advance Recursion/RemoveDuplicatesRecusively.cpp: -------------------------------------------------------------------------------- 1 | Remove Duplicates Recursively 2 | Send Feedback 3 | Given a string S, remove consecutive duplicates from it recursively. 4 | Input Format : 5 | String S 6 | Output Format : 7 | Output string 8 | Constraints : 9 | 1 <= |S| <= 10^3 10 | where |S| represents the length of string 11 | Sample Input 1 : 12 | aabccba 13 | Sample Output 1 : 14 | abcba 15 | Sample Input 2 : 16 | xxxyyyzwwzzz 17 | Sample Output 2 : 18 | xyzwz 19 | 20 | 21 | /**************************************** SOLUTION *************************************/ 22 | 23 | 24 | void remove(char *input, int newIndex,int index) { 25 | if(input[index]=='\0') { 26 | input[newIndex]=input[index-1]; 27 | input[newIndex+1]='\0'; 28 | return; 29 | } 30 | if(input[index]==input[index-1]) { 31 | remove(input,newIndex,index+1); 32 | return; 33 | } 34 | else input[newIndex]=input[index-1]; 35 | remove(input,newIndex+1,index+1); 36 | } 37 | void removeConsecutiveDuplicates(char *input) { 38 | remove(input,0,1); 39 | } 40 | -------------------------------------------------------------------------------- /Advance Recursion/ReplaceCharacterRecursively.cpp: -------------------------------------------------------------------------------- 1 | Replace Character Recursively 2 | Send Feedback 3 | Given an input string S and two characters c1 and c2, you need to replace every occurrence of character c1 with character c2 in the given string. 4 | Do this recursively. 5 | Input Format : 6 | Line 1 : Input String S 7 | Line 2 : Character c1 and c2 (separated by space) 8 | Output Format : 9 | Updated string 10 | Constraints : 11 | 1 <= Length of String S <= 10^6 12 | Sample Input : 13 | abacd 14 | a x 15 | Sample Output : 16 | xbxcd 17 | 18 | 19 | /**************************************** SOLUTION *************************************/ 20 | 21 | void replaceCharacter(char input[], char c1, char c2) { 22 | if(input[0] == '\0') { 23 | return; 24 | } 25 | if(input[0] == c1) { 26 | input[0] = c2; 27 | } 28 | replaceCharacter(input + 1, c1, c2); 29 | } 30 | -------------------------------------------------------------------------------- /Advance Recursion/ReturnKeypadCode.cpp: -------------------------------------------------------------------------------- 1 | Return Keypad Code 2 | Send Feedback 3 | Given an integer n, using phone keypad find out all the possible strings that can be made using digits of input n. 4 | Return empty string for numbers 0 and 1. 5 | Note : 1. The order of strings are not important. 6 | 2. Input and output has already been managed for you. You just have to populate the output array and return the count of elements populated in the output array. 7 | Input Format : 8 | Integer n 9 | Output Format : 10 | All possible strings in different lines 11 | Constraints : 12 | 1 <= n <= 10^6 13 | Sample Input: 14 | 23 15 | Sample Output: 16 | ad 17 | ae 18 | af 19 | bd 20 | be 21 | bf 22 | cd 23 | ce 24 | cf 25 | 26 | 27 | /**************************************** SOLUTION *************************************/ 28 | 29 | 30 | #include 31 | using namespace std; 32 | string a[]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 33 | 34 | 35 | int keypad(int num, string output[]){ 36 | if(num==0) 37 | { 38 | output[0]=""; 39 | return 1; 40 | } 41 | int b=num%10; 42 | num=num/10; 43 | int c=keypad(num,output); 44 | for(int i=0;i 32 | 33 | using namespace std; 34 | 35 | long long helper(long long start, long long end, long long N, long long &ans){ 36 | // cout << "start: "< end) 40 | { 41 | return ans; 42 | } 43 | 44 | long long n = N; 45 | 46 | long long mid = (start+end)/2; 47 | //cout << "mid; "<=k && n>0){ 54 | sharma += k; 55 | n = n-k; 56 | singh += (n)/10; 57 | n = n-(n)/10; 58 | } 59 | 60 | sharma += n; 61 | // cout << "sharma: " <>n; 88 | 89 | cout << helper(1, n, n, n) << '\n'; 90 | 91 | 92 | return 0 ; 93 | 94 | } 95 | -------------------------------------------------------------------------------- /Assignment - Backtracking , Binary Search And Merge Sort Problems/FindPowerOfNumber.cpp: -------------------------------------------------------------------------------- 1 | Find power of a number 2 | Send Feedback 3 | Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to print the answer. 4 | Note : For this question, you can assume that 0 raised to the power of 0 is 1 5 | 6 | 7 | Input format : 8 | Two integers x and n (separated by space) 9 | Output Format : 10 | x^n (i.e. x raise to the power n) 11 | Constraints: 12 | 0 <= x <= 8 13 | 0 <= n <= 9 14 | Sample Input 1 : 15 | 3 4 16 | Sample Output 1 : 17 | 81 18 | Sample Input 2 : 19 | 2 5 20 | Sample Output 2 : 21 | 32 22 | 23 | 24 | /********************************************* SOLUTION ****************************************************/ 25 | 26 | 27 | #include 28 | 29 | using namespace std; 30 | int power(int x, int n){ 31 | if (n==0) 32 | { 33 | return 1; 34 | } 35 | 36 | return x*power(x, n-1); 37 | 38 | 39 | } 40 | 41 | int main( int argc , char ** argv ) 42 | { 43 | ios_base::sync_with_stdio(false) ; 44 | cin.tie(NULL) ; 45 | 46 | int x, n; 47 | cin>>x>>n; 48 | 49 | cout << power(x,n) << '\n'; 50 | 51 | 52 | return 0 ; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Assignment - Backtracking , Binary Search And Merge Sort Problems/SortingTheSkills.cpp: -------------------------------------------------------------------------------- 1 | Sorting the Skills 2 | Send Feedback 3 | There is a company named James Peterson & Co. The company has ‘n’ employees. The employees have skills from 0 to n-1. All the employees have distinct skills. The manager of James Peterson & Co. wants to sort the employees on the basis of their skills in ascending order. He is only allowed to swap two employees which are adjacent to each other. He is given the skills of employees in an array of size ‘n’. He can swap the skills as long as the absolute difference between their skills is 1. You need to help the manager out and tell whether it is possible to sort the skills of employees or not. 4 | Input Format: 5 | First Line will have an integer ‘t’ denoting the no. of test cases. 6 | First line of each test case contains an integer ‘n’ denoting the no. of employees in the company. 7 | Second line of each test case contains ‘n’ distinct integers in the range [0, n-1]. 8 | Output Format: 9 | For each test case, print “Yes” if it is possible to sort the skills otherwise “No”. 10 | Constraints: 11 | 1 <= t <= 10 12 | 1 <= n <= 10^5 13 | Sample Input: 14 | 2 15 | 4 16 | 1 0 3 2 17 | 3 18 | 2 1 0 19 | Sample Output: 20 | Yes 21 | No 22 | Explanation: 23 | In first T.C., [1, 0, 3, 2] -> [0, 1, 3, 2] -> [0, 1, 2, 3] 24 | In second T.C., [2, 1, 0] -> [1, 2, 0] OR [2, 1, 0] -> [2, 0, 1] So, it is impossible to sort. 25 | 26 | 27 | 28 | /********************************************* SOLUTION ****************************************************/ 29 | 30 | 31 | #include 32 | 33 | using namespace std; 34 | 35 | bool skillSort(vector &skills, int start, int end){ 36 | // cout << start<<" " <= end) 38 | { 39 | return 1; 40 | } 41 | 42 | int n = skills.size(); 43 | int mid = (start+end)/2; 44 | 45 | int left = skillSort(skills, start, mid); 46 | int right = skillSort(skills, mid+1, end); 47 | 48 | if (left!=1 || right != 1) 49 | { 50 | return 0; 51 | } 52 | 53 | if (skills[mid+1]>skills[mid]) 54 | { 55 | return 1; 56 | } 57 | 58 | 59 | if (skills[mid]-skills[mid+1]>1) 60 | { 61 | return 0; 62 | } 63 | 64 | if (skills[mid+1]>t; 81 | 82 | while(t--){ 83 | int n; 84 | cin>>n; 85 | //cout << "n "< skills; 88 | for (int i = 0; i < n; ++i) 89 | { 90 | int temp; 91 | cin>>temp; 92 | skills.push_back(temp); 93 | } 94 | 95 | if (skillSort(skills, 0, n-1)==1) 96 | { 97 | cout << "Yes" << '\n'; 98 | }else{ 99 | cout << "No" << '\n'; 100 | } 101 | 102 | } 103 | 104 | return 0 ; 105 | 106 | } 107 | -------------------------------------------------------------------------------- /Assignment - Backtracking , Binary Search And Merge Sort Problems/SudokuSolver.cpp: -------------------------------------------------------------------------------- 1 | Sudoku Solver 2 | Send Feedback 3 | Given a 9*9 sudoku board, in which some entries are filled and others are 0 (0 indicates that the cell is empty), you need to find out whether the Sudoku puzzle can be solved or not i.e. return true or false. 4 | Input Format : 5 | 9 Lines where ith line contains ith row elements separated by space 6 | Output Format : 7 | true or false 8 | Sample Input : 9 | 9 0 0 0 2 0 7 5 0 10 | 6 0 0 0 5 0 0 4 0 11 | 0 2 0 4 0 0 0 1 0 12 | 2 0 8 0 0 0 0 0 0 13 | 0 7 0 5 0 9 0 6 0 14 | 0 0 0 0 0 0 4 0 1 15 | 0 1 0 0 0 5 0 8 0 16 | 0 9 0 0 7 0 0 0 4 17 | 0 8 2 0 4 0 0 0 6 18 | Sample Output : 19 | true 20 | 21 | 22 | /********************************************* SOLUTION ****************************************************/ 23 | 24 | 25 | bool checkPossible(int board[][9],int row,int col,int val) 26 | { 27 | for(int i=0;i<9;i++) 28 | { 29 | if(board[row][i]==val) 30 | return false; 31 | 32 | if(board[i][col]==val) 33 | return false; 34 | } 35 | 36 | int row_start=(row/3)*3; 37 | int col_start=(col/3)*3; 38 | 39 | int row_end=row_start+3; 40 | int col_end=col_start+3; 41 | 42 | for(int i=row_start;i 26 | 27 | using namespace std; 28 | 29 | int board[11][11]; 30 | 31 | bool isPossible(int n,int row,int col){ 32 | 33 | // Same Column 34 | for(int i=row-1;i>=0;i--){ 35 | if(board[i][col] == 1){ 36 | return false; 37 | } 38 | } 39 | //Upper Left Diagonal 40 | for(int i=row-1,j=col-1;i>=0 && j>=0 ; i--,j--){ 41 | if(board[i][j] ==1){ 42 | return false; 43 | } 44 | } 45 | 46 | // Upper Right Diagonal 47 | 48 | for(int i=row-1,j=col+1;i>=0 && j 39 | using namespace std; 40 | 41 | 42 | void printSolution(int** solution,int n){ 43 | for(int i=0;i=n || x<0 || y>=n || y<0 || maze[x][y] ==0 || solution[x][y] ==1){ 60 | return; 61 | } 62 | solution[x][y] = 1; 63 | mazeHelp(maze,n,solution,x-1,y); 64 | mazeHelp(maze,n,solution,x+1,y); 65 | mazeHelp(maze,n,solution,x,y-1); 66 | mazeHelp(maze,n,solution,x,y+1); 67 | solution[x][y] = 0; 68 | } 69 | void ratInAMaze(int maze[][20], int n){ 70 | 71 | int** solution = new int*[n]; 72 | for(int i=0;i 27 | using namespace std; 28 | void findIndexes(int input[],int currIndex, int size, int x, int output[],int &k) { 29 | if(currIndex==size) 30 | 31 | return; 32 | 33 | 34 | if(input[currIndex]==x) { 35 | 36 | output[k]=currIndex; 37 | k++; 38 | 39 | } 40 | 41 | findIndexes(input,currIndex+1,size,x,output,k); 42 | 43 | } 44 | 45 | int allIndexes(int input[], int size, int x, int output[]) { 46 | 47 | int k=0; 48 | findIndexes(input,0,size,x,output,k); 49 | return k; 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Basics of Recursion/CheckNumber.cpp: -------------------------------------------------------------------------------- 1 | Check Number 2 | Send Feedback 3 | Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false. 4 | Do this recursively. 5 | Input Format : 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Line 3 : Integer x 9 | Output Format : 10 | 'true' or 'false' 11 | Constraints : 12 | 1 <= N <= 10^3 13 | Sample Input 1 : 14 | 3 15 | 9 8 10 16 | 8 17 | Sample Output 1 : 18 | true 19 | Sample Input 2 : 20 | 3 21 | 9 8 10 22 | 2 23 | Sample Output 2 : 24 | false 25 | 26 | 27 | /************************************************************* SOLUTION ***************************************************************/ 28 | 29 | 30 | bool checkNumber(int input[], int size, int x) { 31 | if (size == 0) 32 | return false; 33 | if (input[size-1] == x) 34 | return true; 35 | return checkNumber(input, size-1, x); 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Basics of Recursion/FirstIndexOfNumber.cpp: -------------------------------------------------------------------------------- 1 | First Index of Number 2 | Send Feedback 3 | Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. 4 | First index means, the index of first occurrence of x in the input array. 5 | Do this recursively. Indexing in the array starts from 0. 6 | Input Format : 7 | Line 1 : An Integer N i.e. size of array 8 | Line 2 : N integers which are elements of the array, separated by spaces 9 | Line 3 : Integer x 10 | Output Format : 11 | first index or -1 12 | Constraints : 13 | 1 <= N <= 10^3 14 | Sample Input : 15 | 4 16 | 9 8 10 8 17 | 8 18 | Sample Output : 19 | 1 20 | 21 | 22 | /************************************************************* SOLUTION ***************************************************************/ 23 | 24 | 25 | int firstIndex(int input[], int size, int x) { 26 | if ( size < 1 ) 27 | { 28 | return -1; 29 | } 30 | else if ( input[0] == x) 31 | { 32 | return 0; 33 | } 34 | else 35 | { 36 | int i = firstIndex( input + 1, size - 1, x ); 37 | return i == - 1 ? i : i + 1; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Basics of Recursion/LastIndex.cpp: -------------------------------------------------------------------------------- 1 | Last Index of Number 2 | Send Feedback 3 | Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. 4 | Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. 5 | You should start traversing your array from 0, not from (N - 1). 6 | Do this recursively. Indexing in the array starts from 0. 7 | Input Format : 8 | Line 1 : An Integer N i.e. size of array 9 | Line 2 : N integers which are elements of the array, separated by spaces 10 | Line 3 : Integer x 11 | Output Format : 12 | last index or -1 13 | Constraints : 14 | 1 <= N <= 10^3 15 | Sample Input : 16 | 4 17 | 9 8 10 8 18 | 8 19 | Sample Output : 20 | 3 21 | 22 | 23 | 24 | /************************************************************* SOLUTION ***************************************************************/ 25 | 26 | 27 | int lastIndex(int input[], int size, int x) { 28 | if(size == 0) 29 | { 30 | return -1; 31 | } 32 | 33 | if(size < 1) 34 | return -1; 35 | 36 | size--; 37 | if(input[size] == x) 38 | return size; 39 | 40 | return lastIndex(input, size,x); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Basics of Recursion/NumOfDigits.cpp: -------------------------------------------------------------------------------- 1 | Number of Digits 2 | Send Feedback 3 | Given the code to find out and return the number of digits present in a number recursively. But it contains few bugs, that you need to rectify such that all the test cases should pass. 4 | Input Format : 5 | Integer n 6 | Output Format : 7 | Count of digits 8 | Constraints : 9 | 1 <= n <= 10^6 10 | Sample Input 1 : 11 | 156 12 | Sample Output 1 : 13 | 3 14 | Sample Input 2 : 15 | 7 16 | Sample Output 2 : 17 | 1 18 | 19 | 20 | /********************************************************** SOLUTION ****************************************************************/ 21 | 22 | 23 | int count(int n){ 24 | int countn = 0; 25 | while (n != 0) { 26 | n = n / 10; 27 | ++countn; 28 | } 29 | return countn; 30 | } 31 | -------------------------------------------------------------------------------- /Basics of Recursion/Power.cpp: -------------------------------------------------------------------------------- 1 | Power 2 | Send Feedback 3 | Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to return the answer. 4 | Do this recursively. 5 | Input format : 6 | Two integers x and n (separated by space) 7 | Output Format : 8 | x^n (i.e. x raise to the power n) 9 | Constraints : 10 | 1 <= x <= 30 11 | 0 <= n <= 30 12 | Sample Input 1 : 13 | 3 4 14 | Sample Output 1 : 15 | 81 16 | Sample Input 2 : 17 | 2 5 18 | Sample Output 2 : 19 | 32 20 | 21 | 22 | /********************************************************** SOLUTION ****************************************************************/ 23 | 24 | 25 | int power(int x, int n) { 26 | if(n==0) 27 | return 1; 28 | if(n==1) 29 | return x; 30 | else 31 | return x*power(x,n-1); 32 | } 33 | -------------------------------------------------------------------------------- /Basics of Recursion/PrintNumbers.cpp: -------------------------------------------------------------------------------- 1 | Print Numbers 2 | Send Feedback 3 | Given is the code to print numbers from 1 to n in increasing order recursively. But it contains few bugs that you need to rectify such that all the test cases pass. 4 | Input Format : 5 | Integer n 6 | Output Format : 7 | Numbers from 1 to n (separated by space) 8 | Constraints : 9 | 1 <= n <= 10000 10 | Sample Input 1 : 11 | 6 12 | Sample Output 1 : 13 | 1 2 3 4 5 6 14 | Sample Input 2 : 15 | 4 16 | Sample Output 2 : 17 | 1 2 3 4 18 | 19 | /********************************************************** SOLUTION ****************************************************************/ 20 | 21 | 22 | void print(int n){ 23 | if(n > 0){ 24 | print(n - 1); 25 | cout << n << " "; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Basics of Recursion/SumOfArray.cpp: -------------------------------------------------------------------------------- 1 | Sum of Array 2 | Send Feedback 3 | Given an array of length N, you need to find and return the sum of all elements of the array. 4 | Do this recursively. 5 | Input Format : 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Output Format : 9 | Sum 10 | Constraints : 11 | 1 <= N <= 10^3 12 | Sample Input 1 : 13 | 3 14 | 9 8 9 15 | Sample Output 1 : 16 | 26 17 | Sample Input 2 : 18 | 3 19 | 4 2 1 20 | Sample Output 2 : 21 | 7 22 | 23 | 24 | /********************************************************** SOLUTION ****************************************************************/ 25 | 26 | 27 | int sum(int input[], int n) { 28 | if (n <= 0) 29 | return 0; 30 | return (sum(input, n - 1) + input[n - 1]); 31 | } 32 | -------------------------------------------------------------------------------- /Bit Manipulation/ClearAllBitsFromMSB.cpp: -------------------------------------------------------------------------------- 1 | Clear All Bits From MSB 2 | Send Feedback 3 | You are given two integers N and i. You need to clear all bits from MSB to ith bit (start i from right to left) and return the updated N. 4 | Counting of bits starts from 0 from right to left. 5 | Input Format : 6 | Two integers N and i (separated by space) 7 | Output Format : 8 | Updated N 9 | Sample Input 1 : 10 | 15 2 11 | Sample Output 1 : 12 | 3 13 | Sample Output 1 Explanation : 14 | We need to clear all bits from MSB to ith bit i.e. clear all bits except 0th and 1st. 15 | Sample Input 2 : 16 | 4 4 17 | Sample Output 2 : 18 | 4 19 | 20 | 21 | /******************************************************* SOLUTION ****************************************/ 22 | 23 | 24 | int clearAllBits(int n, int i){ 25 | int mask = (1 << i) - 1; 26 | n &= mask; 27 | return n; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Bit Manipulation/FindFirstSetBit.cpp: -------------------------------------------------------------------------------- 1 | Find first set bit 2 | Send Feedback 3 | You are given an integer N. You need to return an integer M, in which only one bit is set which at position of lowest set bit of N (from right to left). 4 | Input Format : 5 | Integer N 6 | Output Format : 7 | Integer M 8 | Sample Input 1 : 9 | 7 10 | Sample Output 1 : 11 | 1 12 | Sample Input 2 : 13 | 12 14 | Sample Output 2 : 15 | 4 16 | 17 | 18 | /******************************************************* SOLUTION ****************************************/ 19 | 20 | 21 | #include 22 | #include 23 | #include 24 | #define INT_SIZE 32 25 | using namespace std; 26 | int returnFirstSetBit(int n){ 27 | int set_bit = n ^ (n&(n-1)); 28 | return set_bit; 29 | } 30 | -------------------------------------------------------------------------------- /Bit Manipulation/Set_ith_Bit.cpp: -------------------------------------------------------------------------------- 1 | Set ith bit 2 | Send Feedback 3 | You are given two integers N and i. You need to make ith bit of binary representation of N to 1 and return the updated N. 4 | Counting of bits start from 0 from right to left. 5 | Input Format : 6 | Two integers N and i (separated by space) 7 | Output Format : 8 | Updated N 9 | Sample Input 1 : 10 | 4 1 11 | Sample Output 1 : 12 | 6 13 | Sample Input 2 : 14 | 4 4 15 | Sample Output 2 : 16 | 20 17 | 18 | 19 | /******************************************************* SOLUTION ****************************************/ 20 | 21 | 22 | 23 | int turnOnIthBit(int n, int i){ 24 | // kth bit of n is being set by this operation 25 | return ((1 << i) | n); 26 | } 27 | -------------------------------------------------------------------------------- /Bit Manipulation/TurnOff1stSetBit.cpp: -------------------------------------------------------------------------------- 1 | Turn off 1st set bit 2 | Send Feedback 3 | You are given an integer Ni. You need to make first set bit of binary representation of N to 0 and return the updated N. 4 | Counting of bits start from 0 from right to left. 5 | Input Format : 6 | Integer N 7 | Output Format : 8 | Updated N 9 | Sample Input 1 : 10 | 4 11 | Sample Output 1 : 12 | 0 13 | Sample Input 2 : 14 | 12 15 | Sample Output 2 : 16 | 8 17 | 18 | 19 | /******************************************************* SOLUTION ****************************************/ 20 | 21 | int turnOffFirstSetBit(int n){ 22 | 23 | return n & (n - 1); 24 | } 25 | -------------------------------------------------------------------------------- /Bit Manipulation/Unset_ith_Bit.cpp: -------------------------------------------------------------------------------- 1 | Unset ith bit 2 | Send Feedback 3 | You are given two integers N and i. You need to make ith bit of binary representation of N to 0 and return the updated N. 4 | Counting of bits start from 0 from right to left. 5 | Input Format : 6 | Two integers N and i (separated by space) 7 | Output Format : 8 | Updated N 9 | Sample Input 1 : 10 | 7 2 11 | Sample Output 1 : 12 | 3 13 | Sample Input 2 : 14 | 12 1 15 | Sample Output 2 : 16 | 12 17 | 18 | 19 | /******************************************************* SOLUTION ****************************************/ 20 | 21 | 22 | #include 23 | using namespace std; 24 | int turnOffIthBit(int n, int i){ 25 | // k must be greater than 0 26 | if (i < 0) return n; 27 | 28 | // Do & of n with a number with all set bits except 29 | // the k'th bit 30 | return (n & ~(1 << (i))); 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/AdjacentBitCounts.cpp: -------------------------------------------------------------------------------- 1 | Adjacent Bit Counts 2 | Send Feedback 3 | For a string of n bits x1,x2,x3,...,Xn the adjacent bit count of the string (AdjBC(x)) is given by 4 | X1*X2 + X2*X3 + X3*X4 + ... + Xn-1 * Xn 5 | which counts the number of times a 1 bit is adjacent to another 1 bit. For example: 6 | AdjBC(011101101) = 3 7 | AdjBC(111101101) = 4 8 | AdjBC(010101010) = 0 9 | Write a program which takes as input integers n and k and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy AdjBC(x) = k. For example, for 5 bit strings, there are 6 ways of getting AdjBC(x) = 2: 10 | 11100, 01110, 00111, 10111, 11101, 11011 11 | Input 12 | The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by a decimal integer giving the number (n) of bits in the bit strings, followed by a single space, followed by a decimal integer (k) giving the desired adjacent bit count. The number of bits (n) will not be greater than 100. 13 | Output 14 | For each data set there is one line of output. It contains the data set number followed by a single space, followed by the number of n-bit strings with adjacent bit count equal to k. As answer can be very large print your answer modulo 10^9+7. 15 | Sample Input 16 | 10 17 | 1 5 2 18 | 2 20 8 19 | 3 30 17 20 | 4 40 24 21 | 5 50 37 22 | 6 60 52 23 | 7 70 59 24 | 8 80 73 25 | 9 90 84 26 | 10 100 90 27 | Sample Output 28 | 1 6 29 | 2 63426 30 | 3 1861225 31 | 4 168212501 32 | 5 44874764 33 | 6 160916 34 | 7 22937308 35 | 8 99167 36 | 9 15476 37 | 10 23076518 38 | 39 | 40 | 41 | /******************************************************************** SOLUTION ***************************************************************************/ 42 | 43 | 44 | 45 | #include 46 | using namespace std; 47 | #define MOD 1000000007 48 | 49 | long long dp[101][101][2]; 50 | 51 | long long adjacentBitCounts(int n,int k,int first) 52 | { 53 | if(dp[n][k][first] >= 0) 54 | return dp[n][k][first]; 55 | 56 | if(n == 1) 57 | { 58 | if(k == 0) 59 | { 60 | dp[n][k][first] = 1; 61 | return 1; 62 | } 63 | else 64 | { 65 | dp[n][k][first] = 0; 66 | return 0; 67 | } 68 | } 69 | 70 | if(k < 0) 71 | { 72 | dp[n][k][first] = 0; 73 | return 0; 74 | } 75 | 76 | if(first == 1) 77 | { 78 | long long ans1 = adjacentBitCounts(n-1,k-1,1); 79 | long long ans2 = adjacentBitCounts(n-1,k,0); 80 | dp[n][k][first] = (ans1 + ans2)%MOD; 81 | } 82 | else 83 | { 84 | long long ans1 = adjacentBitCounts(n-1,k,1); 85 | long long ans2 = adjacentBitCounts(n-1,k,0); 86 | dp[n][k][first] = (ans1 + ans2)%MOD; 87 | } 88 | 89 | return dp[n][k][first]; 90 | } 91 | 92 | long long countBits(int n,int k) 93 | { 94 | long long ans = (adjacentBitCounts(n,k,0)+adjacentBitCounts(n,k,1))%MOD; 95 | return ans; 96 | } 97 | 98 | int main() 99 | { 100 | int t; 101 | cin >> t; 102 | 103 | for(int i = 0; i <= 101; i++) 104 | { 105 | for(int j = 0; j <= 101; j++) 106 | { 107 | dp[i][j][0] = -1; 108 | dp[i][j][1] = -1; 109 | } 110 | } 111 | 112 | while(t--) 113 | { 114 | int a,n,k; 115 | cin >> a >> n >> k ; 116 | cout< 46 | 47 | using namespace std; 48 | 49 | 50 | int main( int argc , char ** argv ) 51 | { 52 | ios_base::sync_with_stdio(false) ; 53 | cin.tie(NULL) ; 54 | 55 | int m, n; 56 | cin>>m>>n; 57 | vector oldinput(n,0); 58 | vector newinput(n,0); 59 | 60 | vector oldsortedfrom(n,0); 61 | vector newsortedfrom(n,0); 62 | 63 | vector rowsortedfrom(m, 0); 64 | //cout <>newinput[j]; 73 | 74 | if(oldinput[j]<=newinput[j]) 75 | newsortedfrom[j] = oldsortedfrom[j]; 76 | else 77 | newsortedfrom[j] = i; 78 | 79 | minimum = min(minimum, newsortedfrom[j]); 80 | } 81 | // for(int j=0;j>q; 93 | while(q--){ 94 | int left, right; 95 | cin>>left>>right; 96 | 97 | if(rowsortedfrom[right-1]<=left-1) 98 | cout << "Yes" << '\n'; 99 | else 100 | cout << "No" << '\n'; 101 | } 102 | 103 | 104 | return 0 ; 105 | 106 | 107 | 108 | } 109 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/AngryChildren.cpp: -------------------------------------------------------------------------------- 1 | Angry Children 2 | Send Feedback 3 | Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has N packets of candies and would like to distribute one packet to each of the K children in the village (each packet may contain different number of candies). To avoid a fight between the children, he would like to pick K out of N packets such that the unfairness is minimized. 4 | Suppose the K packets have (x1, x2, x3,....xk) candies in them, where xi denotes the number of candies in the ith packet, then we define unfairness as 5 | unfairness=0; 6 | for(i=0;i 43 | 44 | using namespace std; 45 | 46 | long go(vector candies, long n, long k){ 47 | //size is n+1 48 | 49 | sort(candies.begin(), candies.end()); 50 | 51 | long sum = 0; 52 | long buffer = 0; 53 | for (long i = 1; i <=k; ++i) 54 | { 55 | sum += i*candies[i]; 56 | sum -= (k-i+1)*candies[i]; 57 | 58 | buffer += candies[i]; 59 | } 60 | 61 | 62 | long ans = sum; 63 | for (long i = 2; i <= n-k+1; ++i) 64 | { 65 | sum = sum - 2*(buffer - candies[i-1])+(k-1)*candies[i-1]+(k-1)*candies[i+k-1]; 66 | 67 | buffer = buffer - candies[i-1]+candies[i+k-1]; 68 | 69 | 70 | ans = min(ans, sum); 71 | } 72 | 73 | return ans; 74 | } 75 | 76 | int main( int argc , char ** argv ) 77 | { 78 | ios_base::sync_with_stdio(false) ; 79 | cin.tie(NULL) ; 80 | 81 | long n, k; 82 | cin>>n>>k; 83 | 84 | vector candies(n+1, 0); 85 | for (int i = 1; i <= n; ++i) 86 | { 87 | cin>>candies[i]; 88 | } 89 | 90 | cout << go(candies, n, k) << '\n'; 91 | 92 | return 0 ; 93 | 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/Boredom.cpp: -------------------------------------------------------------------------------- 1 | Boredom 2 | Send Feedback 3 | Gary is bored and wants to play an interesting but tough game . So he figured out a new board game called "destroy the neighbours" . In this game there are N integers on a board. In one move, he can pick any integer x from the board and then all the integers with value x+1 or x-1 gets destroyed .This move will give him x points. 4 | He plays the game until the board becomes empty . But as he want show this game to his friend Steven, he wants to learn techniques to maximise the points to show off . Can you help Gary in finding out the maximum points he receive grab from the game ? 5 | Input Format : 6 | Line 1 : Integer N 7 | Line 2 : A list of N integers 8 | Output Format : 9 | Maximum points Gary can recieve from the Game setup 10 | Constraints : 11 | 1<=N<=10^5 12 | 1<=A[i]<=1000 13 | Sample Input : 14 | 2 15 | 1 2 16 | Sample Output : 17 | 2 18 | 19 | 20 | /******************************************************************** SOLUTION ***************************************************************************/ 21 | 22 | 23 | #include 24 | #include 25 | using namespace std; 26 | 27 | int freq[1002],dp[1002]; 28 | int solve(int n,vectorA){ 29 | 30 | for(int i=0;i= 0)? table[i - S[j]][j]: 0; 54 | 55 | // Count of solutions excluding S[j] 56 | 57 | y = (j >= 1)? table[i][j-1]: 0; 58 | 59 | // total count 60 | table[i][j] = x + y; 61 | } 62 | } 63 | 64 | return table[n][m-1]; 65 | 66 | } 67 | 68 | 69 | 70 | /* 71 | #include 72 | using namespace std; 73 | 74 | int coin_change_naive(int n, int *d,int numD,int **output) 75 | { 76 | if(n == 0) 77 | { 78 | return 1; 79 | } 80 | if(numD == 0) 81 | { 82 | return 0; 83 | } 84 | if(n < 0) 85 | { 86 | return 0; 87 | } 88 | if(output[n][numD] > -1) 89 | { 90 | return output[n][numD]; 91 | } 92 | int first = coin_change_naive(n - d[0],d,numD,output); 93 | int second = coin_change_naive(n,d + 1,numD - 1,output); 94 | output[n][numD] = first + second; 95 | return output[n][numD]; 96 | } 97 | int countWaysToMakeChange(int denominations[], int numDenominations, int value){ 98 | 99 | int **output = new int*[value+1]; 100 | for(int i = 0; i < value+1 ; i++) 101 | { 102 | output[i] = new int[numDenominations+1]; 103 | for(int j = 0; j < numDenominations+1; j++) 104 | output[i][j] = -1; 105 | } 106 | return coin_change_naive(value,denominations,numDenominations,output); 107 | 108 | 109 | } 110 | */ 111 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/CountBSTs.cpp: -------------------------------------------------------------------------------- 1 | Count BSTs 2 | Send Feedback 3 | Given an integer N, find and return the count of unique Binary search trees (BSTs) are possible with nodes valued from 1 to N. 4 | Output count can be very large, so return the count modulo 10^9+7. 5 | Input Format : 6 | Integer n 7 | Output Format : 8 | Count of BSTs 9 | Contraints : 10 | 1<= N <=1000 11 | Sample Input 1: 12 | 8 13 | Sample Output 1: 14 | 1430 15 | Sample Input 2: 16 | 3 17 | Sample Output 2: 18 | 5 19 | 20 | 21 | /******************************************************************** SOLUTION ***************************************************************************/ 22 | 23 | 24 | 25 | #include 26 | 27 | using namespace std; 28 | 29 | #define m 1000000007 30 | long long count_trees(int n, int *temp=new int [1001]()) 31 | { 32 | if(n==1||n==0) 33 | { 34 | return 1; 35 | } 36 | if(temp[n]>0) 37 | { 38 | return temp[n]; 39 | } 40 | long long count=0; 41 | for(int i=1; i<=n; i++) 42 | { 43 | long long left=count_trees(i-1, temp)%m; 44 | temp[i-1]=left; 45 | long long right=count_trees(n-i, temp)%m; 46 | temp[n-i]=right; 47 | count+= (left*right)%m; 48 | } 49 | temp[n]=count; 50 | return count; 51 | } 52 | int countBST( int n) 53 | { 54 | /* Don't write main(). 55 | * Don't read input, it is passed as function argument. 56 | * Return output and don't print it. 57 | * Taking input and printing output is handled automatically. 58 | */ 59 | 60 | int a= count_trees(n)%m; 61 | return a; 62 | } 63 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/LargestBitonicSubarray.cpp: -------------------------------------------------------------------------------- 1 | Largest Bitonic Subarray 2 | Send Feedback 3 | You are given an array of positive integers as input. Write a code to return the length of the largest such subsequence in which the values are arranged first in strictly ascending order and then in strictly descending order. 4 | Such a subsequence is known as bitonic subsequence. A purely increasing or purely decreasing subsequence will also be considered as a bitonic sequence with the other part empty. 5 | Note that the elements in bitonic subsequence need not be consecutive in the given array but the order should remain same. 6 | Input Format: 7 | Line 1 : A positive Integer N, i.e., the size of array 8 | Line 2 : N space-separated integers as elements of the array 9 | Output Format: 10 | Length of Largest Bitonic subsequence 11 | Input Constraints: 12 | 1<= N <= 100000 13 | Sample Input 1: 14 | 6 15 | 15 20 20 6 4 2 16 | Sample Output 1: 17 | 5 18 | Sample Output 1 Explanation: 19 | Here, longest Bitonic subsequence is {15, 20, 6, 4, 2} which has length = 5. 20 | Sample Input 2: 21 | 2 22 | 1 5 23 | Sample Output 2: 24 | 2 25 | Sample Input 3: 26 | 2 27 | 5 1 28 | Sample Output 3: 29 | 2 30 | 31 | 32 | /******************************************************************** SOLUTION ***************************************************************************/ 33 | 34 | 35 | #include 36 | 37 | using namespace std; 38 | int longestBitonicSubarray(int *arr, int n) { 39 | 40 | int i, j; 41 | 42 | /* Allocate memory for LIS[] and initialize LIS values as 1 for 43 | all indexes */ 44 | int *lis = new int[n]; 45 | for (i = 0; i < n; i++) 46 | lis[i] = 1; 47 | 48 | /* Compute LIS values from left to right */ 49 | for (i = 1; i < n; i++) 50 | for (j = 0; j < i; j++) 51 | if (arr[i] > arr[j] && lis[i] < lis[j] + 1) 52 | lis[i] = lis[j] + 1; 53 | 54 | /* Allocate memory for lds and initialize LDS values for 55 | all indexes */ 56 | int *lds = new int [n]; 57 | for (i = 0; i < n; i++) 58 | lds[i] = 1; 59 | 60 | /* Compute LDS values from right to left */ 61 | for (i = n-2; i >= 0; i--) 62 | for (j = n-1; j > i; j--) 63 | if (arr[i] > arr[j] && lds[i] < lds[j] + 1) 64 | lds[i] = lds[j] + 1; 65 | 66 | 67 | /* Return the maximum value of lis[i] + lds[i] - 1*/ 68 | int max = lis[0] + lds[0] - 1; 69 | for (i = 1; i < n; i++) 70 | if (lis[i] + lds[i] - 1 > max) 71 | max = lis[i] + lds[i] - 1; 72 | return max; 73 | } 74 | 75 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/LootHouses.cpp: -------------------------------------------------------------------------------- 1 | Loot Houses 2 | Send Feedback 3 | A thief wants to loot houses. He knows the amount of money in each house. He cannot loot two consecutive houses. Find the maximum amount of money he can loot. 4 | Input Format 5 | Line 1 : An integer N 6 | Line 2 : N spaced integers denoting money in each house 7 | Output Format 8 | Line 1 : Maximum amount of money looted 9 | Input Constraints 10 | 1 <= n <= 10^4 11 | 1 <= A[i] < 10^4 12 | Sample Input : 13 | 6 14 | 5 5 10 100 10 5 15 | Sample Output 1 : 16 | 110 17 | 18 | 19 | /******************************************************************** SOLUTION ***************************************************************************/ 20 | 21 | 22 | #include 23 | using namespace std; 24 | 25 | int getMaxMoney(int hval[], int n){ 26 | if (n == 0) 27 | return 0; 28 | if (n == 1) 29 | return hval[0]; 30 | if (n == 2) 31 | return max(hval[0], hval[1]); 32 | 33 | // dp[i] represent the maximum value stolen 34 | // so far after reaching house i. 35 | long dp[n]; 36 | 37 | // Initialize the dp[0] and dp[1] 38 | dp[0] = hval[0]; 39 | dp[1] = max(hval[0], hval[1]); 40 | 41 | // Fill remaining positions 42 | for (int i = 2; i 22 | using namespace std; 23 | int findMaxSquareWithAllZeros(int** arr, int row, int col){ 24 | int **dp = new int *[row]; 25 | for(int i = 0; i < row; i++){ 26 | dp[i] = new int[col]; 27 | } 28 | 29 | for(int i = 0; i < row; i++){ 30 | dp[i][0] = arr[i][0] == 1 ? 0 : 1; 31 | } 32 | 33 | for(int j = 1; j < col; j++){ 34 | dp[0][j] = arr[0][j] == 1 ? 0 : 1; 35 | } 36 | 37 | for(int i = 1; i < row; i++){ 38 | for(int j = 1; j < col; j++){ 39 | if(arr[i][j] == 0){ 40 | dp[i][j] = min(dp[i-1][j], min(dp[i-1][j-1], dp[i][j-1]))+1; 41 | } 42 | else dp[i][j] = 0; 43 | } 44 | } 45 | 46 | int max = 0; 47 | for(int i = 0; i < row; i++){ 48 | for(int j = 0; j < col; j++){ 49 | if(dp[i][j] > max) max = dp[i][j]; 50 | } 51 | } 52 | 53 | return max; 54 | } 55 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/MinimumCount.cpp: -------------------------------------------------------------------------------- 1 | Minimum Count 2 | Send Feedback 3 | Given an integer N, find and return the count of minimum numbers, sum of whose squares is equal to N. 4 | That is, if N is 4, then we can represent it as : {1^2 + 1^2 + 1^2 + 1^2} and {2^2}. Output will be 1, as 1 is the minimum count of numbers required. 5 | Note : x^y represents x raise to the power y. 6 | Input Format : 7 | Integer N 8 | Output Format : 9 | Required minimum count 10 | Constraints : 11 | 1 <= N <= 1000 12 | Sample Input 1 : 13 | 12 14 | Sample Output 1 : 15 | 3 16 | Sample Output 1 Explanation : 17 | 12 can be represented as : 18 | 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 19 | 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 2^2 20 | 1^1 + 1^1 + 1^1 + 1^1 + 2^2 + 2^2 21 | 2^2 + 2^2 + 2^2 22 | As we can see, the output should be 3. 23 | Sample Input 2 : 24 | 9 25 | Sample Output 2 : 26 | 1 27 | 28 | 29 | /******************************************************************** SOLUTION ***************************************************************************/ 30 | 31 | 32 | #include 33 | 34 | using namespace std; 35 | 36 | int minCount(int n){ 37 | //non Recursive solution 38 | 39 | std::vector dp(n+1, 0); 40 | dp[0] = 0; 41 | dp[1] = 1; 42 | for (int i = 1; i <= n; ++i) 43 | { 44 | int count = INT_MAX; 45 | for (int j = 1; j <= i; ++j) 46 | { 47 | if (i-j*j<0) 48 | { 49 | break; 50 | } 51 | 52 | count = min(count, dp[i-j*j]); 53 | } 54 | dp[i] = 1+count; 55 | } 56 | 57 | return dp[n]; 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/MinimumNumberofChocolates.cpp: -------------------------------------------------------------------------------- 1 | Minimum Number of Chocolates 2 | Send Feedback 3 | Noor is a teacher. She wants to give some chocolates to the students in her class. All the students sit in a line and each of them has a score according to performance. Noor wants to give at least 1 chocolate to each student. She distributes chocolates to them such that If two students sit next to each other then the one with the higher score must get more chocolates. Noor wants to save money, so she wants to minimise the total number of chocolates. 4 | Note that when two students have equal score they are allowed to have different number of chocolates. 5 | Input Format: 6 | First Line: Integer N, the number of students in Noor’s class. 7 | Second Line: Each of the student's score separated by spaces. 8 | Output Format: 9 | Output a single line containing the minimum number of chocolates Noor must give. 10 | Input Constraints 11 | 1 <= N <= 100000 12 | 1 <= score <= 100000 13 | Sample Input: 14 | 4 15 | 1 4 4 6 16 | sample Output: 17 | 6 18 | Sample Input: 19 | 3 20 | 8 7 5 21 | sample Output: 22 | 6 23 | 24 | 25 | /******************************************************************** SOLUTION ***************************************************************************/ 26 | 27 | 28 | int getMin(int *arr, int n){ 29 | int *dp = new int[n+1]; 30 | 31 | dp[0] = 1; 32 | 33 | int i = 0; 34 | 35 | int sum = 0; 36 | 37 | for(i = 1; i < n; i++){ 38 | 39 | if(arr[i] > arr[i-1]) { 40 | 41 | dp[i] = dp[i-1]+1; 42 | 43 | } 44 | 45 | else 46 | dp[i] = 1; 47 | 48 | } 49 | 50 | for(i = n-2; i >= 0; i--){ 51 | 52 | if(arr[i] > arr[i+1] && dp[i] <= dp[i+1]){ 53 | 54 | dp[i] = dp[i+1]+1; 55 | 56 | } 57 | } 58 | 59 | for(i = 0; i < n; i++) 60 | 61 | sum += dp[i]; 62 | 63 | delete []dp; 64 | 65 | return sum; 66 | 67 | } 68 | 69 | 70 | /* 71 | 72 | #include 73 | 74 | using namespace std; 75 | 76 | int getMin(int *arr, int n){ 77 | std::vector dp(n, 0); 78 | dp[0] = 1; 79 | for (int i = 1; i < n; ++i) 80 | { 81 | if(arr[i]>arr[i-1]) 82 | dp[i] = dp[i-1]+1; 83 | else 84 | dp[i] = 1; // made changes here 85 | } 86 | 87 | 88 | dp[n-1] = max(dp[n-1], 1); 89 | 90 | for (int i = n-2; i >= 0; --i) 91 | { 92 | if(arr[i+1] 49 | 50 | using namespace std; 51 | 52 | 53 | int main( int argc , char ** argv ) 54 | { 55 | ios_base::sync_with_stdio(false) ; 56 | cin.tie(NULL) ; 57 | 58 | int n, m; 59 | cin>>n>>m; 60 | vector s(n+1, 0); 61 | vector e(n+1, 0); 62 | 63 | vector buffer(n+1, 0); 64 | 65 | 66 | for (int i = 0; i < m; ++i) 67 | { 68 | int a, b; 69 | cin>>a>>b; 70 | 71 | s[a]++; 72 | e[b]++; 73 | } 74 | 75 | for (int i = 1; i < n+1; ++i) 76 | { 77 | buffer[i] = s[i] - e[i-1] + buffer[i-1]; 78 | } 79 | 80 | //Will store ki i coins kitne boxes me hai 81 | vector coins(n+1,0); 82 | for (int i = 1; i < n+1; ++i) 83 | { 84 | coins[buffer[i]]++; 85 | } 86 | 87 | for (int i = n-1; i >= 0; --i) 88 | { 89 | coins[i] += coins[i+1]; 90 | } 91 | 92 | int q; 93 | cin>>q; 94 | 95 | for (int i = 0; i < q; ++i) 96 | { 97 | int temp; 98 | cin>>temp; 99 | cout << coins[temp] << '\n'; 100 | } 101 | 102 | 103 | 104 | return 0 ; 105 | 106 | 107 | 108 | } 109 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/StairCaseProblem.cpp: -------------------------------------------------------------------------------- 1 | StairCase Problem 2 | Send Feedback 3 | A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return all possible number of ways. 4 | Time complexity of your code should be O(n). 5 | Input format : 6 | Integer n (No. of steps) 7 | Constraints : 8 | n <= 70 9 | Sample Input 1: 10 | 4 11 | Sample Output 1: 12 | 7 13 | 14 | 15 | /******************************************************************** SOLUTION ***************************************************************************/ 16 | 17 | 18 | long staircase(int n){ 19 | long dp[n + 1]; 20 | dp[0] = 1; 21 | dp[1] = 1; 22 | dp[2] = 2; 23 | for (int i = 3; i <= n; i++) 24 | dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; 25 | 26 | return dp[n]; 27 | } 28 | -------------------------------------------------------------------------------- /Dynamic Programming - 1/VanyaAndGCD.cpp: -------------------------------------------------------------------------------- 1 | Vanya and GCD 2 | Send Feedback 3 | Vanya has been studying all day long about sequences and other Complex Mathematical Terms. She thinks she has now become really good at it. So, her friend Vasya decides to test her knowledge and keeps the following challenge it front of her: 4 | Vanya has been given an integer array A of size N. Now, she needs to find the number of increasing sub-sequences of this array with length ≥1 and GCD=1. A sub-sequence of an array is obtained by deleting some (or none) elements and maintaining the relative order of the rest of the elements. As the answer may be large, print it Modulo 109+7 5 | She finds this task really easy, and thinks that you can do it too. Can you? 6 | Input Format: 7 | The first line contains a single integer N denoting size of array A. The next line contains N space separated integers denoting the elements of array A 8 | Output Format: 9 | Print the required answer Modulo 10^9+7 on a single line. 10 | Constraints: 11 | 1≤N≤500 12 | 13 | 1≤A[i]≤100 14 | Sample Input 15 | 3 16 | 1 2 3 17 | Sample Output 18 | 5 19 | 20 | 21 | /******************************************************************** SOLUTION ***************************************************************************/ 22 | 23 | 24 | #include 25 | 26 | using namespace std; 27 | int go(vector v){ 28 | int n = v.size(); 29 | vector> dp(101, vector(n, 0)); 30 | 31 | for (int i = 0; i < n; ++i) 32 | { 33 | dp[v[i]][i] = 1; 34 | } 35 | 36 | for (int i = 0; i < n; ++i) 37 | { 38 | for (int j = 0; j < i; ++j) 39 | { 40 | if (v[i]>v[j]) 41 | { 42 | for (int k = 1; k < 101; ++k) 43 | { 44 | int gcn = __gcd(k, v[i]); 45 | dp[gcn][i] = (dp[gcn][i]+dp[k][j])%1000000007; 46 | } 47 | } 48 | } 49 | } 50 | 51 | int ans = 0; 52 | 53 | // for (int i = 1; i < 101; ++i) 54 | // { 55 | // for (int j = 0; j < n; ++j) 56 | // { 57 | // cout<>n; 82 | vector v(n, 0); 83 | 84 | for (int i = 0; i < n; ++i) 85 | { 86 | cin>>v[i]; 87 | } 88 | 89 | cout << go(v) << '\n'; 90 | 91 | 92 | 93 | return 0 ; 94 | 95 | 96 | 97 | } 98 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/CharlieAndPilots.cpp: -------------------------------------------------------------------------------- 1 | Charlie and Pilots 2 | Send Feedback 3 | Charlie acquired airline transport company and to stay in business he needs to lower the expenses by any means possible. There are N pilots working for his company (N is even) and N/2 plane crews needs to be made. A plane crew consists of two pilots - a captain and his assistant. A captain must be older than his assistant. Each pilot has a contract granting him two possible salaries - one as a captain and the other as an assistant. A captain's salary is larger than assistant's for the same pilot. However, it is possible that an assistant has larger salary than his captain. Write a program that will compute the minimal amount of money Charlie needs to give for the pilots' salaries if he decides to spend some time to make the optimal (i.e. the cheapest) arrangement of pilots in crews. 4 | Input 5 | The first line of input contains integer N, 2 ≤ N ≤ 10,000, N is even, the number of pilots working for the Charlie's company. The next N lines of input contain pilots' salaries. The lines are sorted by pilot's age, the salaries of the youngest pilot are given the first. Each of those N lines contains two integers separated by a space character, X i Y, 1 ≤ Y < X ≤ 100,000, a salary as a captain (X) and a salary as an assistant (Y). 6 | Output 7 | The first and only line of output should contain the minimal amount of money Charlie needs to give for the pilots' salaries. 8 | Sample Input 9 | 4 10 | 5000 3000 11 | 6000 2000 12 | 8000 1000 13 | 9000 6000 14 | Sample Output 15 | 19000 16 | 17 | 18 | 19 | /******************************************************************** SOLUTION ***************************************************************************/ 20 | 21 | 22 | 23 | #include 24 | using namespace std; 25 | 26 | int minSalary(int *assistant, int *captain, int n, int x, int **memo){ 27 | if(n == 0) return 0; 28 | 29 | if(memo[n][x] != -1) return memo[n][x]; 30 | 31 | if(x == 0){ 32 | int answer = assistant[0]+minSalary(assistant+1, captain+1, n-1, x+1, memo); 33 | memo[n][x] = answer; 34 | return answer; 35 | } 36 | else if(x == n){ 37 | int answer = captain[0]+minSalary(assistant+1, captain+1, n-1, x-1, memo); 38 | memo[n][x] = answer; 39 | return answer; 40 | } 41 | else{ 42 | int a = assistant[0]+minSalary(assistant+1, captain+1, n-1, x+1, memo); 43 | int b = captain[0]+minSalary(assistant+1, captain+1, n-1, x-1, memo); 44 | int answer = min(a, b); 45 | memo[n][x] = answer; 46 | return answer; 47 | } 48 | } 49 | 50 | int main(){ 51 | int n; 52 | cin >> n; 53 | 54 | int *captain = new int[n]; 55 | int *assistant = new int[n]; 56 | for(int i = 0; i < n; i++){ 57 | cin >> captain[i] >> assistant[i]; 58 | } 59 | 60 | int **memo = new int *[n+1]; 61 | for(int i = 0; i <= n; i++){ 62 | memo[i] = new int[(n/2)+1]; 63 | for(int j = 0; j <= n/2; j++) memo[i][j] = -1; 64 | } 65 | 66 | cout << minSalary(assistant, captain, n, 0, memo) << endl; 67 | } 68 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/DistinctSubsequences.cpp: -------------------------------------------------------------------------------- 1 | Distinct Subsequences 2 | Send Feedback 3 | Given a string, count the number of distinct subsequences of it ( including empty subsequence ). For the uninformed, A subsequence of a string is a new string which is formed from the original string by deleting some of the characters without disturbing the relative positions of the remaining characters. 4 | For example, "AGH" is a subsequence of "ABCDEFGH" while "AHG" is not. 5 | Input 6 | First line of input contains an integer T which is equal to the number of test cases. You are required to process all test cases. Each of next T lines contains a string s. 7 | Output 8 | Output consists of T lines. Ith line in the output corresponds to the number of distinct subsequences of ith input string. Since, this number could be very large, you need to output ans%1000000007 where ans is the number of distinct subsequences. 9 | Constraints and Limits 10 | T ≤ 100, length(S) ≤ 100000 11 | 12 | All input strings shall contain only uppercase letters. 13 | Sample Input 14 | 3 15 | AAA 16 | ABCDEFG 17 | CODECRAFT 18 | Sample Output 19 | 4 20 | 128 21 | 496 22 | 23 | 24 | 25 | /******************************************************************** SOLUTION ***************************************************************************/ 26 | 27 | 28 | 29 | #include 30 | using namespace std; 31 | #define MOD 1000000007 32 | 33 | int main(){ 34 | int t; 35 | cin >> t; 36 | while(t--){ 37 | string s; 38 | cin >> s; 39 | int n = s.length(); 40 | 41 | int *occurence = new int[256]; 42 | for(int i = 0; i < 256; i++) occurence[i] = -1; 43 | 44 | int *dp = new int[n+1]; 45 | dp[0] = 1; 46 | for(int i = 1; i <= n; i++){ 47 | dp[i] = (2*dp[i-1])%MOD; 48 | if(occurence[s[i-1]] != -1){ 49 | dp[i] = (dp[i]-dp[occurence[s[i-1]]]+MOD)%MOD; 50 | } 51 | occurence[s[i-1]] = i-1; 52 | } 53 | 54 | cout << dp[n] << endl; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/EditDistance.cpp: -------------------------------------------------------------------------------- 1 | Edit Distance - Problem 2 | Send Feedback 3 | Given two strings s and t of lengths m and n respectively, find the Edit Distance between the strings. Edit Distance of two strings is minimum number of steps required to make one string equal to other. In order to do so you can perform following three operations only : 4 | 1. Delete a character 5 | 6 | 2. Replace a character with another one 7 | 8 | 3. Insert a character 9 | Note - Strings don't contain spaces 10 | Input Format : 11 | Line 1 : String s 12 | Line 2 : String t 13 | Output Format : 14 | Line 1 : Edit Distance value 15 | Constraints 16 | 1<= m,n <= 20 17 | Sample Input 1 : 18 | abc 19 | dc 20 | Sample Output 1 : 21 | 2 22 | 23 | 24 | 25 | /******************************************************************** SOLUTION ***************************************************************************/ 26 | 27 | 28 | #include 29 | #include 30 | using namespace std; 31 | #include 32 | int editDistance(string s1, string s2){ 33 | int m = s1.size(); 34 | int n = s2.size(); 35 | 36 | vector>dp(m+1, vector(n+1, 0)); 37 | 38 | for (int i = 0; i < m+1; ++i) 39 | { 40 | dp[i][n] = m-i; 41 | } 42 | 43 | 44 | for (int i = 0; i < n+1; ++i) 45 | { 46 | dp[m][i] = n-i; 47 | } 48 | 49 | //dp[m][n] = 0; 50 | 51 | for (int i = m-1; i >= 0; --i) 52 | { 53 | for (int j = n-1; j >= 0; --j) 54 | { 55 | if(s1[i]==s2[j]){ 56 | dp[i][j] = dp[i+1][j+1]; 57 | }else{ 58 | 59 | dp[i][j] = min(1+dp[i+1][j+1], min(1+dp[i+1][j], 1+dp[i][j+1])); 60 | } 61 | } 62 | } 63 | return dp[0][0]; 64 | 65 | } 66 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/Knapsnack.cpp: -------------------------------------------------------------------------------- 1 | Knapsnack - Problem 2 | Send Feedback 3 | A thief robbing a store and can carry a maximal weight of W into his knapsack. There are N items and ith item weigh wi and is of value vi. What is the maximum value V, that thief can take ? 4 | Space complexity should be O(W). 5 | Input Format : 6 | Line 1 : N i.e. number of items 7 | Line 2 : N Integers i.e. weights of items separated by space 8 | Line 3 : N Integers i.e. values of items separated by space 9 | Line 4 : Integer W i.e. maximum weight thief can carry 10 | Output Format : 11 | Line 1 : Maximum value V 12 | Constraints 13 | 1 <= N <= 10^4 14 | 1<= wi <= 100 15 | 1 <= vi <= 100 16 | Sample Input 1 : 17 | 4 18 | 1 2 4 5 19 | 5 4 8 6 20 | 5 21 | Sample Output : 22 | 13 23 | 24 | 25 | /******************************************************************** SOLUTION ***************************************************************************/ 26 | 27 | 28 | #include 29 | using namespace std; 30 | 31 | int knapsack(int *weights,int *values,int n,int maxWeight) 32 | { 33 | int *dp[2]; 34 | dp[0] = new int[maxWeight+1]; 35 | dp[1] = new int[maxWeight+1]; 36 | for(int i = 0; i <= maxWeight ; i++) 37 | { 38 | dp[0][i] = 0; 39 | } 40 | dp[1][0] = 0; 41 | bool k = 1; 42 | int w; 43 | for(int i = 1; i <= n ; i++ , k=!k) 44 | { 45 | w = 0; 46 | while(w < weights[i-1]) 47 | { 48 | dp[k][w] = dp[!k][w]; 49 | w++; 50 | } 51 | while(w <= maxWeight){ 52 | dp[k][w] = max(dp[!k][w],values[i-1] + dp[!k][w-weights[i-1]]); 53 | w++; 54 | } 55 | } 56 | return dp[!k][maxWeight]; 57 | } 58 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/LCS.cpp: -------------------------------------------------------------------------------- 1 | LCS - Problem 2 | Send Feedback 3 | Given 2 strings of S1 and S2 with lengths m and n respectively, find the length of longest common subsequence. 4 | A subsequence of a string S whose length is n, is a string containing characters in same relative order as they are present in S, but not necessarily contiguous. Subsequences contain all the strings of length varying from 0 to n. E.g. subsequences of string "abc" are - "",a,b,c,ab,bc,ac,abc. 5 | Input Format : 6 | Line 1 : String S1 7 | Line 2 : String s2 8 | Output Format : 9 | Line 1 : Length of lcs 10 | Sample Input : 11 | adebc 12 | dcadb 13 | Sample Output : 14 | 3 15 | 16 | 17 | /******************************************************************** SOLUTION ***************************************************************************/ 18 | 19 | 20 | #include 21 | #include 22 | using namespace std; 23 | int lcs(string s, string t){ 24 | int m = s.size(); 25 | int n = t.size(); 26 | int **ans = new int*[m+1]; 27 | for(int i = 0; i <= m; i++) { 28 | ans[i] = new int[n+1]; 29 | } 30 | // First row 31 | for(int j = 0; j <= n; j++) { 32 | ans[0][j] = 0; 33 | } 34 | // First col 35 | for(int i = 0; i <= m; i++) { 36 | ans[i][0] = 0; 37 | } 38 | for(int i = 1; i <= m; i++) { 39 | for(int j = 1; j <= n; j++) { 40 | if(s[m-i] == t[n-j]) { 41 | ans[i][j] = 1 + ans[i-1][j-1]; 42 | } 43 | else { 44 | ans[i][j] = max(ans[i-1][j], ans[i][j-1]); 45 | } 46 | } 47 | } 48 | return ans[m][n]; 49 | } 50 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/MiserMan.cpp: -------------------------------------------------------------------------------- 1 | Miser Man 2 | Send Feedback 3 | Jack is a wise and miser man. Always tries to save his money. 4 | One day, he wants to go from city A to city B. Between A and B, there are N number of cities(including B and excluding A) and in each city there are M buses numbered from 1 to M. And the fare of each bus is different. Means for all N*M busses, fare (K) may be different or same. Now Jack has to go from city A to city B following these conditions: 5 | 1. At every city, he has to change the bus. 6 | 2. And he can switch to only those buses which have number either equal or 1 less or 1 greater to the previous. 7 | You are to help Jack to go from A to B by spending the minimum amount of money. 8 | N, M, K <= 100. 9 | Input 10 | Line 1: N M 11 | 12 | Line 2: NxM Grid 13 | 14 | Each row lists the fares the M busses to go form the current city to the next city. 15 | Output 16 | Single Line containing the minimum amount of fare that Jack has to give. 17 | Sample Input 18 | 5 5 19 | 1 3 1 2 6 20 | 10 2 5 4 15 21 | 10 9 6 7 1 22 | 2 7 1 5 3 23 | 8 2 6 1 9 24 | Sample Output 25 | 10 26 | 27 | 28 | 29 | /******************************************************************** SOLUTION ***************************************************************************/ 30 | 31 | 32 | 33 | #include 34 | using namespace std; 35 | 36 | int findFare(int **input, int n, int m, int row, int col, int **dp){ 37 | if(row == n) return 0; 38 | 39 | if(dp[row][col] != -1) return dp[row][col]; 40 | 41 | int a = INT_MAX, b = INT_MAX, c = INT_MAX; 42 | if(col-1 >= 0) a = input[row][col]+findFare(input, n, m, row+1, col-1, dp); 43 | b = input[row][col]+findFare(input, n, m, row+1, col, dp); 44 | if(col+1 < m) c = input[row][col]+findFare(input, n, m, row+1, col+1, dp); 45 | 46 | dp[row][col] = min(a, min(b, c)); 47 | return min(a, min(b, c)); 48 | } 49 | 50 | int main(){ 51 | int n, m; 52 | cin >> n >> m; 53 | 54 | int **input = new int *[n]; 55 | for(int i = 0; i < n; i++){ 56 | input[i] = new int[m]; 57 | for(int j = 0; j < m; j++) cin >> input[i][j]; 58 | } 59 | 60 | int **dp = new int *[n]; 61 | for(int i = 0; i < n; i++) dp[i] = new int[m]; 62 | 63 | int minFare = INT_MAX; 64 | for(int i = 0; i < m; i++){ 65 | for(int j = 0; j < n; j++){ 66 | for(int k = 0; k < m; k++) dp[j][k] = -1; 67 | } 68 | 69 | minFare = min(minFare, findFare(input, n, m, 0, i, dp)); 70 | } 71 | 72 | cout << minFare << endl; 73 | } 74 | 75 | 76 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/ShortestSubsequence.cpp: -------------------------------------------------------------------------------- 1 | Shortest Subsequence 2 | Send Feedback 3 | Gary has two string S and V. Now Gary wants to know the length shortest subsequence in S such that it is not a subsequence in V. 4 | Note: input data will be such so there will always be a solution. 5 | Input Format : 6 | Line 1 : String S of length N (1 <= N <= 1000) 7 | Line 2 : String V of length M (1 <= M <= 1000) 8 | Output Format : 9 | Length of shortest subsequence in S such that it is not a subsequence in V 10 | Sample Input : 11 | babab 12 | babba 13 | Sample Output : 14 | 3 15 | 16 | 17 | /******************************************************************** SOLUTION ***************************************************************************/ 18 | 19 | 20 | 21 | #include 22 | 23 | using namespace std; 24 | int solve(string s1,string s2) 25 | { 26 | int m =s1.size(); 27 | int n =s2.size(); 28 | 29 | vector> dp(m+1, vector(n+1, 0)); 30 | 31 | for (int i = 0; i < n+1; ++i) 32 | { 33 | dp[m][i] = n-i; 34 | } 35 | 36 | for (int i = 0; i < m+1; ++i) 37 | { 38 | dp[i][n] = m-i; 39 | } 40 | 41 | for (int i = m-1; i >= 0; --i) 42 | { 43 | for (int j = n-1; j >= 0; --j) 44 | { 45 | int k = j; 46 | 47 | while(k 28 | 29 | using namespace std; 30 | 31 | int go(string s1, string s2, int i, int j, int** mem){ 32 | int m = s1.size(); 33 | int n = s2.size(); 34 | 35 | //cout << m<<" "< m-1) 38 | { 39 | return n-j; 40 | } 41 | 42 | if (j > n-1) 43 | { 44 | return m-i; 45 | } 46 | 47 | if (mem[i][j]!=-1) 48 | { 49 | return mem[i][j]; 50 | } 51 | 52 | if (s1[i] == s2[j]) 53 | { 54 | mem[i][j] = 1 + go(s1, s2, i+1, j+1, mem); 55 | return mem[i][j]; 56 | }else{ 57 | mem[i][j] = min(1+go(s1, s2, i+1, j, mem), 1+go(s1, s2, i, j+1, mem)); 58 | return mem[i][j]; 59 | } 60 | 61 | } 62 | int smallestSuperSequence(char str1[], int len1, char str2[], int len2) { 63 | string s1 = ""; 64 | string s2 = ""; 65 | 66 | for (int i = 0; i < len1; ++i) 67 | { 68 | s1 += str1[i]; 69 | } 70 | 71 | for (int i = 0; i < len2; ++i) 72 | { 73 | s2 += str2[i]; 74 | } 75 | 76 | int** mem = new int*[len1+1]; 77 | 78 | for (int i = 0; i < len1+1; ++i) 79 | { 80 | mem[i] = new int[len2+1]; 81 | for (int j = 0; j < len2+1; ++j) 82 | { 83 | mem[i][j] = -1; 84 | } 85 | } 86 | 87 | 88 | return go(s1, s2, 0, 0, mem); 89 | 90 | } 91 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/SquareBrackets.cpp: -------------------------------------------------------------------------------- 1 | Square Brackets 2 | Send Feedback 3 | You are given: 4 | a positive integer n, 5 | an integer k, 1<=k<=n, 6 | an increasing sequence of k integers 0 < s1 < s2 < ... < sk <= 2n. 7 | What is the number of proper bracket expressions of length 2n with opening brackets appearing in positions s1, s2,...,sk? 8 | Illustration 9 | Several proper bracket expressions: 10 | [[]][[[]][]] 11 | [[[][]]][][[]] 12 | An improper bracket expression: 13 | [[[][]]][]][[]] 14 | There is exactly one proper expression of length 8 with opening brackets in positions 2, 5 and 7. 15 | Task 16 | Write a program which for each data set from a sequence of several data sets: 17 | 1. reads integers n, k and an increasing sequence of k integers from input, 18 | 2. computes the number of proper bracket expressions of length 2n with opening brackets appearing at positions s1,s2,...,sk, 19 | 3. writes the result to output. 20 | Input 21 | The first line of the input file contains one integer d, 1 <= d <= 10, which is the number of data sets. The data sets follow. Each data set occupies two lines of the input file. The first line contains two integers n and k separated by single space, 1 <= n <= 19, 1 <= k <= n. The second line contains an increasing sequence of k integers from the interval [1;2n] separated by single spaces. 22 | Output 23 | The i-th line of output should contain one integer - the number of proper bracket expressions of length 2n with opening brackets appearing at positions s1, s2,...,sk. 24 | Sample Input 25 | 5 26 | 1 1 27 | 1 28 | 1 1 29 | 2 30 | 2 1 31 | 1 32 | 3 1 33 | 2 34 | 4 2 35 | 5 7 36 | Sample Output 37 | 1 38 | 0 39 | 2 40 | 3 41 | 2 42 | 43 | 44 | 45 | /******************************************************************** SOLUTION ***************************************************************************/ 46 | 47 | 48 | #include 49 | using namespace std; 50 | 51 | int squareBrackets(int id, int numOpen, int *input, int n, int **dp){ 52 | int numClose = id-numOpen; 53 | 54 | if(id == n){ 55 | if(numOpen == numClose) return 1; 56 | else return 0; 57 | } 58 | 59 | if(dp[id][numOpen] != -1) return dp[id][numOpen]; 60 | 61 | if(numOpen-numClose > n-id) return 0; 62 | if(numClose > numOpen) return 0; 63 | 64 | if(id == input[0]){ 65 | int answer = squareBrackets(id+1, numOpen+1, input+1, n, dp); 66 | dp[id][numOpen] = answer; 67 | return answer; 68 | } 69 | 70 | if(numOpen == numClose){ 71 | int answer = squareBrackets(id+1, numOpen+1, input, n, dp); 72 | dp[id][numOpen] = answer; 73 | return answer; 74 | } 75 | 76 | if(numOpen-numClose == n-id){ 77 | int answer = squareBrackets(id+1, numOpen, input, n, dp); 78 | dp[id][numOpen] = answer; 79 | return answer; 80 | } 81 | 82 | int a = squareBrackets(id+1, numOpen+1, input, n, dp); 83 | int b = squareBrackets(id+1, numOpen, input, n, dp); 84 | dp[id][numOpen] = a+b; 85 | return a+b; 86 | } 87 | 88 | int main(){ 89 | int d; 90 | cin >> d; 91 | while(d--){ 92 | int n, k; 93 | cin >> n >> k; 94 | 95 | int *input = new int[k]; 96 | int x; 97 | for(int i = 0; i < k; i++){ 98 | cin >> x; 99 | input[i] = x-1; 100 | } 101 | 102 | sort(input, input+k); 103 | int **dp = new int *[2*n+1]; 104 | for(int i = 0; i <= 2*n; i++){ 105 | dp[i] = new int[2*n+1]; 106 | for(int j = 0; j <= 2*n; j++) dp[i][j] = -1; 107 | } 108 | 109 | if(input[0] < 0 || input[k-1] >= 2*n){ 110 | cout << 0 << endl; 111 | continue; 112 | } 113 | 114 | cout << squareBrackets(0, 0, input, 2*n, dp) << endl; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/SubsetSum.cpp: -------------------------------------------------------------------------------- 1 | Subset Sum - Problem 2 | Send Feedback 3 | Given a set of n integers, find if a subset of sum k can be formed from the given set. Print Yes or No. 4 | 5 | Input Format 6 | First line contains a single integer n (1<=n<=1000) 7 | Second line contains n space separated integers (1<=a[i]<=1000) 8 | Last line contains a single positive integer k (1<=k<=1000) 9 | Output Format 10 | Output Yes if there exists a subset whose sum is k, else output No. 11 | Sample Input 12 | 3 13 | 1 2 3 14 | 4 15 | Sample Output 16 | Yes 17 | 18 | 19 | /******************************************************************** SOLUTION ***************************************************************************/ 20 | 21 | 22 | 23 | #include 24 | 25 | using namespace std; 26 | 27 | void go(vector arr, int n, int i , int sum){ 28 | vector> dp(n+1, vector(sum+1, 0)); 29 | 30 | for (int i = 0; i < n+1; ++i) 31 | { 32 | dp[i][0] = 1; 33 | } 34 | 35 | for (int i = 1; i < sum+1; ++i) 36 | { 37 | dp[n][i] = 0; 38 | } 39 | 40 | for (int j = 1; j < sum+1; ++j) 41 | { 42 | for (int i = n-1; i >= 0; --i) 43 | { 44 | bool c1 = 0; 45 | if (j-arr[i]>=0) 46 | { 47 | c1 = dp[i+1][j-arr[i]]; 48 | } 49 | 50 | if (c1 == 1) 51 | dp[i][j] = 1; 52 | else 53 | { 54 | dp[i][j] = dp[i+1][j]; 55 | 56 | } 57 | } 58 | } 59 | 60 | // for (int i = 0; i < n+1; ++i) 61 | // { 62 | // for (int j = 0; j < sum+1; ++j) 63 | // { 64 | // cout<>n; 88 | 89 | vector arr(n, 0); 90 | for (int i = 0; i < n; ++i) 91 | { 92 | cin>>arr[i]; 93 | } 94 | 95 | int sum; 96 | cin>>sum; 97 | 98 | go(arr, n, 0, sum); 99 | 100 | 101 | 102 | return 0 ; 103 | 104 | 105 | 106 | } 107 | -------------------------------------------------------------------------------- /Dynamic Programming - 2/TraderProfit.cpp: -------------------------------------------------------------------------------- 1 | Trader Profit 2 | Send Feedback 3 | Mike is a stock trader and makes a profit by buying and selling stocks. He buys a stock at a lower price and sells it at a higher price to book a profit. He has come to know the stock prices of a particular stock for n upcoming days in future and wants to calculate the maximum profit by doing the right transactions (single transaction = buying + selling). Can you help him maximize his profit? 4 | Note: A transaction starts after the previous transaction has ended. Two transactions can't overlap or run in parallel. 5 | The stock prices are given in the form of an array A for n days. 6 | Given the stock prices and a positive integer k, find and print the maximum profit Mike can make in at most k transactions. 7 | Input Format 8 | The first line of input contains an integer q denoting the number of queries. 9 | 10 | The first line of each test case contains a positive integer k, denoting the number of transactions. 11 | 12 | The second line of each test case contains a positive integer n, denoting the length of the array A. 13 | 14 | The third line of each test case contains n space-separated positive integers, denoting the prices of each day in the array A. 15 | Constraints 16 | 1<=q<=100 17 | 18 | 0 48 | using namespace std; 49 | typedef pair pii; 50 | #define f first 51 | #define s second 52 | 53 | int maxProfit(int *input, int id, int n, int k, bool buy, pii **memo){ 54 | if(k == 0 || id == n) return 0; 55 | 56 | if(buy){ 57 | if(memo[id][k].f != -1) return memo[id][k].f; 58 | } 59 | else{ 60 | if(memo[id][k].s != -1) return memo[id][k].s; 61 | } 62 | 63 | if(buy){ 64 | int a = maxProfit(input, id+1, n, k, false, memo)-input[id]; 65 | int b = maxProfit(input, id+1, n, k, true, memo); 66 | memo[id][k].f = max(a, b); 67 | return max(a, b); 68 | } 69 | else{ 70 | int a = input[id]+maxProfit(input, id+1, n, k-1, true, memo); 71 | int b = maxProfit(input, id+1, n, k, false, memo); 72 | memo[id][k].s = max(a, b); 73 | return max(a, b); 74 | } 75 | } 76 | 77 | int main(){ 78 | int q; 79 | cin >> q; 80 | while(q--){ 81 | int k, n; 82 | cin >> k >> n; 83 | 84 | int *input = new int[n]; 85 | for(int i = 0; i < n; i++) cin >> input[i]; 86 | 87 | pii **memo = new pii *[n+1]; 88 | for(int i = 0; i <= n; i++){ 89 | memo[i] = new pii[k+1]; 90 | for(int j = 0; j <= k; j++){ 91 | memo[i][j].f = -1; 92 | memo[i][j].s = -1; 93 | } 94 | } 95 | 96 | cout << maxProfit(input, 0, n, k, true, memo) << endl; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Graphs 1/3Cycle.cpp: -------------------------------------------------------------------------------- 1 | 3 Cycle 2 | Send Feedback 3 | Given a graph with N vertices (numbered from 1 to N) and Two Lists (U,V) of size M where (U[i],V[i]) and (V[i],U[i]) are connected by an edge , then count the distinct 3-cycles in the graph. A 3-cycle PQR is a cycle in which (P,Q), (Q,R) and (R,P) are connected an edge. 4 | Input Format : 5 | Line 1 : Two integers N and M 6 | Line 2 : List u of size of M 7 | Line 3 : List v of size of M 8 | Return Format : 9 | The count the number of 3-cycles in the given Graph 10 | Constraints : 11 | 1<=N<=100 12 | 1<=M<=(N*(N-1))/2 13 | 1<=u[i],v[i]<=N 14 | Sample Input: 15 | 3 3 16 | 1 2 3 17 | 2 3 1 18 | Sample Output: 19 | 1 20 | 21 | 22 | 23 | /*************************************************************** SOLUTION *******************************************************************************/ 24 | 25 | 26 | #include 27 | using namespace std; 28 | int helper(int i, int** matrix, int n, int* visited, int & count){ 29 | for(int j=1;ju,vectorv) 42 | { 43 | //Creating matrix 44 | int** matrix = new int*[n+1]; 45 | 46 | for(int i=0;i<=n;i++){ 47 | matrix[i] = new int[n+1]; 48 | 49 | for(int j=0;j<=n;j++){ 50 | matrix[i][j]=0; 51 | } 52 | 53 | } 54 | 55 | for(int i=0;i 38 | 39 | 40 | #include 41 | using namespace std; 42 | void connected(bool** edges, int n, int sv, int *visited) 43 | { 44 | int init=sv; 45 | 46 | while(init q; 53 | q.push(init); 54 | init++; 55 | vector v1; 56 | while(!q.empty()) 57 | { 58 | int x = q.front(); 59 | v1.push_back(x); 60 | 61 | q.pop(); 62 | 63 | for(int i=0;i> V >> E; 86 | 87 | bool** edges = new bool*[V]; 88 | for(int i=0; i>f; 98 | cin>>s; 99 | 100 | edges[f][s]=1; 101 | edges[s][f]=1; 102 | 103 | 104 | } 105 | 106 | int *visited = new int[V]; 107 | for(int i=0;i 33 | using namespace std; 34 | 35 | void BFS(int **graph,int n,int sv,int *visited) 36 | { 37 | queue que; 38 | que.push(sv); 39 | visited[sv] = 1; 40 | 41 | while(!que.empty()) 42 | { 43 | int v = que.front(); 44 | que.pop(); 45 | cout<> n >> e; 84 | 85 | int **graph = new int*[n]; 86 | for(int i = 0;i < n; i++) 87 | { 88 | graph[i] = new int[n]; 89 | for(int j = 0; j < n; j++) 90 | graph[i][j] = 0; 91 | } 92 | 93 | for(int i = 0; i < e; i++) 94 | { 95 | int f,s; 96 | cin >> f >> s; 97 | graph[f][s] = 1; 98 | graph[s][f] = 1; 99 | } 100 | 101 | bfs_disconnected(graph,n); 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /Graphs 1/ConnectingDots.cpp: -------------------------------------------------------------------------------- 1 | Connecting Dots 2 | Send Feedback 3 | Gary has a board of size NxM. Each cell in the board is a coloured dot. There exist only 26 colours denoted by uppercase Latin characters (i.e. A,B,...,Z). Now Gary is getting bore and wants to play a game. The key of this game is to find a cycle that contain dots of same colour. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: 4 | 1. These k dots are different: if i ≠ j then di is different from dj. 5 | 2. k is at least 4. 6 | 3. All dots belong to the same colour. 7 | 4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. 8 | Since Gary is colour blind, he wants your help. Your task is to determine if there exists a cycle on the board. 9 | Assume input to be 0-indexed based. 10 | Input Format : 11 | Line 1 : Two integers N and M, the number of rows and columns of the board 12 | Next N lines : a string consisting of M characters, expressing colors of dots in each line. Each character is an uppercase Latin letter. 13 | Output Format : 14 | Return 1 if there is a cycle else return 0 15 | Constraints : 16 | 2 ≤ N, M ≤ 50 17 | Sample Input : 18 | 3 4 19 | AAAA 20 | ABCA 21 | AAAA 22 | Sample Output : 23 | 1 24 | 25 | 26 | 27 | /*************************************************************** SOLUTION *******************************************************************************/ 28 | 29 | 30 | #include 31 | using namespace std; 32 | #define MAXN 51 33 | int moveX[4] = {-1, 0, 1, 0}; 34 | int moveY[4] = {0, -1, 0, 1}; 35 | bool isCyclePresent(char board[][MAXN], int n, int m, int sourceX, int sourceY, int x, int y, int count, bool **isVisited){ 36 | for(int i = 0; i < 4; i++){ 37 | int nextX = x+moveX[i]; 38 | int nextY = y+moveY[i]; 39 | 40 | if(nextX == sourceX && nextY == sourceY && count >= 4) return true; 41 | } 42 | 43 | for(int i = 0; i < 4; i++){ 44 | int nextX = x+moveX[i]; 45 | int nextY = y+moveY[i]; 46 | 47 | if(nextX >= 0 && nextX < n && nextY >= 0 && nextY < m){ 48 | if(board[nextX][nextY] == board[x][y] && !isVisited[nextX][nextY]){ 49 | isVisited[nextX][nextY] = true; 50 | if(isCyclePresent(board, n, m, sourceX, sourceY, nextX, nextY, count+1, isVisited)){ 51 | return true; 52 | } 53 | isVisited[nextX][nextY] = false; 54 | } 55 | } 56 | } 57 | 58 | return false; 59 | } 60 | int solve(char board[][MAXN],int n, int m) 61 | { 62 | bool **isVisited = new bool *[n]; 63 | for(int i = 0; i < n; i++){ 64 | isVisited[i] = new bool[m]; 65 | for(int j = 0; j < m; j++) isVisited[i][j] = false; 66 | } 67 | 68 | for(int i = 0; i < n; i++){ 69 | for(int j = 0; j < m; j++){ 70 | if(!isVisited[i][j]){ 71 | isVisited[i][j] = true; 72 | if(isCyclePresent(board, n, m, i, j, i, j, 1, isVisited)) return 1; 73 | isVisited[i][j] = false; 74 | } 75 | } 76 | } 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Graphs 1/GetPathBFS.cpp: -------------------------------------------------------------------------------- 1 | Code : Get Path - BFS 2 | Send Feedback 3 | Given an undirected graph G(V, E) and two vertices v1 and v2(as integers), find and print the path from v1 to v2 (if exists). Print nothing if there is no path between v1 and v2. 4 | Find the path using BFS and print the shortest path available. 5 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 6 | E is the number of edges present in graph G. 7 | Print the path in reverse order. That is, print v2 first, then intermediate vertices and v1 at last. 8 | Note : Save the input graph in Adjacency Matrix. 9 | Input Format : 10 | Line 1: Two Integers V and E (separated by space) 11 | Next E lines : Two integers a and b, denoting that there exists an edge between vertex a and vertex b (separated by space) 12 | Line (E+2) : Two integers v1 and v2 (separated by space) 13 | Output Format : 14 | Path from v1 to v2 in reverse order (separated by space) 15 | Constraints : 16 | 2 <= V <= 1000 17 | 1 <= E <= 1000 18 | 0 <= v1, v2 <= V-1 19 | Sample Input 1 : 20 | 4 4 21 | 0 1 22 | 0 3 23 | 1 2 24 | 2 3 25 | 1 3 26 | Sample Output 1 : 27 | 3 0 1 28 | Sample Input 2 : 29 | 6 3 30 | 5 3 31 | 0 1 32 | 3 4 33 | 0 3 34 | Sample Output 2 : 35 | 36 | 37 | 38 | /******************************************************** SOLUTION *****************************************************/ 39 | 40 | 41 | 42 | #include 43 | #include 44 | #include 45 | using namespace std; 46 | 47 | vector* getPath(int** edges, int n, int sv, int ev) 48 | { queue bfsQ; 49 | bool * visited = new bool[n]; 50 | for (int i = 0; i < n; i++) { 51 | visited[i] = false; 52 | } 53 | 54 | bfsQ.push(sv); 55 | 56 | visited[sv] = true; 57 | bool done = false; 58 | unordered_map parent; 59 | while (!bfsQ.empty() && !done) { 60 | int front = bfsQ.front(); 61 | bfsQ.pop(); 62 | for (int i = 0; i < n; i++) { 63 | if (edges[front][i] && !visited[i]) { 64 | parent[i] = front; bfsQ.push(i); 65 | visited[i] = true; if (i == ev) { 66 | done = true; 67 | break; 68 | } 69 | } 70 | } 71 | } 72 | delete [] visited; 73 | if (!done) { 74 | return NULL; 75 | } else { 76 | vector* output = new vector(); 77 | int current = ev; 78 | output->push_back(ev); 79 | while (current != sv) { 80 | current = parent[current]; 81 | output->push_back(current); 82 | } return output; 83 | } 84 | } 85 | 86 | 87 | 88 | int main() { 89 | int n; 90 | int e; 91 | cin >> n >> e; 92 | int** edges = 93 | new int*[n]; 94 | for (int i = 0; i < n; i++) { 95 | edges[i] = new int[n]; 96 | for (int j = 0; j < n; j++) { 97 | edges[i][j] = 0; 98 | } 99 | } for (int i = 0; i < e; i++) { 100 | int f, s; 101 | cin >> f >> s; 102 | edges[f][s] = 1; edges[s][f] = 1; } 103 | int sv, ev; 104 | cin >> sv >> ev; 105 | vector* output = getPath(edges, n, sv, ev); 106 | if (output != NULL) { 107 | for (int i = 0; i < output->size(); i++) { 108 | cout << output->at(i) << " "; 109 | } delete output; 110 | } for (int i = 0; i < n; i++) { 111 | delete [] edges[i]; 112 | } delete [] edges; 113 | } 114 | -------------------------------------------------------------------------------- /Graphs 1/GetPathDFS.cpp: -------------------------------------------------------------------------------- 1 | Code : Get Path - DFS 2 | Send Feedback 3 | Given an undirected graph G(V, E) and two vertices v1 and v2(as integers), find and print the path from v1 to v2 (if exists). Print nothing if there is no path between v1 and v2. 4 | Find the path using DFS and print the first path that you encountered. 5 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 6 | E is the number of edges present in graph G. 7 | Print the path in reverse order. That is, print v2 first, then intermediate vertices and v1 at last. 8 | Note : Save the input graph in Adjacency Matrix. 9 | Input Format : 10 | Line 1: Two Integers V and E (separated by space) 11 | Next E lines : Two integers a and b, denoting that there exists an edge between vertex a and vertex b (separated by space) 12 | Line (E+2) : Two integers v1 and v2 (separated by space) 13 | Output Format : 14 | Path from v1 to v2 in reverse order (separated by space) 15 | Constraints : 16 | 2 <= V <= 1000 17 | 1 <= E <= 1000 18 | 0 <= v1, v2 <= V-1 19 | Sample Input 1 : 20 | 4 4 21 | 0 1 22 | 0 3 23 | 1 2 24 | 2 3 25 | 1 3 26 | Sample Output 1 : 27 | 3 0 1 28 | Sample Input 2 : 29 | 6 3 30 | 5 3 31 | 0 1 32 | 3 4 33 | 0 3 34 | Sample Output 2 : 35 | 36 | 37 | 38 | /******************************************************** SOLUTION *****************************************************/ 39 | 40 | 41 | 42 | 43 | #include 44 | using namespace std; 45 | #include 46 | vector* getPath(int *edges[],int n,int sv,int ev,bool *visited) 47 | { 48 | if(sv==ev){ 49 | //make a vector 50 | vector *v=new vector; 51 | v->push_back(sv); 52 | return v; 53 | } 54 | vector*temp2=NULL; 55 | visited[sv]=true; 56 | 57 | for(int i=0;i*temp=getPath(edges,n,i,ev,visited); 64 | if(temp!=NULL) 65 | { 66 | temp2=temp; 67 | break; 68 | 69 | } 70 | } 71 | } 72 | if(temp2!=NULL) 73 | { 74 | temp2->push_back(sv); 75 | 76 | } 77 | return temp2; 78 | } 79 | 80 | 81 | int main() 82 | { 83 | int n,e; 84 | cin>>n>>e; 85 | int**edges=new int*[n]; 86 | for(int i=0;i>f>>s; 105 | edges[f][s]=1; 106 | edges[s][f]=1; 107 | 108 | } 109 | int v1,v2; 110 | cin>>v1>>v2; 111 | 112 | /// print(edges,n,0,visited); 113 | vector *v=getPath(edges,n,v1,v2,visited); 114 | if(v==NULL) return 0; 115 | 116 | for(int i=0;isize();i++) 117 | { 118 | cout<at(i)<<" "; 119 | } 120 | ///delete memory now 121 | 122 | } 123 | -------------------------------------------------------------------------------- /Graphs 1/HasPath.cpp: -------------------------------------------------------------------------------- 1 | Code : Has Path 2 | Send Feedback 3 | Given an undirected graph G(V, E) and two vertices v1 and v2(as integers), check if there exists any path between them or not. Print true or false. 4 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 5 | E is the number of edges present in graph G. 6 | Input Format : 7 | Line 1: Two Integers V and E (separated by space) 8 | Next E lines : Two integers a and b, denoting that there exists an edge between vertex a and vertex b (separated by space) 9 | Line (E+2) : Two integers v1 and v2 (separated by space) 10 | Output Format : 11 | true or false 12 | Constraints : 13 | 2 <= V <= 1000 14 | 1 <= E <= 1000 15 | 0 <= v1, v2 <= V-1 16 | Sample Input 1 : 17 | 4 4 18 | 0 1 19 | 0 3 20 | 1 2 21 | 2 3 22 | 1 3 23 | Sample Output 1 : 24 | true 25 | Sample Input 2 : 26 | 6 3 27 | 5 3 28 | 0 1 29 | 3 4 30 | 0 3 31 | Sample Output 2 : 32 | false 33 | 34 | 35 | 36 | 37 | /******************************************************** SOLUTION *****************************************************/ 38 | 39 | 40 | 41 | #include 42 | 43 | using namespace std; 44 | bool hasPath(int** edges, int n, int a, int b, int* visited){ 45 | //Base Case 46 | if (a==b) 47 | { 48 | return 1; 49 | } 50 | int result = 0; 51 | 52 | for (int i = 0; i < n; ++i) 53 | { 54 | if (edges[a][i] == 1 && visited[i] == 0) 55 | { 56 | visited[i] = 1; 57 | result = hasPath(edges, n, i, b, visited); 58 | if (result==1) 59 | { 60 | return 1; 61 | } 62 | } 63 | } 64 | 65 | // for (int i = 0; i < n; ++i) 66 | // { 67 | // cout << visited[i] << ' '; 68 | // } 69 | 70 | return result; 71 | 72 | } 73 | 74 | int main( int argc , char ** argv ) 75 | { 76 | ios_base::sync_with_stdio(false) ; 77 | cin.tie(NULL) ; 78 | 79 | int n, e; 80 | cin>>n>>e; 81 | 82 | int** edges = new int*[n]; 83 | 84 | for (int i = 0; i < n; ++i) 85 | { 86 | edges[i] = new int[n]; 87 | for (int j = 0; j < n; ++j) 88 | { 89 | edges[i][j] = 0; 90 | } 91 | 92 | } 93 | 94 | int* visited = new int[n]; 95 | for (int i = 0; i < n; ++i) 96 | { 97 | visited[i] = 0; 98 | } 99 | 100 | for (int i = 0; i < e; ++i) 101 | { 102 | int a, b; 103 | cin>>a>>b; 104 | 105 | edges[a][b] = 1; 106 | edges[b][a] = 1; 107 | } 108 | 109 | int c, d; 110 | cin>>c>>d; 111 | 112 | if(hasPath(edges, n, c, d, visited)){ 113 | cout << "true" << '\n'; 114 | }else{ 115 | cout << "false" << '\n'; 116 | } 117 | 118 | return 0 ; 119 | 120 | 121 | 122 | } 123 | -------------------------------------------------------------------------------- /Graphs 1/IsConnected.cpp: -------------------------------------------------------------------------------- 1 | Code : Is Connected ? 2 | Send Feedback 3 | Given an undirected graph G(V,E), check if the graph G is connected graph or not. 4 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 5 | E is the number of edges present in graph G. 6 | Input Format : 7 | Line 1: Two Integers V and E (separated by space) 8 | Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'. 9 | Output Format : 10 | "true" or "false" 11 | Constraints : 12 | 2 <= V <= 1000 13 | 1 <= E <= 1000 14 | Sample Input 1: 15 | 4 4 16 | 0 1 17 | 0 3 18 | 1 2 19 | 2 3 20 | Sample Output 1: 21 | true 22 | Sample Input 2: 23 | 4 3 24 | 0 1 25 | 1 3 26 | 0 3 27 | Sample Output 2: 28 | false 29 | Sample Output 2 Explanation 30 | The graph is not connected, even though vertices 0,1 and 3 are connected to each other but there isn’t any path from vertices 0,1,3 to vertex 2. 31 | 32 | 33 | 34 | /******************************************************** SOLUTION *****************************************************/ 35 | 36 | 37 | 38 | #include 39 | 40 | using namespace std; 41 | 42 | void marker(int** edges, int n, int* visited, int sv){ 43 | if (n==1) 44 | { 45 | visited[sv] = 1; 46 | return; 47 | } 48 | 49 | visited[sv] = 1; 50 | 51 | for (int i = 0; i < n; ++i) 52 | { 53 | if (edges[sv][i]==1 && visited[i]==0) 54 | { 55 | marker(edges, n, visited, i); 56 | } 57 | } 58 | return; 59 | 60 | } 61 | 62 | int main( int argc , char ** argv ) 63 | { 64 | ios_base::sync_with_stdio(false) ; 65 | cin.tie(NULL) ; 66 | 67 | int n, e; 68 | cin>>n>>e; 69 | 70 | int** edges = new int*[n]; 71 | 72 | for (int i = 0; i < n; ++i) 73 | { 74 | edges[i] = new int[n]; 75 | for (int j = 0; j < n; ++j) 76 | { 77 | edges[i][j] = 0; 78 | } 79 | 80 | } 81 | 82 | int* visited = new int[n]; 83 | for (int i = 0; i < n; ++i) 84 | { 85 | visited[i] = 0; 86 | } 87 | 88 | for (int i = 0; i < e; ++i) 89 | { 90 | int a, b; 91 | cin>>a>>b; 92 | 93 | edges[a][b] = 1; 94 | edges[b][a] = 1; 95 | } 96 | 97 | 98 | marker(edges, n, visited, 0); 99 | 100 | for (int i = 0; i < n; ++i) 101 | { 102 | if (visited[i] == 0) 103 | { 104 | cout << "false" << '\n'; 105 | return 0; 106 | } 107 | 108 | } 109 | cout << "true" << '\n'; 110 | 111 | 112 | return 0 ; 113 | 114 | 115 | 116 | } 117 | -------------------------------------------------------------------------------- /Graphs 1/Islands.cpp: -------------------------------------------------------------------------------- 1 | Islands 2 | Send Feedback 3 | An island is a small piece of land surrounded by water . A group of islands is said to be connected if we can reach from any given island to any other island in the same group . Given N islands (numbered from 1 to N) and two lists of size M (u and v) denoting island u[i] is connected to island v[i] and vice versa . Can you count the number of connected groups of islands. 4 | Constraints : 5 | 1<=N<=100 6 | 1<=M<=(N*(N-1))/2 7 | 1<=u[i],v[i]<=N 8 | Input Format : 9 | Line 1 : Two integers N and M 10 | Line 2 : List u of size of M 11 | Line 3 : List v of size of M 12 | Output Return Format : 13 | The count the number of connected groups of islands 14 | Sample Input : 15 | 2 1 16 | 1 17 | 2 18 | Sample Output : 19 | 1 20 | 21 | 22 | 23 | /******************************************************** SOLUTION *****************************************************/ 24 | 25 | 26 | 27 | #include 28 | 29 | using namespace std; 30 | 31 | void DFS(int** arr, int* visited, int n, int sv){ 32 | 33 | visited[sv] = 1; 34 | 35 | for (int i = 0; i < n; ++i) 36 | { 37 | if (i==sv) 38 | { 39 | continue; 40 | } 41 | if (arr[sv][i] == 1 && visited[i] == 0) 42 | { 43 | DFS(arr, visited, n, i); 44 | } 45 | } 46 | 47 | return; 48 | } 49 | int solve(int n,int m,vectoru,vectorv) 50 | { 51 | int** arr = new int*[n]; 52 | for (int i = 0; i < n; ++i) 53 | { 54 | arr[i] = new int[n]; 55 | for (int j = 0; j < n; ++j) 56 | { 57 | arr[i][j] = 0; 58 | } 59 | } 60 | 61 | 62 | 63 | for (int i = 0; i < m; ++i) 64 | { 65 | arr[u[i]-1][v[i]-1] = 1; 66 | arr[v[i]-1][u[i]-1] = 1; 67 | } 68 | 69 | 70 | int* visited = new int[n]; 71 | 72 | for (int i = 0; i < n; ++i) 73 | { 74 | visited[i] = 0; 75 | } 76 | 77 | int count = 0; 78 | for (int i = 0; i < n; ++i) 79 | { 80 | if (visited[i]==0) 81 | { 82 | count++; 83 | DFS(arr, visited, n, i); 84 | } 85 | } 86 | 87 | return count; 88 | 89 | } 90 | -------------------------------------------------------------------------------- /Graphs 1/LargestPiece.cpp: -------------------------------------------------------------------------------- 1 | Largest Piece 2 | Send Feedback 3 | Its Gary's birthday today and he has ordered his favourite square cake consisting of '0's and '1's . But Gary wants the biggest piece of '1's and no '0's . A piece of cake is defined as a part which consist of only '1's, and all '1's share an edge with eachother on the cake. Given the size of cake N and the cake , can you find the size of the biggest piece of '1's for Gary ? 4 | Constraints : 5 | 1<=N<=50 6 | Input Format : 7 | Line 1 : An integer N denoting the size of cake 8 | Next N lines : N characters denoting the cake 9 | Output Format : 10 | Size of the biggest piece of '1's and no '0's 11 | Sample Input : 12 | 2 13 | 11 14 | 01 15 | Sample Output : 16 | 3 17 | 18 | 19 | /*************************************************************** SOLUTION *******************************************************************************/ 20 | 21 | 22 | 23 | #include 24 | 25 | using namespace std; 26 | #include 27 | #include 28 | #include 29 | 30 | 31 | static int rowNbr[] = {-1, 1, 0, 0}; 32 | static int colNbr[] = {0, 0, 1, -1}; 33 | 34 | 35 | //To check if the index is an eligible index for our cake 36 | bool iseligible(char cake[][55], int x, int y, int** visited, int n) 37 | { 38 | // if(x == 0 && y == 4) 39 | // cout << "Chirag" << endl; 40 | //cout << x << " " << y << endl; 41 | if(x<0 || x>=n || y<0 || y>=n|| visited[x][y] == 1 || cake[x][y] == '0' ){ 42 | return 0; 43 | } 44 | else 45 | return 1; 46 | } 47 | 48 | //Returns the maximum peice of cake that can be taken starting from x,y 49 | int solver(int n, char cake[][55], int** visited, int x, int y){ 50 | int sum=0; 51 | 52 | for(int k=0;k<4;k++){ 53 | if(iseligible(cake,x+rowNbr[k], y+colNbr[k], visited, n)){ 54 | 55 | visited[x+rowNbr[k]][y+colNbr[k]]=1; 56 | sum=sum+solver(n, cake, visited, x+rowNbr[k], y+colNbr[k]); 57 | } 58 | } 59 | return 1+sum; 60 | } 61 | 62 | 63 | //passes index of each one to solver as starting point and returns max of all 64 | int solve(int n,char cake[][55]) 65 | { 66 | int** visited = new int*[n]; 67 | for(int i=0;i 32 | #include 33 | using namespace std; 34 | 35 | int findMinVertex(int* distance, bool* visited, int n){ 36 | 37 | int minVertex = -1; 38 | for(int i = 0; i < n; i++){ 39 | if(!visited[i] && (minVertex == -1 || distance[i] < distance[minVertex])){ 40 | minVertex = i; 41 | } 42 | } 43 | return minVertex; 44 | } 45 | 46 | void dijkstra(int** edges, int n){ 47 | int* distance = new int[n]; 48 | bool* visited = new bool[n]; 49 | 50 | for(int i = 0; i < n; i++){ 51 | distance[i] = INT_MAX; 52 | visited[i] = false; 53 | } 54 | distance[0] = 0; 55 | for(int i = 0; i < n - 1; i++){ 56 | int minVertex = findMinVertex(distance, visited, n); 57 | visited[minVertex] = true; 58 | for(int j = 0; j < n; j++){ 59 | if(edges[minVertex][j] != 0 && !visited[j]){ 60 | int dist = distance[minVertex] + edges[minVertex][j]; 61 | if(dist < distance[j]){ 62 | distance[j] = dist; 63 | } 64 | } 65 | } 66 | } 67 | for(int i = 0; i < n; i++){ 68 | cout << i << " " << distance[i] << endl; 69 | } 70 | delete [] visited; 71 | delete [] distance; 72 | } 73 | int main() { 74 | int n; 75 | int e; 76 | cin >> n >> e; 77 | int** edges = new int*[n]; 78 | for (int i = 0; i < n; i++) { 79 | edges[i] = new int[n]; 80 | for (int j = 0; j < n; j++) { 81 | edges[i][j] = 0; 82 | } 83 | } 84 | 85 | for (int i = 0; i < e; i++) { 86 | int f, s, weight; 87 | cin >> f >> s >> weight; 88 | edges[f][s] = weight; 89 | edges[s][f] = weight; 90 | } 91 | cout << endl; 92 | dijkstra(edges, n); 93 | 94 | for (int i = 0; i < n; i++) { 95 | delete [] edges[i]; 96 | } 97 | delete [] edges; 98 | } 99 | -------------------------------------------------------------------------------- /Graphs 2/Kruskal'sAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | Kruskal's Algorithm 2 | Send Feedback 3 | Given an undirected, connected and weighted graph G(V, E) with V number of vertices (which are numbered from 0 to V-1) and E number of edges. 4 | Find and print the Minimum Spanning Tree (MST) using Kruskal's algorithm. 5 | For printing MST follow the steps - 6 | 1. In one line, print an edge which is part of MST in the format - 7 | v1 v2 w 8 | where, v1 and v2 are the vertices of the edge which is included in MST and whose weight is w. And v1 <= v2 i.e. print the smaller vertex first while printing an edge. 9 | 2. Print V-1 edges in above format in different lines. 10 | Note : Order of different edges doesn't matter. 11 | Input Format : 12 | Line 1: Two Integers V and E (separated by space) 13 | Next E lines : Three integers ei, ej and wi, denoting that there exists an edge between vertex ei and vertex ej with weight wi (separated by space) 14 | Output Format : 15 | MST 16 | Constraints : 17 | 2 <= V, E <= 10^5 18 | Sample Input 1 : 19 | 4 4 20 | 0 1 3 21 | 0 3 5 22 | 1 2 1 23 | 2 3 8 24 | Sample Output 1 : 25 | 1 2 1 26 | 0 1 3 27 | 0 3 5 28 | 29 | 30 | 31 | /************************************************* SOLUTION **********************************************************************/ 32 | 33 | 34 | #include 35 | using namespace std; 36 | 37 | struct Edge 38 | { 39 | int start; 40 | int end; 41 | int weight; 42 | }; 43 | 44 | struct DisjSet 45 | { 46 | int parent; 47 | int rank; 48 | }; 49 | 50 | int find(DisjSet *ds, int x) 51 | { 52 | if(ds[x].parent != x) 53 | ds[x].parent = find(ds,ds[x].parent); 54 | 55 | return ds[x].parent; 56 | } 57 | 58 | void Union(DisjSet *ds, int x, int y) 59 | { 60 | int rootX = find(ds,x); 61 | int rootY = find(ds,y); 62 | 63 | if(ds[rootX].rank < ds[rootY].rank) 64 | { 65 | ds[rootX].parent = rootY; 66 | } 67 | else if(ds[rootX].rank > ds[rootY].rank) 68 | { 69 | ds[rootY].parent = rootX; 70 | } 71 | else 72 | { 73 | ds[rootX].parent = rootY; 74 | ds[rootY].rank++; 75 | } 76 | } 77 | 78 | bool isUnion(DisjSet *ds, int x, int y) 79 | { 80 | return find(ds,x) == find(ds,y); 81 | } 82 | 83 | void KruskalsMST(Edge *graph, DisjSet *ds, int n, int m) 84 | { 85 | vector MST; 86 | 87 | int j = 0; 88 | 89 | for(int i = 0; i < m && j < n-1 ; i++) 90 | { 91 | if(!isUnion(ds,graph[i].start,graph[i].end)) 92 | { 93 | Union(ds,graph[i].start,graph[i].end); 94 | MST.push_back(graph[i]); 95 | j++; 96 | } 97 | } 98 | 99 | for(auto it : MST) 100 | { 101 | if(it.start <= it.end) 102 | cout << it.start << " " << it.end << " " << it.weight << endl; 103 | else 104 | cout << it.end << " " << it.start << " " << it.weight << endl; 105 | 106 | } 107 | } 108 | 109 | bool compare(Edge a,Edge b) 110 | { 111 | return a.weight < b.weight; 112 | } 113 | 114 | int main() 115 | { 116 | int n,m,cost; 117 | cin >> n >> m; 118 | 119 | Edge *graph = new Edge[m]; 120 | for(int i = 0; i < m; i++) 121 | { 122 | int a,b,c; 123 | cin >> a >> b >> c; 124 | graph[i] = {a,b,c}; 125 | } 126 | 127 | DisjSet *ds = new DisjSet[n]; 128 | 129 | for(int i = 0; i < n; i++) 130 | { 131 | ds[i].parent = i; 132 | ds[i].rank = 0; 133 | } 134 | 135 | sort(graph, graph + m, compare); 136 | 137 | KruskalsMST(graph,ds,n,m); 138 | 139 | return 0; 140 | } 141 | -------------------------------------------------------------------------------- /Graphs 2/Prim'sAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | Prim's Algorithm 2 | Send Feedback 3 | Given an undirected, connected and weighted graph G(V, E) with V number of vertices (which are numbered from 0 to V-1) and E number of edges. 4 | Find and print the Minimum Spanning Tree (MST) using Prim's algorithm. 5 | For printing MST follow the steps - 6 | 1. In one line, print an edge which is part of MST in the format - 7 | v1 v2 w 8 | where, v1 and v2 are the vertices of the edge which is included in MST and whose weight is w. And v1 <= v2 i.e. print the smaller vertex first while printing an edge. 9 | 2. Print V-1 edges in above format in different lines. 10 | Note : Order of different edges doesn't matter. 11 | Input Format : 12 | Line 1: Two Integers V and E (separated by space) 13 | Next E lines : Three integers ei, ej and wi, denoting that there exists an edge between vertex ei and vertex ej with weight wi (separated by space) 14 | Output Format : 15 | MST 16 | Constraints : 17 | 2 <= V, E <= 10^5 18 | Sample Input 1 : 19 | 4 4 20 | 0 1 3 21 | 0 3 5 22 | 1 2 1 23 | 2 3 8 24 | Sample Output 1 : 25 | 0 1 3 26 | 1 2 1 27 | 0 3 5 28 | 29 | 30 | 31 | /************************************************* SOLUTION **********************************************************************/ 32 | 33 | 34 | 35 | 36 | #include 37 | #include 38 | using namespace std; 39 | 40 | int findMinVertex(int* weights, bool* visited, int n){ 41 | 42 | int minVertex = -1; 43 | for(int i = 0; i < n; i++){ 44 | if(!visited[i] && (minVertex == - 1 || weights[i] < weights[minVertex])){ 45 | minVertex = i; 46 | } 47 | } 48 | return minVertex; 49 | } 50 | 51 | void prims(int** edges, int n){ 52 | 53 | int* parent = new int[n]; 54 | int* weights = new int[n]; 55 | bool* visited = new bool[n]; 56 | 57 | for(int i = 0; i < n; i++){ 58 | visited[i] = false; 59 | weights[i] = INT_MAX; 60 | } 61 | parent[0] = -1; 62 | weights[0] = 0; 63 | 64 | for(int i = 0; i < n - 1; i++){ 65 | // Find Min Vertex 66 | int minVertex = findMinVertex(weights, visited, n); 67 | visited[minVertex] = true; 68 | // Explore un visted neighbours 69 | for(int j = 0; j < n; j++){ 70 | if(edges[minVertex][j] != 0 && !visited[j]){ 71 | if(edges[minVertex][j] < weights[j]){ 72 | weights[j] = edges[minVertex][j]; 73 | parent[j] = minVertex; 74 | } 75 | } 76 | } 77 | } 78 | 79 | for(int i = 1; i < n; i++){ 80 | if(parent[i] < i){ 81 | cout << parent[i]<<" " << i << " " << weights[i] << endl; 82 | }else{ 83 | cout << i << " " << parent[i] << " " << weights[i] << endl; 84 | } 85 | } 86 | } 87 | 88 | int main() { 89 | int n; 90 | int e; 91 | cin >> n >> e; 92 | int** edges = new int*[n]; 93 | for (int i = 0; i < n; i++) { 94 | edges[i] = new int[n]; 95 | for (int j = 0; j < n; j++) { 96 | edges[i][j] = 0; 97 | } 98 | } 99 | 100 | for (int i = 0; i < e; i++) { 101 | int f, s, weight; 102 | cin >> f >> s >> weight; 103 | edges[f][s] = weight; 104 | edges[s][f] = weight; 105 | } 106 | cout << endl; 107 | prims(edges, n); 108 | 109 | for (int i = 0; i < n; i++) { 110 | delete [] edges[i]; 111 | } 112 | delete [] edges; 113 | } 114 | -------------------------------------------------------------------------------- /Greedy Problems/ActivitySelection.cpp: -------------------------------------------------------------------------------- 1 | Activity Selection 2 | Send Feedback 3 | 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. 4 | Input 5 | The first line of input contains one integer denoting N. 6 | Next N lines contains two space separated integers denoting the start time and finish time for the ith activity. 7 | 8 | Output 9 | Output one integer, the maximum number of activities that can be performed 10 | Constraints 11 | 1 ≤ N ≤ 10^6 12 | 1 ≤ ai, di ≤ 10^9 13 | Sample Input 14 | 6 15 | 1 2 16 | 3 4 17 | 0 6 18 | 5 7 19 | 8 9 20 | 5 9 21 | Sample Output 22 | 4 23 | 24 | 25 | /********************************************* SOLUTION ****************************************************************/ 26 | 27 | 28 | #include 29 | using namespace std; 30 | #define LL unsigned long long int 31 | 32 | struct Activity 33 | { 34 | LL start; 35 | LL end; 36 | }; 37 | 38 | bool operator <(Activity a,Activity b) 39 | { 40 | if(a.end == b.end) 41 | { 42 | return a.start < b.start; 43 | } 44 | return a.end < b.end; 45 | } 46 | 47 | int main() 48 | { 49 | //Write your code here 50 | int n; 51 | cin >> n; 52 | 53 | Activity *act = new Activity[n]; 54 | for(int i = 0; i < n; i++) 55 | cin >> act[i].start >> act[i].end; 56 | 57 | sort(act,act+n); 58 | 59 | int cnt = 1; 60 | Activity prev = act[0]; 61 | 62 | for(int i = 1; i < n; i++) 63 | { 64 | if(prev.end <= act[i].start) 65 | { 66 | cnt++; 67 | prev = act[i]; 68 | } 69 | } 70 | 71 | cout << cnt << endl; 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /Greedy Problems/FractionalKnapsack.cpp: -------------------------------------------------------------------------------- 1 | Fractional Knapsack 2 | Send Feedback 3 | You want to paint your house. The total area of your house is D units. There are a total of N workers. The ith worker is available after time Ti, has hiring cost Xi and speed Yi. This means he becomes available for hiring from time Ti and remains available after that. Once available, you can hire him with cost Xi, after which he will start painting the house immediately, covering exactly Yi units of house with paint per time unit. You may or may not hire a worker and can also hire or fire him at any later point of time. However, no more than 1 worker can be painting the house at a given time. 4 | Since you want the work to be done as fast as possible, figure out a way to hire the workers, such that your house gets painted at the earliest possible time, with minimum cost to spend for hiring workers. 5 | Note: You can hire a previously hired worker without paying him again. 6 | Input 7 | The first line of input contains two integers "N D", the number of workers and the area of your house respectively. The ith of the next N lines denotes the ith worker, and contains three integers "Ti Xi Yi", described in the statement. 8 | Output 9 | Output one integer, the minimum cost that you can spend in order to get your house painted at the earliest. 10 | Constraints 11 | 1 ≤ N, T, X, Y ≤ 10^5 12 | 1 ≤ D ≤ 10^11 13 | Sample Input 14 | 3 3 15 | 1 1 1 16 | 2 2 2 17 | 3 1 5 18 | Sample Output 19 | 3 20 | 21 | 22 | /********************************************* SOLUTION ****************************************************************/ 23 | 24 | 25 | #include 26 | 27 | using namespace std; 28 | 29 | bool mySort(vector a, vector b){ 30 | 31 | if (a[0] == b[0]) { 32 | if (a[2] == b[2]) { 33 | return (a[1] < b[1]); 34 | } 35 | return (a[2] > b[2]); 36 | } 37 | return (a[0] < b[0]); 38 | } 39 | 40 | long long go(vector> worker, long long area){ 41 | long long n = worker.size(); 42 | sort(worker.begin(),worker.end(),mySort); 43 | 44 | long long cost = worker.at(0)[1]; 45 | long long area_done = 0; 46 | long long current_worker = 0; 47 | long long last = 0; 48 | 49 | for (int i = 1; i < n && area_done=area) 64 | { 65 | 66 | return cost; 67 | 68 | } 69 | 70 | if (worker.at(current_worker)[2]>n>>d; 94 | vector> worker; 95 | 96 | while(n--){ 97 | long long t,x,y; 98 | cin>>t>>x>>y; 99 | 100 | vector temp; 101 | temp.push_back(t); 102 | temp.push_back(x); 103 | temp.push_back(y); 104 | 105 | worker.push_back(temp); 106 | } 107 | 108 | cout << go(worker, d) << '\n'; 109 | 110 | 111 | 112 | return 0 ; 113 | 114 | 115 | 116 | } 117 | -------------------------------------------------------------------------------- /Greedy Problems/Min.AbsoluteDifferenceInArray.cpp: -------------------------------------------------------------------------------- 1 | Min. Absolute Difference In Array 2 | Send Feedback 3 | Given an integer array A of size N, find and return the minimum absolute difference between any two elements in the array. 4 | We define the absolute difference between two elements ai, and aj (where i != j ) is |ai - aj|. 5 | Input format : 6 | Line 1 : Integer N, Array Size 7 | Line 2 : Array elements (separated by space) 8 | Output Format : 9 | Minimum difference 10 | Constraints : 11 | 1 <= N <= 10^6 12 | Sample Input : 13 | 5 14 | 2 9 0 4 5 15 | Sample Input : 16 | 1 17 | 18 | 19 | /********************************************* SOLUTION ****************************************************************/ 20 | 21 | 22 | #include 23 | using namespace std; 24 | 25 | int minAbsoluteDiff(int arr[], int n) { 26 | 27 | sort(arr,arr+n); 28 | int minDiff = INT_MAX; 29 | for(int i = 1; i < n; i++) 30 | { 31 | if(abs(arr[i]-arr[i-1]) < minDiff) 32 | minDiff = arr[i]-arr[i-1]; 33 | } 34 | return minDiff; 35 | } 36 | -------------------------------------------------------------------------------- /Greedy Problems/NikunjAndDonuts.cpp: -------------------------------------------------------------------------------- 1 | Nikunj and Donuts 2 | Send Feedback 3 | Nikunj loves donuts, but he also likes to stay fit. He eats n donuts in one sitting, and each donut has a calorie count, ci. After eating a donut with k calories, he must walk at least 2^j x k(where j is the number donuts he has already eaten) miles to maintain his weight. 4 | Given the individual calorie counts for each of the n donuts, find and print a long integer denoting the minimum number of miles Nikunj must walk to maintain his weight. Note that he can eat the donuts in any order. 5 | Input 6 | The first line contains an integer, n, denoting the number of donuts. 7 | The second line contains n space-separated integers describing the respective calorie counts of each donut I, i.e ci. 8 | Output 9 | Print a long integer denoting the minimum number of miles Nikunj must walk to maintain his weight. 10 | Constraints 11 | 1 ≤ n ≤ 40 12 | 1 ≤ ci ≤ 1000 13 | Sample Input 14 | 3 15 | 1 3 2 16 | Sample Output 17 | 11 18 | 19 | /********************************************* SOLUTION ****************************************************************/ 20 | 21 | 22 | #include 23 | using namespace std; 24 | int main() 25 | { 26 | int n; 27 | cin >> n; 28 | 29 | int *arr = new int[n]; 30 | for(int i = 0; i < n; i++) 31 | { 32 | cin >> arr[i]; 33 | } 34 | 35 | sort(arr,arr+n,greater()); 36 | 37 | unsigned long long int miles = 0,power2 = 1; 38 | for(int i = 0; i < n; i++) 39 | { 40 | miles += (power2*arr[i]); 41 | power2 *= 2; 42 | } 43 | cout << miles << endl; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Greedy Problems/PerimeterWithConditions.cpp: -------------------------------------------------------------------------------- 1 | Perimeter with conditions 2 | Send Feedback 3 | Aahad gives an array of integers and asks Harshit to find which three elements form a triangle (non-degenerate). The task seems easy to Harshit. 4 | So, Aahad adds some conditions to this task - 5 | 1. Find the triangle with maximum perimeter 6 | 2. If there are two or more combinations with same value of maximum perimeter, then find the one with the longest side. 7 | 3.If there are more than one combinations which satisfy all the above conditions the find with maximum longest minimum side. 8 | Input Format 9 | The First line contains no of elements of array: N 10 | Each T lines contains N space-separated integers: A [i] 11 | Output Format 12 | The output contains three space-separated elements that denote the length of the sides of triangle. If no such triangle is possible, then print -1. 13 | Constraints 14 | 1 =< N <= 10^5 15 | 1 <= A[i] <= 10^9 16 | Time Limit: 1 second 17 | Sample Input1: 18 | 5 19 | 1 1 1 3 3 20 | Sample Output1: 21 | 1 3 3 22 | Sample Input2: 23 | 3 24 | 2 2 4 25 | Sample Output3: 26 | -1 27 | Explaination 28 | In the First Sample case, the elements that form a triangle with maximum perimeter is 1,3,3. 29 | In the Second Sample case, the elements that can form a triangle are degenerate, so, we printed -1. 30 | 31 | 32 | /********************************************* SOLUTION ****************************************************************/ 33 | 34 | 35 | #include 36 | using namespace std; 37 | void go(int* arr, int n){ 38 | sort(arr, arr+n, greater()); 39 | 40 | for (int i = 0; i < n-2; ++i) 41 | { 42 | int s1, s2, s3; 43 | 44 | s1 = arr[i]; 45 | s2 = arr[i+1]; 46 | s3 = arr[i+2]; 47 | 48 | if (s2+s3>s1 && s1+s2>s3 && s3+s1>s2) 49 | { 50 | cout << s3<<" "<>n; 67 | 68 | int* arr = new int[n]; 69 | 70 | for (int i = 0; i < n; ++i) 71 | { 72 | cin>>arr[i]; 73 | } 74 | go(arr, n); 75 | 76 | delete [] arr; 77 | 78 | return 0 ; 79 | 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /Greedy Problems/ProblemDiscussion.cpp: -------------------------------------------------------------------------------- 1 | Problem discussion 2 | Send Feedback 3 | Harshit gave Aahad an array of size N and asked to minimize the difference between the maximum value and minimum value by modifying the array under the condition that each array element either increase or decrease by k(only once). 4 | It seems difficult for Aahad so he asked for your help 5 | Input Format 6 | The First line contains two space-separated integers: N,K 7 | Next lines contain N space-separated integers denoting elements of the array 8 | Output Format 9 | The output contains a single integer denoting the minimum difference between maximum value and the minimum value in the array 10 | Constraints 11 | 1 =< N <= 10^5 12 | 1 <= Ai,K <= 10^9 13 | Sample Input1: 14 | 3 6 15 | 1 15 10 16 | Sample Output1: 17 | 5 18 | Explaination 19 | We change from 1 to 6, 15 to 9 and 10 to 4. Maximum difference is 5 (between 4 and 9). We can't get a lower difference. 20 | 21 | 22 | /********************************************* SOLUTION ****************************************************************/ 23 | 24 | 25 | #include 26 | 27 | using namespace std; 28 | 29 | int getMinDiff(int arr[], int n, int k) 30 | { 31 | if (n == 1) 32 | return 0; 33 | 34 | // Sort all elements 35 | sort(arr, arr+n); 36 | 37 | // Initialize result 38 | int ans = arr[n-1] - arr[0]; 39 | 40 | // Handle corner elements 41 | int small = arr[0] + k; 42 | int big = arr[n-1] - k; 43 | if (small > big) 44 | swap(small, big); 45 | 46 | // Traverse middle elements 47 | for (int i = 1; i < n-1; i ++) 48 | { 49 | int subtract = arr[i] - k; 50 | int add = arr[i] + k; 51 | 52 | // If both subtraction and addition 53 | // do not change diff 54 | if (subtract >= small || add <= big) 55 | continue; 56 | 57 | // Either subtraction causes a smaller 58 | // number or addition causes a greater 59 | // number. Update small or big using 60 | // greedy approach (If big - subtract 61 | // causes smaller diff, update small 62 | // Else update big) 63 | if (big - subtract <= add - small) 64 | small = subtract; 65 | else 66 | big = add; 67 | } 68 | 69 | return min(ans, big - small); 70 | } 71 | 72 | int main( int argc , char ** argv ) 73 | { 74 | ios_base::sync_with_stdio(false) ; 75 | cin.tie(NULL) ; 76 | 77 | int n,k; 78 | cin>>n>>k; 79 | 80 | int* arr = new int[n]; 81 | 82 | for (int i = 0; i < n; ++i) 83 | { 84 | cin>>arr[i]; 85 | } 86 | 87 | cout << getMinDiff(arr, n, k) << '\n'; 88 | 89 | 90 | return 0 ; 91 | 92 | 93 | 94 | } 95 | -------------------------------------------------------------------------------- /Greedy Problems/WeightedJobScheduling.cpp: -------------------------------------------------------------------------------- 1 | Weighted Job Scheduling 2 | Send Feedback 3 | You are given N jobs where every job is represented as: 4 | 1.Start Time 5 | 2.Finish Time 6 | 3.Profit Associated 7 | Find the maximum profit subset of jobs such that no two jobs in the subset overlap. 8 | Input 9 | The first line of input contains one integer denoting N. 10 | Next N lines contains three space separated integers denoting the start time, finish time and the profit associated with the ith job. 11 | Output 12 | Output one integer, the maximum profit that can be achieved. 13 | Constraints 14 | 1 ≤ N ≤ 10^6 15 | 1 ≤ ai, di, p ≤ 10^6 16 | Sample Input 17 | 4 18 | 3 10 20 19 | 1 2 50 20 | 6 19 100 21 | 2 100 200 22 | Sample Output 23 | 250 24 | 25 | 26 | /********************************************* SOLUTION ****************************************************************/ 27 | 28 | 29 | #include 30 | using namespace std; 31 | typedef long long ll; 32 | 33 | struct job{ 34 | ll start, finish, profit; 35 | 36 | job(ll s, ll f, ll p){ 37 | start = s; 38 | finish = f; 39 | profit = p; 40 | } 41 | }; 42 | 43 | bool compare(job a, job b){ 44 | return a.finish < b.finish; 45 | } 46 | 47 | ll search(vector *input, ll limit, ll si, ll ei){ 48 | if(si > ei) return -1; 49 | 50 | if(si == ei){ 51 | if((input->at(si)).finish <= limit) return si; 52 | else return -1; 53 | } 54 | 55 | ll mid = (si+ei)/2; 56 | if((input->at(mid)).finish <= limit){ 57 | ll answer = search(input, limit, mid+1, ei); 58 | if(answer == -1) return mid; 59 | else return answer; 60 | } 61 | else return search(input, limit, si, mid-1); 62 | } 63 | 64 | int main(){ 65 | ll n; 66 | cin >> n; 67 | 68 | vector input; 69 | for(ll i = 0; i < n; i++){ 70 | ll s, f, p; 71 | cin >> s >> f >> p; 72 | input.push_back(job(s, f, p)); 73 | } 74 | 75 | sort(input.begin(), input.end(), compare); 76 | 77 | ll *dp = new ll[n]; 78 | dp[0] = input[0].profit; 79 | for(ll i = 1; i < n; i++){ 80 | ll include = input[i].profit; 81 | 82 | ll id = -1; 83 | id = search(&input, input[i].start, 0, i-1); 84 | // for(ll j = i-1; j >= 0; j--){ 85 | // if(input[j].finish <= input[i].start){ 86 | // id = j; 87 | // break; 88 | // } 89 | // } 90 | 91 | if(id != -1){ 92 | include += dp[id]; 93 | } 94 | 95 | dp[i] = max(dp[i-1], include); 96 | } 97 | 98 | cout << dp[n-1] << endl; 99 | } 100 | -------------------------------------------------------------------------------- /Greedy Problems/WinningLottery.cpp: -------------------------------------------------------------------------------- 1 | Winning Lottery 2 | Send Feedback 3 | Harshit knows by his resources that this time the winning lottery number is the smallest number whose sum of the digits is S and the number of digits is D. You have to help Harshit and print the winning lottery number. 4 | Input Format 5 | The Input line contains two space-separated integers: S,D 6 | Output Format 7 | The output contains a single integer denoting the winning lottery number 8 | Constraints 9 | 1 <= D <= 1000 10 | 1 <= S <= 9*D 11 | Time Limit: 1 second 12 | Sample Input1: 13 | 9 2 14 | Sample Output1: 15 | 18 16 | Explanation 17 | There are many other possible numbers like 45, 54, 90, etc with the sum of digits as 9 and number of digits as 2. The smallest of them is 18. 18 | 19 | 20 | /********************************************* SOLUTION ****************************************************************/ 21 | 22 | 23 | #include 24 | 25 | using namespace std; 26 | 27 | void findSmallest(int m, int s) 28 | { 29 | // If sum of digits is 0, then a number is possible 30 | // only if number of digits is 1. 31 | if (s == 0) 32 | { 33 | (m == 1)? cout << 0 34 | : cout << "Not possible"; 35 | return ; 36 | } 37 | 38 | // Sum greater than the maximum possible sum. 39 | if (s > 9*m) 40 | { 41 | cout << "Not possible"; 42 | return ; 43 | } 44 | 45 | // Create an array to store digits of result 46 | int res[m]; 47 | 48 | // deduct sum by one to account for cases later 49 | // (There must be 1 left for the most significant 50 | // digit) 51 | s -= 1; 52 | 53 | // Fill last m-1 digits (from right to left) 54 | for (int i=m-1; i>0; i--) 55 | { 56 | // If sum is still greater than 9, 57 | // digit must be 9. 58 | if (s > 9) 59 | { 60 | res[i] = 9; 61 | s -= 9; 62 | } 63 | else 64 | { 65 | res[i] = s; 66 | s = 0; 67 | } 68 | } 69 | 70 | // Whatever is left should be the most significant 71 | // digit. 72 | res[0] = s + 1; // The initially subtracted 1 is 73 | // incorporated here. 74 | 75 | 76 | for (int i=0; i>s>>d; 88 | 89 | findSmallest(d,s); 90 | 91 | 92 | return 0 ; 93 | 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/DuplicateinArray.cpp: -------------------------------------------------------------------------------- 1 | Duplicate in array 2 | Send Feedback 3 | Given an array of integers of size n which contains numbers from 0 to n - 2. Each number is present at least once. That is, if n = 5, numbers from 0 to 3 is present in the given array at least once and one number is present twice. You need to find and return that duplicate number present in the array. 4 | Assume, duplicate number is always present in the array. 5 | Input format : 6 | Line 1 : Size of input array 7 | Line 2 : Array elements (separated by space) 8 | Output Format : 9 | Duplicate element 10 | Constraints : 11 | 1 <= n <= 10^6 12 | Sample Input: 13 | 9 14 | 0 7 2 5 4 7 1 3 6 15 | Sample Output: 16 | 7 17 | 18 | 19 | /*************************************** SOLUTION *********************************************/ 20 | 21 | 22 | // arr - input array 23 | // size - size of array 24 | #include 25 | using namespace std; 26 | 27 | int MissingNumber(int arr[], int size){ 28 | 29 | unordered_map m1; 30 | 31 | for (int i = 0; i < size; ++i) 32 | { 33 | m1[arr[i]]++; 34 | } 35 | 36 | for (int i = 0; i < size; ++i) 37 | { 38 | if (m1[arr[i]] == 2) 39 | { 40 | return arr[i]; 41 | } 42 | } 43 | 44 | return -1; 45 | } 46 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/FindTheUniqueElement.cpp: -------------------------------------------------------------------------------- 1 | Find the Unique Element 2 | Send Feedback 3 | Given an integer array of size 2N + 1. In this given array, N numbers are present twice and one number is present only once in the array. 4 | You need to find and return that number which is unique in the array. 5 | Note : Given array will always contain odd number of elements. 6 | Input format : 7 | Line 1 : Array size i.e. 2N+1 8 | Line 2 : Array elements (separated by space) 9 | Output Format : 10 | Unique element present in the array 11 | Constraints : 12 | 1 <= N <= 10^6 13 | Sample Input : 14 | 7 15 | 2 3 1 6 3 6 2 16 | Sample Output : 17 | 1 18 | 19 | 20 | /*************************************** SOLUTION *********************************************/ 21 | 22 | 23 | // arr - input array 24 | // size - size of array 25 | #include 26 | using namespace std; 27 | int FindUnique(int arr[], int size){ 28 | unordered_map m1; 29 | 30 | for (int i = 0; i < size; ++i) 31 | { 32 | m1[arr[i]]++; 33 | } 34 | 35 | for (int i = 0; i < size; ++i) 36 | { 37 | if (m1[arr[i]]==1) 38 | { 39 | return arr[i]; 40 | } 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/LongestConsecutiveSequence.cpp: -------------------------------------------------------------------------------- 1 | Longest consecutive Sequence 2 | Send Feedback 3 | You are given with an array of integers that contain numbers in random order. Write a program to find the longest possible sequence of consecutive numbers using the numbers from given array. 4 | You need to return the output array which contains consecutive elements. Order of elements in the output is not important. 5 | Best solution takes O(n) time. 6 | If two sequences are of equal length then return the sequence starting with the number whose occurrence is earlier in the array. 7 | Input Format : 8 | Line 1 : Integer n, Size of array 9 | Line 2 : Array elements (separated by space) 10 | Constraints : 11 | 0 <= n <= 10^8 12 | Sample Input 1 : 13 | 13 14 | 2 12 9 16 10 5 3 20 25 11 1 8 6 15 | Sample Output 1 : 16 | 8 17 | 9 18 | 10 19 | 11 20 | 12 21 | Sample Input 2 : 22 | 7 23 | 3 7 2 1 9 8 1 24 | Sample Output 2 : 25 | 7 26 | 8 27 | 9 28 | Explanation: Sequence should be of consecutive numbers. Here we have 2 sequences with same length i.e. [1, 2, 3] and [7, 8, 9], but output should be [7, 8, 9] because the starting point of [7, 8, 9] comes first in input array. 29 | Sample Input 3 : 30 | 7 31 | 15 24 23 12 19 11 16 32 | Sample Output 3 : 33 | 15 34 | 16 35 | 36 | 37 | /*************************************** SOLUTION *********************************************/ 38 | 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | using namespace std; 46 | 47 | vector longestConsecutiveIncreasingSequence(int *arr, int n){ 48 | unordered_map countMap; 49 | vector results; 50 | 51 | for(int i=0;i 28 | using namespace std; 29 | void PairSum(int *input, int n) { 30 | unordered_map m1; 31 | for (int i = 0; i < n; ++i) 32 | { 33 | if(m1[0-input[i]]==0){ 34 | m1[input[i]]++; 35 | 36 | }else{ 37 | m1[input[i]]++; 38 | } 39 | } 40 | 41 | unordered_map::iterator it=m1.begin(); 42 | while(it!=m1.end()){ 43 | int total = 0; 44 | int left = it->second; 45 | int right = m1[-it->first]; 46 | total = left*right; 47 | while(total>0){ 48 | cout << min(it->first, -it->first)<<" "<< max(it->first, -it->first) << '\n'; 49 | total--; 50 | } 51 | m1[it->first]=0; 52 | m1[-it->first]=0; 53 | it++; 54 | 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/RotateArray.cpp: -------------------------------------------------------------------------------- 1 | Rotate array 2 | Send Feedback 3 | You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left). 4 | Note: 5 | Change in the input array/list itself. You don't need to return or print the elements. 6 | Input format : 7 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 8 | 9 | First line of each test case or query contains an integer 'N' representing the size of the array/list. 10 | 11 | Second line contains 'N' single space separated integers representing the elements in the array/list. 12 | 13 | Third line contains the value of 'D' by which the array/list needs to be rotated. 14 | Output Format : 15 | For each test case, print the rotated array/list in a row separated by a single space. 16 | 17 | Output for every test case will be printed in a separate line. 18 | Constraints : 19 | 1 <= t <= 10^4 20 | 0 <= N <= 10^6 21 | 0 <= D <= N 22 | Time Limit: 1 sec 23 | Sample Input 1: 24 | 1 25 | 7 26 | 1 2 3 4 5 6 7 27 | 2 28 | Sample Output 1: 29 | 3 4 5 6 7 1 2 30 | Sample Input 2: 31 | 2 32 | 7 33 | 1 2 3 4 5 6 7 34 | 0 35 | 4 36 | 1 2 3 4 37 | 2 38 | Sample Output 2: 39 | 1 2 3 4 5 6 7 40 | 3 4 1 2 41 | 42 | 43 | /*************************************** SOLUTION *********************************************/ 44 | 45 | 46 | 47 | void swapElements(int *input, int i, int j) { 48 | 49 | int temp = input[i]; 50 | input[i] = input[j]; 51 | 52 | input[j] = temp; 53 | 54 | } 55 | 56 | void reverse(int *input, int start, int end) { 57 | 58 | int i = start, j = end; 59 | 60 | while (i < j) { 61 | 62 | swapElements(input, i, j); 63 | i++; 64 | j--; 65 | } 66 | } 67 | 68 | void rotate(int *input, int d, int n) { 69 | 70 | if (d >= n && n != 0) { 71 | 72 | d = d % n; 73 | 74 | } 75 | 76 | else if (n == 0) { 77 | 78 | return; 79 | 80 | } 81 | 82 | reverse(input, 0, n - 1); 83 | 84 | reverse(input, 0, n - d - 1); 85 | 86 | reverse(input, n - d, n - 1); 87 | 88 | } 89 | -------------------------------------------------------------------------------- /Language Tools + Time and Complexity Assignment/SumMeUp.cpp: -------------------------------------------------------------------------------- 1 | Sum me Up 2 | Send Feedback 3 | There will be ‘t’ test cases having an integer. You have to sum up all the digits of this integer. For e.g. For 6754, the answer will be 6 + 7 + 5 + 4 = 22. 4 | Input Format: 5 | First line will have an integer ‘t’ denoting the number of test cases. 6 | Next ‘t’ lines will have an integer ‘val’ each. 7 | Output format: 8 | Print ‘t’ lines of output denoting the sum of all the digits of the number in each test case. 9 | Constraints: 10 | 1 <= t <= 10^5 11 | 0 <= val <= 10^18 12 | Sample Input: 13 | 2 14 | 1547 15 | 45876 16 | Sample Output: 17 | 17 18 | 30 19 | Explanation: 20 | 1 + 5 + 4 + 7 = 17 21 | 4 + 5 + 8 + 7 + 6 = 30 22 | 23 | 24 | /*************************************** SOLUTION *********************************************/ 25 | 26 | 27 | 28 | #include 29 | using namespace std; 30 | int main() { 31 | int t; 32 | cin>>t; 33 | while(t-->0) { 34 | long n; 35 | cin>>n; 36 | long sum=0; 37 | while(n!=0) { 38 | sum += n % 10; 39 | n=n/10; 40 | } 41 | cout< 33 | using namespace std; 34 | 35 | 36 | void FindTriplet(int arr[], int size, int x) { 37 | sort(arr, arr+size); 38 | //int end = size-1; 39 | for (int i = 0; i < size; i++) 40 | { 41 | int val = x-arr[i]; 42 | int j = i+1; 43 | int k = size-1; 44 | while(jval) 48 | { 49 | k--; 50 | 51 | }else if (arr[j]+arr[k]= j; ptr--) 70 | { 71 | if (arr[ptr] == arr[k]) 72 | { 73 | rightcount++; 74 | }else 75 | break; 76 | } 77 | 78 | int total = leftcount*rightcount; 79 | // cout< 28 | using namespace std; 29 | 30 | 31 | int main( int argc , char ** argv ) 32 | { 33 | ios_base::sync_with_stdio(false) ; 34 | cin.tie(NULL) ; 35 | 36 | string names; 37 | getline(cin, names); 38 | 39 | 40 | stringstream iss(names); 41 | 42 | unordered_map m1; 43 | string temp; 44 | 45 | while(iss>>temp){ 46 | m1[temp]++; 47 | } 48 | 49 | unordered_map :: iterator it=m1.begin(); 50 | int count = 0; 51 | for (it; it != m1.end(); ++it) 52 | { 53 | if(it->second>1){ 54 | cout << it->first<<" "<< it->second << '\n'; 55 | count++; 56 | } 57 | } 58 | if (count == 0) 59 | { 60 | cout << -1 << '\n'; 61 | } 62 | 63 | return 0 ; 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Language Tools/ExtractUniqueChar.cpp: -------------------------------------------------------------------------------- 1 | Extract Unique characters 2 | Send Feedback 3 | Given a string, you need to remove all the duplicates. That means, the output string should contain each character only once. The respective order of characters should remain same. 4 | Input format : 5 | String S 6 | Output format : 7 | Output String 8 | Constraints : 9 | 0 <= Length of S <= 10^8 10 | Sample Input 1 : 11 | ababacd 12 | Sample Output 1 : 13 | abcd 14 | Sample Input 2 : 15 | abcde 16 | Sample Output 2 : 17 | abcde 18 | 19 | /************************************************** SOLUTION ***********************************************/ 20 | 21 | 22 | #include 23 | 24 | string uniqueChar (string str) { 25 | string answer; 26 | unordered_set charSet; 27 | 28 | for (char ch: str) { 29 | if (charSet.find(ch)==charSet.end()) { 30 | answer.push_back(ch); 31 | charSet.insert(ch); 32 | } 33 | } 34 | 35 | return answer; 36 | } 37 | -------------------------------------------------------------------------------- /Language Tools/LoveForChar.cpp: -------------------------------------------------------------------------------- 1 | Love for Characters 2 | Send Feedback 3 | Ayush loves the characters ‘a’, ‘s’, and ‘p’. He got a string of lowercase letters and he wants to find out how many times characters ‘a’, ‘s’, and ‘p’ occurs in the string respectively. Help him find it out. 4 | Input: 5 | First line contains an integer denoting length of the string. 6 | Next line contains the string. 7 | Constraints: 8 | 1<=n<=10^5 9 | ‘a’<= each character of string <= ‘z’ 10 | Output: 11 | Three space separated integers denoting the occurrence of letters ‘a’, ‘s’ and ‘p’ respectively. 12 | Sample Input: 13 | 6 14 | aabsas 15 | Sample output: 16 | 3 2 0 17 | 18 | 19 | /************************************************** SOLUTION ***********************************************/ 20 | 21 | 22 | #include 23 | 24 | using namespace std; 25 | 26 | 27 | int main( int argc , char ** argv ) 28 | { 29 | ios_base::sync_with_stdio(false) ; 30 | cin.tie(NULL) ; 31 | 32 | int n; 33 | cin>>n; 34 | string s; 35 | std::cin>>s; 36 | 37 | unordered_map m1; 38 | 39 | for (int i = 0; i < s.size(); ++i) 40 | { 41 | m1[s[i]]++; 42 | } 43 | 44 | cout << m1['a']<<" "< 28 | 29 | using namespace std; 30 | 31 | class student{ 32 | public: 33 | string name; 34 | int marks; 35 | int roll; 36 | }; 37 | 38 | bool mycompare(student a, student b){ 39 | 40 | if (a.marks!=b.marks) 41 | { 42 | return (a.marks>b.marks); 43 | }else{ 44 | return(a.roll>n; 57 | 58 | //std::vector name; //ncross1 59 | std::vector stud; //ncross3 60 | 61 | for (int i = 0; i < n; ++i) 62 | { 63 | string temp_name; 64 | int sub1; 65 | int sub2; 66 | int sub3; 67 | cin>>temp_name>>sub1>>sub2>>sub3; 68 | 69 | int sum = sub1+sub2+sub3; 70 | 71 | student temp_sub; 72 | 73 | temp_sub.name = temp_name; 74 | temp_sub.marks = sum; 75 | temp_sub. roll = i+1; 76 | 77 | stud.push_back(temp_sub); 78 | } 79 | 80 | 81 | 82 | sort(stud.begin(), stud.end(), mycompare); 83 | 84 | for (int i = 0; i < n; ++i) 85 | { 86 | cout << i+1<<" "< 29 | #include 30 | using namespace std; 31 | int findPlatform(int arr[], int dep[], int n) { 32 | sort(arr, arr+n); 33 | sort(dep, dep+n); 34 | int chair_needed = 1, result = 1; 35 | int i = 1, j = 0; 36 | while (i < n && j < n) { 37 | if (arr[i] <= dep[j]) { 38 | chair_needed++; 39 | i++; 40 | if (chair_needed > result) 41 | result = chair_needed; 42 | } 43 | else { 44 | chair_needed--; 45 | j++; 46 | } 47 | } 48 | return result; 49 | } 50 | int main() { 51 | int n; 52 | cin>>n; 53 | int* arr=new int[n]; 54 | int* dep =new int[n]; 55 | 56 | for(int i=0;i>arr[i]; 58 | } 59 | 60 | for(int i=0;i>dep[i]; 62 | } 63 | 64 | cout<< findPlatform(arr, dep, n); 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /Modulo Arithmetic/NumberOfBalancedBTs.cpp: -------------------------------------------------------------------------------- 1 | Number Of Balanced BTs 2 | Send Feedback 3 | Given an integer h, find the possible number of balanced binary trees of height h. You just need to return the count of possible binary trees which are balanced. 4 | This number can be huge, so return output modulus 10^9 + 7. 5 | Write a simple recursive solution. 6 | Input Format : 7 | Integer h 8 | Output Format : 9 | Count % 10^9 + 7 10 | Input Constraints : 11 | 1 <= h <= 40 12 | Sample Input 1: 13 | 3 14 | Sample Output 1: 15 | 15 16 | Sample Input 2: 17 | 4 18 | Sample Output 2: 19 | 315 20 | 21 | 22 | /********************************************************* SOLUTION *************************************************************************/ 23 | 24 | 25 | 26 | #include 27 | 28 | int balancedBTs(int h) { 29 | 30 | if(h <= 1) { 31 | 32 | return 1; 33 | 34 | } 35 | 36 | int mod = (int) (pow(10, 9)) + 7; 37 | int x = balancedBTs(h - 1); 38 | int y = balancedBTs(h - 2); 39 | int temp1 = (int)(((long)(x)*x) % mod); 40 | int temp2 = (int)((2* (long)(x) * y) % mod); 41 | int ans = (temp1 + temp2) % mod; return ans; 42 | 43 | } 44 | 45 | 46 | /* 47 | #include 48 | using namespace std; 49 | int balancedBTs(int h) { 50 | if(h==0 || h==1){ 51 | return 1; 52 | } 53 | 54 | int m = 1000000000 + 7; //1000000000 = pow(10,9) 55 | int x = balancedBTs(h-1); 56 | int y = balancedBTs(h-2); 57 | 58 | long res1 = (long)x*x; 59 | long res2 = (long)x*y*2; 60 | 61 | int ans1 = (int)(res1%m); 62 | int ans2 = (int)(res2%m); 63 | 64 | int ans = (ans1+ans2)%m; 65 | 66 | return ans; 67 | } 68 | */ 69 | -------------------------------------------------------------------------------- /Prerequisites/Even&Odd_Indexes.cpp: -------------------------------------------------------------------------------- 1 | Even and Odd Indexes 2 | Send Feedback 3 | Given an array of integers, print two integer values: 4 | First, the sum of all numbers which are even as well as whose index are even. 5 | Second, the sum of all numbers which are odd as well as whose index are odd. 6 | Print the two integers space separated. (Arrays is 0-indexed) 7 | Input: 8 | Given an integer denoting the size of array. 9 | Next line will have a line containing ‘n’ space separated integers. 10 | Constraints: 11 | 1<=n<=10^5 12 | 1 <= Ai <= 10^6 13 | Output: 14 | Two space separated integers denoting even and odd sums respectively. 15 | Sample Input: 16 | 5 17 | 2 3 5 1 4 18 | Sample Output: 19 | 6 4 20 | 21 | 22 | /************************************************************************** SOLUTION ****************************************************************************************/ 23 | 24 | 25 | #include 26 | using namespace std; 27 | int main( int argc , char ** argv ) 28 | { 29 | ios_base::sync_with_stdio(false) ; 30 | cin.tie(NULL) ; 31 | 32 | int n; 33 | cin>> n; 34 | int* arr = new int[n]; 35 | int sum1=0, sum2=0; 36 | for (int i = 0; i < n; ++i) 37 | { 38 | int a; 39 | cin>>a; 40 | arr[i] = a; 41 | if(i%2==0 && a%2==0){ 42 | sum1+=a; 43 | }else if(i%2 != 0 && a%2!=0){ 44 | sum2+=a; 45 | } 46 | } 47 | cout << sum1<<" "< 26 | using namespace std; 27 | 28 | int main( int argc , char ** argv ) 29 | { 30 | ios_base::sync_with_stdio(false) ; 31 | cin.tie(NULL) ; 32 | 33 | int n; 34 | cin>>n; 35 | int a[n]; 36 | for(int i=0;i>a[i]; 38 | int profit=0; 39 | for(int i=0;i0) && ((a[j]-a[i])>profit)) 44 | { 45 | profit=a[j]-a[i]; 46 | } 47 | } 48 | } 49 | cout< 28 | using namespace std; 29 | int main() { 30 | int n,sum=0; 31 | cin>>n; 32 | int* arr=new int[n]; 33 | for(int i=0;i>arr[i]; 35 | } 36 | for(int i=0,j=n-1;i 33 | 34 | using namespace std; 35 | 36 | 37 | int main( int argc , char ** argv ) 38 | { 39 | ios_base::sync_with_stdio(false) ; 40 | cin.tie(NULL) ; 41 | 42 | int n,sum; 43 | 44 | cin>> n>>sum; 45 | 46 | int* arr = new int[n]; 47 | for (int i = 0; i < n; ++i) 48 | { 49 | cin>>arr[i]; 50 | } 51 | 52 | int start=0; 53 | int end=0; 54 | int tempsum=arr[end]; 55 | 56 | while(1){ 57 | 58 | if(tempsum==sum){ 59 | cout << "true" << '\n'; 60 | for (int i = start; i <= end; ++i) 61 | { 62 | cout << arr[i]<< " "; 63 | } 64 | return 0; 65 | } 66 | else if (tempsum < sum ) 67 | { 68 | // cout << "imhere" << '\n'; 69 | if (endsum) 84 | { if (startend){ 89 | end++; 90 | tempsum = arr[end]; 91 | } 92 | continue; 93 | } 94 | else{ 95 | cout << "false" << '\n'; 96 | return 0; 97 | } 98 | 99 | } 100 | else if (start == n-1) 101 | { 102 | cout << "false" << '\n'; 103 | return 0; 104 | } 105 | } 106 | return 0 ; 107 | } 108 | -------------------------------------------------------------------------------- /Prerequisites/TotalSum_Boundaries&Diagonals.cpp: -------------------------------------------------------------------------------- 1 | Total Sum on the Boundaries and Diagonals 2 | Send Feedback 3 | For a given two-dimensional square matrix of size (N x N). Find the total sum of elements on both the diagonals and at all the four boundaries. 4 | Input format: 5 | The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. 6 | 7 | First line of each test case or query contains a single integer value, 'N' representing the 'rows' and 'columns' for the two-dimensional square matrix. 8 | 9 | Second line onwards, the next 'N' lines or rows represent the ith row values. 10 | 11 | Each of the ith row constitutes 'N' column values separated by a single space. 12 | Output format: 13 | For each test case, print the single integer denoting the sum. 14 | 15 | Output for every test case will be printed in a seperate line. 16 | Constraints: 17 | 1 <= t <= 10^2 18 | 0 <= N <= 10^3 19 | Time Limit: 1sec 20 | Sample input 1: 21 | 1 22 | 3 23 | 1 2 3 24 | 4 5 6 25 | 7 8 9 26 | Sample Output 1: 27 | 45 28 | Explanation for Sample Output 1: 29 | The boundary elements are 1, 2, 3, 6, 9, 8, 7 and 4. 30 | 31 | The first-diagonal elements are 1, 5 and 9. 32 | 33 | The second-diagonal elements are 3, 5 and 7. 34 | 35 | We just need to add all these numbers making sure that no number is added twice. For example, '1' is both a boundary element and a first-diagonal element similarly, '5' contributes to both the diagonals but they won't be added twice. 36 | 37 | Hence, we add up, [1 + 2 + 3 + 6 + 9 + 8 + 7 + 4 + 5] to give 45 as the output. 38 | Sample input 2: 39 | 2 40 | 5 41 | 1 2 3 4 5 42 | 6 7 8 9 10 43 | 11 12 13 14 15 44 | 16 17 18 19 20 45 | 21 22 23 24 25 46 | 4 47 | 1 2 3 10 48 | 4 5 6 11 49 | 7 8 9 12 50 | 13 14 15 16 51 | Sample Output 2: 52 | 273 53 | 136 54 | 55 | 56 | /************************************************************************** SOLUTION ****************************************************************************************/ 57 | 58 | 59 | int getFirstDiagonalSum(int **input, int n) { 60 | int sum = 0; 61 | for (int i = 0, j = 0; i < n; i++, j++) { 62 | sum += input[i][j]; } return sum; 63 | } 64 | 65 | int getSecondDiagonalSum(int **input, int n) { 66 | 67 | int sum = 0; 68 | 69 | for (int i = 0, j = n - 1; i < n; i++, j--) { 70 | sum += input[i][j]; 71 | } 72 | 73 | return sum; 74 | } 75 | 76 | int getBoundarySum(int **input, int n) { 77 | 78 | int sum = 0; 79 | 80 | for (int i = 1; i < n - 1; i++) { 81 | 82 | sum += input[0][i]; 83 | //Upper boundary 84 | sum += input[n - 1][i]; 85 | //Lower boundary 86 | sum += input[i][0]; 87 | //Left boundary 88 | sum += input[i][n - 1]; 89 | //Right boundary 90 | } 91 | return sum; 92 | } 93 | 94 | int totalSum(int **input, int n) { 95 | 96 | int sum = getFirstDiagonalSum(input, n); 97 | 98 | sum += getSecondDiagonalSum(input, n); 99 | sum += getBoundarySum(input, n); 100 | if (n % 2 != 0) { 101 | 102 | sum -= input[n / 2][n / 2]; 103 | //To avoid double counting of middle element in case of odd 'n' 104 | 105 | } 106 | 107 | return sum; 108 | 109 | } 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eminence - Competitive Programming. Coding Ninjas(Batch: Jaunuary 15, 2020) 2 | # My Offical Website: https://ashhar001.github.io/my-react-portfolio/ 3 | # Repository for storing implementations and solutions of Assignments and Test questions in C++. 4 | # Complete course: Well Organized and sorted. 5 | 6 | ``` 7 | * Here,you'll get solutions to all the lectures problem and assignment problem of the course Competitive Programming Course from Coding Ninjas. 8 | If there's any doubt please put it on the issues list or contact me. 9 | * Coding Ninjas Solution to all the Lecture questions and Assignments. 10 | * You can email at ashar.ansari1020@gmail.com for solutions that are missing or Generate a pull request. 11 | ``` 12 | ## Students: 13 | 14 | Fork this repo or download this, add the codes and the questions to C++ files that are not present and send it to me at ashar.ansari1020@gmail.com Start Open Source Contributions today!!! Needless to say, this adds value to your resume. 15 | 16 | 17 | ### Refer the the link below to get upto Rs.1000 discount on Coding Ninjas Courses 18 | https://classroom.codingninjas.com/app/invite/CHVYN 19 | -------------------------------------------------------------------------------- /Searching & Sorting Applications/AggressiveCowsProblem.cpp: -------------------------------------------------------------------------------- 1 | Aggressive Cows Problem 2 | Send Feedback 3 | Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000). 4 | His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ wants to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance? 5 | Input 6 | t – the number of test cases, then t test cases follows. 7 | * Line 1: Two space-separated integers: N and C 8 | * Lines 2..N+1: Line i+1 contains an integer stall location, xi 9 | Output 10 | For each test case output one integer: the largest minimum distance. 11 | Sample Input : 12 | 1 13 | 5 3 14 | 1 15 | 2 16 | 8 17 | 4 18 | 9 19 | Sample Output: 20 | 3 21 | Output details: 22 | FJ can put his 3 cows in the stalls at positions 1, 4 and 8, 23 | resulting in a minimum distance of 3. 24 | 25 | 26 | 27 | /********************************************************** SOLUTION *******************************************************/ 28 | 29 | #include 30 | using namespace std; 31 | 32 | bool check(int cows,long long positions[],int n,long long distance){ 33 | 34 | int count = 1; 35 | long long last_position = positions[0]; 36 | 37 | for(int i=1;i= distance){ 39 | last_position = positions[i]; 40 | count++; 41 | } 42 | 43 | if(count == cows){ 44 | return true; 45 | } 46 | } 47 | return false; 48 | } 49 | 50 | int main(){ 51 | int t; 52 | cin >> t; 53 | while(t--){ 54 | int n,c; 55 | cin >> n >> c; 56 | 57 | long long positions[n]; 58 | for(int i=0;i> positions[i]; 60 | } 61 | sort(positions,positions+n); 62 | long long start = 0; 63 | long long end = positions[n-1] - positions[0]; 64 | 65 | long long ans = -1; 66 | 67 | while(start<=end){ 68 | long long mid = start + (end-start)/2; 69 | 70 | if(check(c,positions,n,mid)){ 71 | ans = mid; 72 | start = mid+1; 73 | }else{ 74 | end = mid-1; 75 | } 76 | 77 | } 78 | cout << ans < 26 | using namespace std; 27 | 28 | typedef long long ll; 29 | 30 | bool func(ll a[],ll val,ll k,ll n) 31 | { 32 | if(k==1) 33 | return true; 34 | ll sum=0; 35 | for(ll i=n-1;i>=0;i--) 36 | { 37 | sum +=(a[i]/val); 38 | } 39 | if(sum >= k) 40 | return true; 41 | else 42 | return false; 43 | } 44 | void binary_search(ll a[],ll n,ll k) 45 | { 46 | ll lo =1; 47 | ll high =a[n-1]+1; 48 | ll mid=0; 49 | while(high > lo) 50 | { 51 | mid = (lo+high)/2; 52 | if(func(a,mid,k,n)) 53 | lo = mid+1; 54 | else 55 | high = mid; 56 | } 57 | cout<>t; 63 | while(t--){ 64 | ll n,k; 65 | cin>>n>>k; 66 | ll ar[500010]; 67 | 68 | for(ll i = 0;i>ar[i]; 70 | } 71 | sort(ar,ar+n); 72 | binary_search(ar,n,k); 73 | } 74 | return 0; 75 | 76 | } 77 | -------------------------------------------------------------------------------- /Searching & Sorting Applications/InversionCount.cpp: -------------------------------------------------------------------------------- 1 | Inversion Count 2 | Send Feedback 3 | Let A[0 ... n-1] be an array of n distinct positive integers. If i < j and A[i] > A[j] then the pair (i, j) is called an inversion of A (where i and j are indexes of A). Given an integer array A, your task is to find the number of inversions in A. 4 | Input format : 5 | Line 1 : n, array size 6 | Line 2 : Array elements (separated by space). 7 | Output format : 8 | Count of inversions 9 | Constraints : 10 | 1 <= n <= 10^5 11 | 1 <= A[i] <= 10^9 12 | Sample Input 1 : 13 | 3 14 | 3 2 1 15 | Sample Output 1 : 16 | 3 17 | Sample Input 2 : 18 | 5 19 | 2 5 1 3 4 20 | Sample Output 1 : 21 | 4 22 | 23 | 24 | 25 | /********************************************************** SOLUTION *******************************************************/ 26 | 27 | 28 | #include 29 | using namespace std; 30 | 31 | 32 | long long merge(int A[],int left,int mid,int right){ 33 | 34 | int i=left,j=mid,k=0; 35 | 36 | int temp[right-left+1]; 37 | long long count = 0; 38 | while(i left){ 62 | int mid = (left + right)/2; 63 | 64 | long long countLeft = merge_sort(A,left,mid); 65 | long long countRight = merge_sort(A,mid+1,right); 66 | long long myCount = merge(A,left,mid+1,right); 67 | 68 | return myCount + countLeft + countRight; 69 | } 70 | return count; 71 | 72 | } 73 | long long solve(int A[], int n) 74 | { 75 | long long ans = merge_sort(A,0,n-1); 76 | return ans; 77 | } 78 | -------------------------------------------------------------------------------- /Searching & Sorting Applications/MomosMarket.cpp: -------------------------------------------------------------------------------- 1 | Momos Market 2 | Send Feedback 3 | Shreya loves to eat momos. Her mother gives her money to buy vegetables but she manages to save some money out of it daily. After buying vegetables, she goes to "Momos Market", where there are ‘n’ number of shops of momos. Each of the shops of momos has a rate per momo. She visits the market and starts buying momos (one from each shop) starting from the first shop. She will visit the market for ‘q’ days. You have to tell that how many momos she can buy each day if she starts buying from the first shop daily. She cannot use the remaining money of one day on some other day. But she will save them for other expenses in the future, so, you also need to tell the sum of money left with her at the end of each day. 4 | Input Format: 5 | First line will have an integer ‘n’ denoting the number of shops in market. 6 | Next line will have ‘n’ numbers denoting the price of one momo of each shop. 7 | Next line will have an integer ‘q’ denoting the number of days she will visit the market. 8 | Next ‘q’ lines will have one integer ‘X’ denoting the money she saved after buying vegetables. 9 | Constraints: 10 | 1 <= n <= 10^5 11 | 1 <= q <= 10^5 12 | 1 <= X <= 10^9 13 | Output: 14 | There will be ‘q’ lines of output each having two space separated integers denoting number of momos she can buy and amount of money she saved each day. 15 | Sample Input: 16 | 4 17 | 2 1 6 3 18 | 1 19 | 11 20 | Sample Output: 21 | 3 2 22 | Explanation: 23 | Shreya visits the "Momos Market" for only one day. She has 11 INR to spend. She can buy 3 momos, each from the first 3 shops. She would 9 INR (2 + 1 + 6) for the same and hence, she will save 2 INR. 24 | 25 | 26 | /********************************************************** SOLUTION *******************************************************/ 27 | 28 | 29 | #include 30 | using namespace std; 31 | int search(long arr[], int low, int high, long x) { 32 | if(low>high) { 33 | return -1; 34 | } 35 | if(x>=arr[high]) { 36 | return high; 37 | } 38 | int mid=(low+high)/2; 39 | if(arr[mid]==x) { 40 | return mid; 41 | } 42 | if(mid>0 && arr[mid-1]<=x && x>n; 53 | long* arr=new long[n]; 54 | for(int i=0;i>arr[i]; 56 | } 57 | long* prefix=new long[n]; 58 | prefix[0]=arr[0]; 59 | for(int i=1;i>q; 64 | while(q-->0) { 65 | long x; 66 | cin>>x; 67 | int s=search(prefix,0,n-1,x); 68 | long val=x; 69 | if(s!=-1) { 70 | val-=prefix[s]; 71 | } 72 | cout< 41 | 42 | using namespace std; 43 | long long merge(vector &v, long long start, long long mid, long long end){ 44 | 45 | long long sum = 0; 46 | long long i = start; 47 | long long j = mid+1; 48 | 49 | 50 | while(j<=end && i<=mid){ 51 | 52 | if (v.at(j)>v.at(i)) 53 | { 54 | 55 | sum += (end-j+1)*v.at(i); 56 | i++; 57 | }else{ 58 | j++; 59 | } 60 | 61 | } 62 | return sum; 63 | 64 | } 65 | 66 | long long go(vector &v, long long start, long long end){ 67 | 68 | if (start>=end) 69 | { 70 | return 0; 71 | } 72 | long long mid = (start+end)/2; 73 | 74 | long long left = go(v, start, mid); 75 | long long right = go(v, mid+1, end); 76 | 77 | sort(v.begin()+start, v.begin()+mid+1); 78 | sort(v.begin()+mid+1, v.begin()+end+1); 79 | 80 | return left+right+merge(v, start, mid, end); 81 | 82 | } 83 | 84 | 85 | int main( int argc , char ** argv ) 86 | { 87 | ios_base::sync_with_stdio(false) ; 88 | cin.tie(NULL) ; 89 | 90 | long long t; 91 | cin>>t; 92 | 93 | while(t--){ 94 | long long n; 95 | cin>>n; 96 | long long m = n; 97 | 98 | std::vector v; 99 | while(n--){ 100 | long long a; 101 | cin>>a; 102 | v.push_back(a); 103 | } 104 | 105 | cout << go(v, 0, m-1) << '\n'; 106 | } 107 | 108 | return 0 ; 109 | } 110 | -------------------------------------------------------------------------------- /Searching & Sorting Applications/TajMahalEntry.cpp: -------------------------------------------------------------------------------- 1 | Taj Mahal Entry 2 | Send Feedback 3 | Taj Mahal is one of the seven wonders of the world. Aahad loves to travel places and wants to visit Taj Mahal. He visited Agra to view Taj Mahal. There is a ticketing system at Taj Mahal. There are total ‘n’ windows which provide the tickets to get entry into Taj Mahal. There are ‘Ai’ people already present at each window to get the tickets. Each window gives ticket to one person in one minute. Initially, Aahad stands in front of the first window. After each minute, if he didn’t get the ticket, he moves on to the next window to get the ticket. If he is at window 1, he will move to 2. If at 2nd, he will move to 3rd. If he is at last window, he will move to 1st again and so on. Find the window number at which he will get the ticket. 4 | Input Format: 5 | First line contains a single integer ‘n’ denoting the no. of windows. 6 | Next line contains ‘n’ space separated integers denoting the no. of people already standing in front of the ith window. (1 <= i <= n) 7 | Output Format: 8 | Print a single integer denoting the window number that Aahad will get ticket from. 9 | Constraints: 10 | 1 <= n <= 10^5 11 | 1 <= Ai <= 10^9 12 | Sample Input: 13 | 4 14 | 2 3 2 0 15 | Sample Output: 16 | 3 17 | Explanation: 18 | Aahad at Window 1: [2, 3, 2, 0] 19 | Aahad at Window 2: [1, 2, 1, 0] 20 | Aahad at Window 3: [0, 1, 0, 0] 21 | So, when Aahad is at window 3, he got zero people before him. Hence, he will get the ticket at window 3. 22 | 23 | 24 | /********************************************************** SOLUTION *******************************************************/ 25 | 26 | 27 | #include 28 | 29 | using namespace std; 30 | 31 | int go(vector window, int min_index){ 32 | int n = window.size(); 33 | int pos = window.at(min_index)%n; 34 | int min_value = window.at(min_index); 35 | 36 | if (pos==min_index) 37 | { 38 | return min_index; 39 | } 40 | 41 | int cycles = min_value/n; 42 | 43 | for (int i = pos; i < n+pos; ++i) 44 | { 45 | window.at(i%n) = window.at(i%n) - abs(i-pos)-cycles*n-min_value; 46 | if (window.at(i%n)<=0) 47 | { 48 | return i%n; 49 | } 50 | } 51 | 52 | return 0; 53 | 54 | } 55 | 56 | 57 | int main( int argc , char ** argv ) 58 | { 59 | ios_base::sync_with_stdio(false) ; 60 | cin.tie(NULL) ; 61 | 62 | int n; 63 | cin>>n; 64 | //int m = n; 65 | int min_index= 0; 66 | int min_value = INT_MAX; 67 | int h = 0; 68 | 69 | std::vector window; 70 | while(n--){ 71 | int a; 72 | cin>>a; 73 | window.push_back(a); 74 | if (window.at(min_index)>window.at(h)) 75 | { 76 | min_index = h; 77 | min_value = window.at(min_index); 78 | } 79 | h++; 80 | } 81 | 82 | cout << go(window, min_index)+1 << '\n'; 83 | 84 | 85 | 86 | 87 | return 0 ; 88 | 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /Segment Tree/MinimumInSubArray.cpp: -------------------------------------------------------------------------------- 1 | Minimum In SubArray 2 | Send Feedback 3 | Range Minimum Query 4 | Given an array A of size N, there are two types of queries on this array. 5 | 1) q l r: In this query you need to print the minimum in the sub-array A[l:r]. 6 | 2) u x y: In this query you need to update A[x]=y. 7 | Input: 8 | First line of the test case contains two integers, N and Q, size of array A and number of queries. 9 | Second line contains N space separated integers, elements of A. 10 | Next Q lines contain one of the two queries. 11 | Output: 12 | For each type 1 query, print the minimum element in the sub-array A[l:r]. 13 | Contraints: 14 | 1≤N,Q,y≤10^5 15 | 1≤l,r,x≤N 16 | Sample Input : 17 | 5 5 18 | 1 5 2 4 3 19 | q 1 5 20 | q 1 3 21 | q 3 5 22 | u 3 6 23 | q 1 5 24 | Sample Output : 25 | 1 26 | 1 27 | 2 28 | 1 29 | 30 | 31 | 32 | /********************************************** SOLUTION ***************************************************/ 33 | 34 | 35 | 36 | #include 37 | 38 | using namespace std; 39 | 40 | int query(int* tree, int start, int end, int treeNode, int left, int right){ 41 | 42 | //Completely out 43 | if (left>end || right=left && end<=right) 50 | { 51 | return tree[treeNode]; 52 | } 53 | 54 | //Partially inside 55 | int mid = (start+end)/2; 56 | 57 | int l = query(tree, start, mid, 2*treeNode+1, left, right); 58 | int r= query(tree, mid+1, end, 2*treeNode+2, left, right); 59 | 60 | return min(l, r); 61 | } 62 | 63 | 64 | void update(int* arr, int* tree, int start, int end, int treeNode, int idx, int value){ 65 | int mid = (start+end)/2; 66 | 67 | if (start == end) 68 | { 69 | arr[idx] = value; 70 | tree[treeNode] = value; 71 | return; 72 | } 73 | 74 | if (idx<=mid) 75 | { 76 | update(arr, tree, start, mid, 2*treeNode+1, idx, value); 77 | }else{ 78 | 79 | update(arr, tree, mid+1, end, 2*treeNode+2, idx, value); 80 | } 81 | 82 | tree[treeNode] = min(tree[2*treeNode+1], tree[2*treeNode+2]); 83 | } 84 | 85 | 86 | void create(int* arr, int* tree, int start, int end, int treeNode){ 87 | if (start == end) 88 | { 89 | tree[treeNode] = arr[start]; 90 | return; 91 | } 92 | 93 | int mid = (start+end)/2; 94 | 95 | create(arr, tree, start, mid, 2*treeNode+1); 96 | create(arr, tree, mid+1, end, 2*treeNode+2); 97 | 98 | tree[treeNode] = min(tree[2*treeNode+1], tree[2*treeNode+2]); 99 | return; 100 | } 101 | 102 | int main( int argc , char ** argv ) 103 | { 104 | ios_base::sync_with_stdio(false) ; 105 | cin.tie(NULL) ; 106 | 107 | int n, q; 108 | cin>>n>>q; 109 | 110 | int* arr = new int[n]; 111 | for (int i = 0; i < n; ++i) 112 | { 113 | cin>>arr[i]; 114 | } 115 | 116 | int* tree = new int[4*n]; 117 | 118 | create(arr, tree, 0, n-1, 0); 119 | 120 | 121 | 122 | while(q--){ 123 | char a; 124 | int b, c; 125 | cin>>a>>b>>c; 126 | 127 | if (a=='q') 128 | { 129 | cout << query(tree, 0, n-1, 0, b-1, c-1) << '\n'; 130 | }else{ 131 | update(arr, tree, 0, n-1, 0, b-1, c); 132 | } 133 | 134 | } 135 | 136 | 137 | return 0 ; 138 | 139 | 140 | 141 | } 142 | -------------------------------------------------------------------------------- /String Algorithms/StringSearch.cpp: -------------------------------------------------------------------------------- 1 | String Search 2 | Send Feedback 3 | Given two strings S and T, write a function to find if T is present as a substring inside S or not. If yes, return the starting index otherwise return -1. 4 | Input format : 5 | 6 | Line 1 : String S 7 | 8 | Line 2 : String T 9 | 10 | Sample Input 1: 11 | WelcomeBack 12 | come 13 | Sample Output 1: 14 | 3 15 | Sample Input 2: 16 | WelcomeBack 17 | code 18 | Sample Output 2: 19 | -1 20 | 21 | 22 | /*********************************** SOLUTION ********************************************/ 23 | 24 | 25 | #include 26 | using namespace std; 27 | typedef long long ll; 28 | typedef unordered_map umapii; 29 | typedef unordered_map umapib; 30 | typedef unordered_map umapsi; 31 | typedef unordered_map umapss; 32 | typedef map mapsi; 33 | typedef map, int> mappiii; 34 | typedef map mapii; 35 | typedef pair pii; 36 | typedef pair pll; 37 | typedef unordered_set useti; 38 | 39 | #define uset unordered_set 40 | #define it iterator 41 | #define mp make_pair 42 | #define pb push_back 43 | #define all(x) (x).begin(), (x).end() 44 | #define f first 45 | #define s second 46 | #define MOD 1000000007 47 | 48 | 49 | int findString(char S[], char T[]) { 50 | int length = strlen(T); 51 | int n = strlen(S); 52 | 53 | 54 | vector pitable(length, 0); 55 | int i = 0; 56 | int j = i+1; 57 | 58 | while(j