├── .all-contributorsrc ├── Arrays ├── ASmallerTeam.cpp ├── ASortedTeam.cpp ├── ArrayHill.cpp ├── ArrayRotation.cpp ├── AssigningMicetoHoles.py ├── BaruaRankReversal.py ├── BlissfulPairs.cpp ├── Cashew Conjecture(Prime No Based).c ├── CoinFlip.py ├── Consecutive Prime Sum.cpp ├── GasStations.py ├── Greatest Number with the Digits.py ├── HappySighting.cpp ├── Hourglass Sum.cpp ├── Kefa hates coins.cpp ├── LargestContiguousSumSubarray.py ├── LeftRotation.py ├── MinUniqueSum.py ├── NewCustomerAtElectronicsStore.cpp ├── NextGreaterElement.py ├── PuccaAndTheCardGame.cpp ├── ReplaceArray.cpp ├── ReplaceTheArray.cpp ├── Search_in_rotated_Sorted_array.cpp ├── SecretSanta.c ├── ShortestManOnTheTeam.cpp ├── TheElectronicStore.cpp ├── TrickOrTreat.cpp ├── ValidateSudoku.cpp ├── WaveArray.py └── matrixoperationusing2d.cpp ├── Backtracking └── NQueens.cpp ├── CONTRIBUTING.md ├── Dynamic Programming ├── Cut_Ribbon.java ├── Kadane_LargestSumContArray.cpp ├── LCS.cpp ├── LargestContiguousSumSubarray.py ├── MaxArraySum_NonAdjacent.py ├── MaxSizeSquareSubMatrix.cpp ├── MinAvgSubarray.cpp ├── NonDecreaseSubarray.py └── ZeroOneKnapsack.cpp ├── Greedy Algorithms ├── ActivitySelectionProblem.cpp ├── AutonomousCar.cpp ├── EatLessCupcakes.c ├── GreedyFlorist.py ├── JumpGame.cpp ├── KnapsackUsingArray.cpp ├── KnapsackUsingDictionaries.py ├── KnapsackUsingStruct.cpp ├── LargestNumberGivenDigitsAndSum.py └── SmallestNumberGivenDigitsAndSum.py ├── Hash table └── Group_anagrams.cpp ├── Linked Lists ├── Circular Linked List │ ├── CLL - Deletions.c │ └── CLL - Insertions.c ├── Doubly Linked List │ ├── DLL - All_Insertions.c │ ├── DLL - Deletions.c │ └── DequeLL.c └── Singly Linked List │ ├── Deletion at Any Position.c │ ├── Deletion at Ending.c │ ├── Deletion at beginning.c │ ├── FindLoopAndMidElement.cpp │ ├── Harry Potter and the Half Blood Prince.c │ ├── Insertion At Beginning.c │ ├── Insertion at any position.c │ ├── Linked List Deletions.c │ ├── Linked Lists Insertions.c │ ├── Linked Lists-Searching.c │ ├── LoopCheck.c │ ├── PalindromeCheck.c │ ├── Printing in reverse.c │ └── Reversing and Printing.c ├── Miscellaneous ├── 7DivisiblePairs.cpp ├── AccrualSystem.py ├── ConfusedInteger.cpp ├── ConsecutivePrimeSum.cpp ├── Counting Valleys.py ├── DigitsInFactorial.py ├── EsotericChairs.py ├── Factors57.py ├── HourGlass problem.c ├── Jumping on the Clouds.cpp ├── Kangaroo.cpp ├── NobleInteger.py ├── NotExactlyGCD.c ├── ParliamentSquare.py ├── ResetButtons.cpp ├── ResidueArithmetic.cpp ├── SquareInACircle.c ├── SumOfPairs.py ├── SumOfPrimes.cpp ├── TrailingZerosOfFactorial.py └── XOR.py ├── Patterns ├── AlphabetRangoli.py ├── BoxPattern.cpp ├── DesignerDoorMat.py ├── GreatPattern.py ├── PascalTriangle.cpp ├── Pattern1.py ├── Pattern2.py ├── Pattern3.py ├── Prime pyramid.cpp ├── PyramidByNumericals.py ├── SpiralMatrix.cpp ├── String Repetition.cpp └── SubwayRunners.cpp ├── Pointers ├── Nested2DPointers.c └── PointerArrays2D.c ├── Queue ├── DownToZero.cpp ├── StackUsingQueues.cpp └── The Circular Queue.c ├── README.md ├── Recursion ├── Fibonacci.py ├── JumpingOnClouds.py ├── MinimumNumberFunction.cpp ├── RecursiveInsertionSort.py ├── SumOfAllDigits.cpp ├── SumOfAllDigits.py ├── Tower_of_Hanoi.c ├── combinationStrings.cpp ├── gcd.cpp ├── powersum.cpp └── rat-in-a-maze-CPP.cpp ├── Sorting Techniques ├── AllSortingTechniques.cpp ├── DateSorting.cpp ├── Quick Sort.cpp └── Structures date sorting.cpp ├── Stacks ├── BalancedParenthesis.cpp ├── Harry Potter and the Sorceror's Stone.c ├── Harry Potter and the Sorceror's Stone.cpp ├── HistogramArea.cpp ├── MaxElementInStackArrays.c ├── MaxElementInStackLinkedLists.c ├── ParenthesisDepth.cpp ├── QueueUsingStacks.cpp └── Stacks_Using_LinkedLists.cpp ├── Strings ├── AmazingSubarrays.py ├── BinaryStringDuplication.py ├── CapitalizeFirstLetterName.py ├── CharCompression.cpp ├── CharCompression.py ├── ContactsApplication.py ├── DiscoverTheRightCharacter.cpp ├── DiscoverTheRightNumber.py ├── DiscoverTheSubstring.java ├── DiscoverTheSubstring.py ├── Lapindrome.py ├── MinimizeWasteCells.cpp ├── MinimizeWasteCells.py ├── Repeated String.py ├── ReverseVowels.cpp ├── StringConcatenation.cpp ├── StringConversion.cpp ├── allTrim.c ├── leftTrim.c └── rightTrim.c ├── Structures ├── EmployeeSheetSTL.cpp └── Structures date sorting.cpp └── Trees ├── BST Traversals.c ├── HeightOfBinaryTree.c ├── HuffmanDecoding.cpp ├── InOrder.c ├── PostOrder.c ├── PostOrderFromPreAndInorder.cpp ├── PreOrder.c └── TraversalsAndHeight.cpp /Arrays/ASmallerTeam.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A Smaller Team 3 | 4 | The coach from the previous problem has now changed his mind. He only wants to take n-k people into the team. He asks the first person in the line to go find the shortest person and switch places with him. He then asks the second person in line to go find the second shortest person and switch places with him. So on, until the kth person has switched with the Kth shortest person in front of the line. 5 | 6 | Formally, swap the first element of the array with the smallest element of the array, then second element of the array with the second smallest element in the array and so on. Repeat this process k times. 7 | 8 | INPUT 9 | 10 | The first line of input is n (1≤n≤100), the number of applicants for the basketball team The second line of input is the heights of the n players (distinct positive numbers) each separated by a space. The third line of input is the number k (1≤k≤n) 11 | 12 | OUTPUT 13 | 14 | Print the heights of the players in a line after the k switches are complete. 15 | 16 | Sample Input 0 17 | 18 | 7 19 | 4 9 6 3 1 7 5 20 | 4 21 | Sample Output 0 22 | 23 | 1 3 4 5 6 7 9 24 | */ 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | int main() { 32 | int a,m,k; 33 | cin>>a; 34 | int b[a]; 35 | for(int i=0; i>b[i]; 37 | int c; 38 | cin>>c; 39 | for(int i=0; ib[j]) 45 | { 46 | m=j; 47 | } 48 | } 49 | k=b[m]; 50 | b[m]=b[i]; 51 | b[i]=k; 52 | } 53 | for(int i=0; i 24 | #include 25 | #include 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | 31 | int main() { 32 | int a; 33 | cin>>a; 34 | int b[a]; 35 | for(int i=0; i>b[i]; 37 | sort(b,b+a); 38 | for(int i=0; i 27 | #include 28 | #include 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | 34 | int main() { 35 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 36 | int n,i,max=0,pos,flag=1; 37 | cin>>n; 38 | int arr[n]; 39 | for(i=0;i>arr[i]; 42 | if(arr[i]>=max) 43 | { 44 | max=arr[i]; 45 | pos=i; 46 | } 47 | } 48 | for(i=1;im): 43 | m=ct 44 | print(m) -------------------------------------------------------------------------------- /Arrays/BaruaRankReversal.py: -------------------------------------------------------------------------------- 1 | # Barua and his Rank Reversal 2 | 3 | # You've been given a permutation of containing N distinct elements between 1 and N, both included. (1<=N<=10^3) 4 | # The rank of an element in this array is the number of elements to it's left which are strictly lesser than it. 5 | # You have been given array,formulate it's rank array. 6 | # Seems tough right? Let's make the question a bit simpler :P 7 | 8 | # Instead of the actual array, you would be given a rank array. Formulate the initial array from it. It is guaranteed 9 | # that the solution would be unique. 10 | 11 | # Input Format 12 | # In the first line input N(1<=N<=10^3) 13 | # In the next line input rank array 0<=Rank[i] 14 | 15 | # Output Format 16 | # Print the N integers of the actual array. 17 | 18 | # NOTE : All elements in the rank array may or may not be distinct 19 | 20 | # Sample Input 0 21 | 22 | # 3 23 | # 0 1 2 24 | # Sample Output 0 25 | 26 | # 1 2 3 27 | # Explanation 0 28 | 29 | # If the actual array is : 1 2 3 30 | # Rank array will be : 0 1 2 Thus it satisfies the provided input. 31 | # Because there are 0 elements to the left of 1 which are lesser than 1, 1 element to the left of 2 which is lesser than 32 | # 2 and 2 elements to the left of 3 which are lesser than 3. 33 | 34 | # Enter your code here. Read input from STDIN. Print output to STDOUT 35 | 36 | n = int(input()) 37 | l = [x for x in range(1,n+1)] 38 | # print(l) 39 | mylist = [x for x in range(1,n+1)] 40 | # print(mylist) 41 | 42 | res = [] 43 | 44 | for i in range(n): 45 | pos=ranks[n-i-1] 46 | res.append(mylist[pos]) 47 | mylist.pop(pos) 48 | for x in range(n-1,-1,-1): 49 | print(res[x],end=" ") -------------------------------------------------------------------------------- /Arrays/BlissfulPairs.cpp: -------------------------------------------------------------------------------- 1 | /*Given a permutation of number from 1 to N. Among all the subarrays, find the number of unique pairs (a,b) such that a≠b and a is maximum and b is second maximum in that subarray. 2 | 3 | Input Format 4 | 5 | First line contains an integer, N. 6 | Second line contains N space separated distinct integers, Ai, denoting the permutation. 7 | 8 | Constraints 9 | 10 | 1≤N≤10^5 11 | 1≤Ai≤N 12 | 13 | Output Format 14 | 15 | Print the required answer. 16 | 17 | Sample Input 0 18 | 19 | 5 20 | 1 2 3 4 5 21 | 22 | Sample Output 0 23 | 24 | 4 25 | 26 | Explanation 0 27 | 28 | All possible subarrays are : 29 | 1 30 | 1 2 31 | 1 2 3 32 | 1 2 3 4 33 | 1 2 3 4 5 34 | 2 35 | 2 3 36 | 2 3 4 37 | 2 3 4 5 38 | 3 39 | 3 4 40 | 3 4 5 41 | 4 42 | 4 5 43 | 5 44 | 45 | The 4 unique pairs are : 46 | (2, 1) 47 | (3, 2) 48 | (4, 3) 49 | (5, 4) */ 50 | 51 | #include 52 | #include 53 | #include 54 | #include 55 | #include 56 | using namespace std; 57 | 58 | 59 | int main() { 60 | int n; cin>>n; 61 | int a[n]; 62 | for(int i=0;i>a[i]; 64 | 65 | int count=0; 66 | 67 | for(int i=0;ia[j] && a[j]>max) 80 | { 81 | max=a[j]; 82 | count++; 83 | } 84 | else continue; 85 | } 86 | } 87 | 88 | cout< 22 | #include 23 | #include 24 | #include 25 | #include 26 | using namespace std; 27 | 28 | int isPrime(int n) 29 | { 30 | for(int i=2;i<=(int)sqrt(n);i++) 31 | { 32 | if(n%i==0) 33 | return 0; 34 | } 35 | return 1; 36 | } 37 | 38 | int main() { 39 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 40 | int i,j,n,ct=0,sum=2; 41 | cin>>n; 42 | for(i=3;sumsg: 40 | print("-1") 41 | else: 42 | tank=0 43 | pos=-1 44 | count=0 45 | i=0 46 | while(True): 47 | if tank==0: 48 | tank+=gas[i] 49 | if i!=len(gas)-1: 50 | if tank-cost[i]>=0: 51 | tank=tank-cost[i]+gas[i+1] 52 | count=count+1 53 | if count==len(gas): 54 | pos=i+1 55 | break 56 | i=i+1 57 | else: 58 | if count==len(gas)-1: 59 | break 60 | else: 61 | tank=0 62 | count=0 63 | i+=1 64 | else: 65 | if tank-cost[i]>=0: 66 | tank=tank-cost[i]+gas[0] 67 | count+=1 68 | i=0 69 | if(count==n): 70 | pos=i 71 | break 72 | else: 73 | break 74 | print(pos) 75 | -------------------------------------------------------------------------------- /Arrays/Greatest Number with the Digits.py: -------------------------------------------------------------------------------- 1 | #Given a number N, find the largest number that you can form with its digits. 2 | #You are allowed to rearrange the digits in any way you wish as long as the resultant number does not contain any leading zeroes. 3 | 4 | #Input Format 5 | 6 | #Only one line of input with number N. 7 | 8 | #Constraints 9 | 10 | #1 <= N <= 10^9 11 | 12 | #Output Format 13 | 14 | #Output one number, which is the largest possible number that can be formed with the digits of N. 15 | 16 | #Sample Input 0 17 | 18 | #5318008 19 | 20 | #Sample Output 0 21 | 22 | #8853100 23 | 24 | #code:- 25 | 26 | n = int(input()) 27 | l = [] 28 | while(n): 29 | x = n % 10 30 | l.append(x) 31 | n = n // 10 32 | m = l[0] 33 | le = len(l) 34 | l.sort(reverse = True) 35 | 36 | for i in range(le): 37 | print(l[i], end ='') 38 | -------------------------------------------------------------------------------- /Arrays/HappySighting.cpp: -------------------------------------------------------------------------------- 1 | /*1. There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. 2 | 3 | We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last. In other words, we are allowed to rearrange elements of array a in any order. What is the maximum possible number of indices i (1 <= i <= n - 1), such that ai + 1 > ai. 4 | 5 | Input Format 6 | 7 | The first line of the input contains integer n — the number of painting. 8 | 9 | The second line contains the sequence a1, a2, ..., an, where ai means the beauty of the i-th painting. 10 | 11 | Constraints 12 | 13 | 1 <= n <= 1000 14 | 1 <= ai <= 1000 15 | 16 | Output Format 17 | 18 | Print one integer — the maximum possible number of neighbouring pairs, such that ai + 1 > ai, after the optimal rearrangement. 19 | 20 | 21 | input 22 | 5 23 | 20 30 10 50 40 24 | output 25 | 4 26 | input 27 | 4 28 | 200 100 100 200 29 | output 30 | 2 31 | */ 32 | 33 | 34 | 35 | 36 | 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | using namespace std; 44 | int main() { 45 | int a, k; 46 | cin >> a; 47 | int b[a]; 48 | for (int i = 0; i < a; i++) { 49 | cin >> b[i]; 50 | } 51 | sort(b, b + a); 52 | for (int i = 1; i < a; i++) { 53 | for (int j = i; j < a; j++) { 54 | if (b[i-1] < b[j]) { 55 | k=b[j]; 56 | for(int k=j; k>i; k--) { 57 | b[k]=b[k-1]; 58 | } 59 | b[i]=k; 60 | break; 61 | } 62 | } 63 | } 64 | k=0; 65 | for (int i = 1; i < a; i++) { 66 | if (b[i]>b[i-1]) { 67 | k++; 68 | } 69 | } 70 | cout< 50 | #include 51 | #include 52 | #include 53 | #include 54 | using namespace std; 55 | 56 | 57 | int main() { 58 | int n, m; 59 | cin>>n>>m; 60 | int a[n], p[m], i, j, count=0; 61 | for(i = 0;i < n; i++) 62 | { 63 | cin>>a[i]; 64 | count = count+a[i]; 65 | } 66 | for(i = 0;i < m; i++) 67 | cin>>p[i]; 68 | sort(a, a+n); 69 | int pos = 0; 70 | for(i = 0; i < m; i++) 71 | { 72 | int x = 0,flag = 0,j = pos,c = 0; 73 | while(j= p[i]) 78 | { 79 | pos = j + 1; 80 | flag = 1; 81 | break; 82 | } 83 | j++; 84 | } 85 | if(flag == 1) 86 | { 87 | cout<= a: 26 | pos = pos % a 27 | newl.append(li[pos]) 28 | for i in newl: 29 | print(i, end=' ') 30 | -------------------------------------------------------------------------------- /Arrays/MinUniqueSum.py: -------------------------------------------------------------------------------- 1 | # Minimum Unique Array Sum 2 | 3 | # If any element has a duplicate in the array, increment it by 1 until no 2 elements are the same in the array. 4 | # Find the sum of all the array elements once all elements are unique. 5 | 6 | # Sample Input: [3,1,3,5,7] 7 | # Output: 20 8 | 9 | # Explanation: 10 | # arr = [3,1,3,5,7] 11 | # arrunique = [3,1,4,5,7] 12 | # sum = 20 13 | 14 | 15 | #!/bin/python3 16 | 17 | import math 18 | import os 19 | import random 20 | import re 21 | import sys 22 | 23 | 24 | 25 | # 26 | # Complete the 'getMinimumUniqueSum' function below. 27 | # 28 | # The function is expected to return an INTEGER. 29 | # The function accepts INTEGER_ARRAY arr as parameter. 30 | # 31 | 32 | def getMinimumUniqueSum(arr): 33 | # Write your code here 34 | l = [] 35 | s = 0 36 | for i in arr: 37 | if i not in l: 38 | print('appended',i) 39 | l.append(i) 40 | s+=i 41 | else: 42 | while i in l: 43 | i+=1 44 | l.append(i) 45 | print('appended',i) 46 | s+=i 47 | return s 48 | 49 | if __name__ == '__main__': 50 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 51 | 52 | arr_count = int(input().strip()) 53 | 54 | arr = [] 55 | 56 | for _ in range(arr_count): 57 | arr_item = int(input().strip()) 58 | arr.append(arr_item) 59 | 60 | result = getMinimumUniqueSum(arr) 61 | 62 | fptr.write(str(result) + '\n') 63 | 64 | fptr.close() 65 | -------------------------------------------------------------------------------- /Arrays/NewCustomerAtElectronicsStore.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The server is finally happy that he sorted the line and now he gets to sell his portable chargers. But alas, a new person enters with a battery percentage of k comes to the store and stands at the back of the queue. Now he has to fit him in this already ascending ordered queue. He asks for your help. 3 | 4 | Formally, you are given an array of size n where the first n - 1 elements are sorted in ascending order and the last element can be any value. Sort this array by sliding the last element into its correct position. 5 | 6 | INPUT 7 | 8 | The first line of input is n (1≤n≤100), the number of customers in the queue. The second line of input is the battery percentages of the n customers (positive numbers less than 100) 9 | the first n - 1 of which are standing in ascending order according to their battery percentage. 10 | 11 | OUTPUT 12 | 13 | Print the battery percentages of the customers in a line after the new person has been put in his right place in the queue. 14 | 15 | Sample Input 0 16 | 17 | 6 18 | 1 3 5 7 9 4 19 | Sample Output 0 20 | 21 | 1 3 4 5 7 9 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | using namespace std; 30 | 31 | 32 | int main() { 33 | int a,k; 34 | cin>>a; 35 | int b[a]; 36 | for(int i=0; i>b[i]; 38 | for(int i=0; i1; i--) 41 | { 42 | if(b[i]>b[i+1]) 43 | { 44 | k=b[i]; 45 | b[i]=b[i+1]; 46 | b[i+1]=k; 47 | } 48 | } 49 | } 50 | for(int i=0; i 5 12 | # 5 --> 25 13 | # 2 --> 25 14 | # 25 --> -1 15 | # d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows. 16 | 17 | # Element NGE 18 | # 13 --> -1 19 | # 7 --> 12 20 | # 6 --> 12 21 | # 12 --> -1 22 | 23 | 24 | # cook your dish here 25 | arr = list(map(int,input().split())) 26 | 27 | for i in range(0,len(arr),1): 28 | next = -1 29 | for j in range(i+1,len(arr),1): 30 | if arr[i] 41 | #include 42 | #include 43 | #include 44 | #include 45 | using namespace std; 46 | 47 | 48 | int main() { 49 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 50 | int n,i,low,high; 51 | cin>>n; 52 | int arr[n]; 53 | int pucca=0; 54 | int garu=0; 55 | for(i=0;i>arr[i]; 57 | low=0; 58 | high=n-1; 59 | while(low=arr[high]) 62 | { 63 | if((low+high)%2!=0) 64 | pucca+=arr[low]; 65 | else 66 | garu+=arr[low]; 67 | low++; 68 | } 69 | else 70 | { 71 | if((low+high)%2!=0) 72 | pucca+=arr[high]; 73 | else 74 | garu+=arr[high]; 75 | high--; 76 | } 77 | } 78 | // cout<<"Pucca:"<=garu) 80 | cout<<"Pucca"; 81 | else 82 | cout<<"Garu"; 83 | return 0; 84 | } -------------------------------------------------------------------------------- /Arrays/ReplaceArray.cpp: -------------------------------------------------------------------------------- 1 | // Replace The Array 2 | 3 | // Given an array of integers, replace every element with the greatest element on the right side in the array. Replace last element with 0 as there no element on the right side of it. 4 | 5 | // Input Format 6 | 7 | // First line contains N , the number of Numbers. Next line contains N integers a[1]..a[n] the numbers 8 | 9 | // Constraints 10 | 11 | // 1<= N <= 10^5 12 | // 1<= ai <= 10^5 13 | 14 | // Output Format 15 | 16 | // Print the array required 17 | 18 | // Sample Input 0 19 | 20 | // 6 21 | // 6 7 4 3 5 2 22 | // Sample Output 0 23 | 24 | // 7 5 5 5 2 0 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | 34 | int main() { 35 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 36 | int n,i; 37 | cin>>n; 38 | int arr[n]; 39 | for(i=0;i>arr[i]; 41 | int max=arr[n-1]; 42 | arr[n-1]=0; 43 | for(i=n-2;i>=0;i--) 44 | { 45 | if(arr[i]>max) 46 | { 47 | int temp=arr[i]; 48 | arr[i]=max; 49 | max=temp; 50 | } 51 | else 52 | { 53 | arr[i]=max; 54 | } 55 | } 56 | for(i=0;i 26 | #include 27 | #include 28 | #include 29 | #include 30 | using namespace std; 31 | 32 | 33 | int main() { 34 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 35 | int n; 36 | cin>>n; 37 | int a[n]; 38 | for(int i=0; i>a[i]; 40 | 41 | int max = a[n-1]; 42 | int b[n]; 43 | b[n-1] = 0; 44 | 45 | for(int i=n-2; i>=0; i--) 46 | { 47 | b[i] = max; 48 | if(max < a[i]) 49 | max = a[i]; 50 | } 51 | for(int i=0; i& nums, int target) 22 | { 23 | while (nums.size()>1 && nums.back()==nums[0]) 24 | nums.pop_back(); 25 | 26 | int left = 0; 27 | int right = nums.size()-1; 28 | 29 | while (left=nums[0] == target>=nums[0]) 36 | { 37 | if (nums[mid]=nums[0]) 43 | right = mid-1; 44 | else 45 | left = mid+1; 46 | } 47 | 48 | if (left==right && nums[left]==target) 49 | return true; 50 | else 51 | return false; 52 | } 53 | }; -------------------------------------------------------------------------------- /Arrays/SecretSanta.c: -------------------------------------------------------------------------------- 1 | // Bug's friends play Secret Santa. He has n friends. Lets number them from 1 to n. 2 | // For each friend i he knows pi, the person that i gave a gift to. 3 | // Bug needs to find out ri for each friend i, which is the person that i received a gift from. 4 | 5 | // Input Format 6 | 7 | // First line contains one number n. Second line contains n space separated integers. 8 | 9 | // Constraints 10 | 11 | // 1 <= n <= 100 12 | 13 | // Output Format 14 | 15 | // Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i. 16 | 17 | // Sample Input: 18 | 19 | // 4 20 | // 2 3 4 1 21 | 22 | // Sample Output: 23 | 24 | // 4 1 2 3 25 | 26 | // Explanation: 27 | // Ouput is 28 | 29 | // 4 : because 1 received a gift from 4 30 | 31 | // 1 : because 2 received a gift from 1 32 | 33 | // 2 : because 3 received a gift from 2 34 | 35 | // 3 : because 4 received a gift from 3 36 | 37 | 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | int main() { 44 | int n; 45 | scanf("%d", &n); 46 | int arr[n], b[n]; 47 | int count = 0; 48 | for(int i = 0; i 24 | #include 25 | #include 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | 31 | int main() { 32 | int a; 33 | cin>>a; 34 | int b[a]; 35 | for(int i=0; i>b[i]; 37 | int m; 38 | m=0; 39 | for(int i=0; ib[i]) 42 | m=i; 43 | } 44 | int k; 45 | k=b[0]; 46 | b[0]=b[m]; 47 | b[m]=k; 48 | for(int i=0; i 27 | #include 28 | #include 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | 34 | int main() { 35 | int a,k; 36 | cin>>a; 37 | int b[a]; 38 | for(int i=0; i>b[i]; 40 | for(int i=0; ib[i+1]) 45 | { 46 | k=b[i]; 47 | b[i]=b[i+1]; 48 | b[i+1]=k; 49 | } 50 | } 51 | } 52 | for(int i=0; i 32 | #include 33 | #include 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | 39 | int main() { 40 | int a; 41 | cin>>a; 42 | int b[a]; 43 | for(int i=0; i>b[i]; 45 | int c; 46 | cin>>c; 47 | int d[c]; 48 | for(int i=0; i>d[i]; 50 | for(int i=0; i= a2 <= a3 >= a4 <= a5..... 4 | 5 | # Example 6 | 7 | # Given [1, 2, 3, 4] 8 | 9 | # One possible answer : [2, 1, 4, 3] 10 | # Another possible answer : [4, 1, 3, 2] 11 | # NOTE : If there are multiple answers possible, return the one thats lexicographically smallest. 12 | # So, in example case, you will return [2, 1, 4, 3] 13 | 14 | 15 | class Solution: 16 | def wave(self, A): 17 | # Sort 18 | A = sorted(A) 19 | i = 0 20 | size = len(A) 21 | # Swapping neighbors 22 | while(i < size - 1): 23 | A[i], A[i + 1] = A[i + 1], A[i] 24 | i += 2 25 | return A 26 | -------------------------------------------------------------------------------- /Backtracking/NQueens.cpp: -------------------------------------------------------------------------------- 1 | /*Problem Name: NQueens 2 | 3 | Problem Description: 4 | The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. 5 | Given an integer n, return all distinct solutions to the n-queens puzzle. 6 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 7 | There exist two distinct solutions to the 4-queens puzzle as shown above. 8 | 9 | INPUT: 4 10 | 11 | OUTPUT: 12 | [ #Solution1 13 | [".Q..", 14 | "...Q", 15 | "Q...", 16 | "..Q."], 17 | 18 | CONSTRAINTS: 19 | 20 | Sample input: 4 21 | 22 | Sample output: 23 | ["..Q.", 24 | "Q...", #solution2 25 | "...Q", 26 | ".Q.."] 27 | ]*/ 28 | 29 | 30 | 31 | 32 | 33 | #include 34 | using namespace std; 35 | #define N 4 36 | void printBoard(int board[N][N]) { 37 | for (int i = 0; i < N; i++) { 38 | for (int j = 0; j < N; j++) 39 | cout << board[i][j] << " "; 40 | cout << endl; 41 | } 42 | } 43 | bool isValid(int board[N][N], int row, int col) { 44 | for (int i = 0; i < col; i++) //check whether there is queen in the left or not 45 | if (board[row][i]) 46 | return false; 47 | for (int i=row, j=col; i>=0 && j>=0; i--, j--) 48 | if (board[i][j]) //check whether there is queen in the left upper diagonal or not 49 | return false; 50 | for (int i=row, j=col; j>=0 && i= N) //when N queens are placed successfully 57 | return true; 58 | for (int i = 0; i < N; i++) { //for each row, check placing of queen is possible or not 59 | if (isValid(board, i, col) ) { 60 | board[i][col] = 1; //if validate, place the queen at place (i, col) 61 | if ( solveNQueen(board, col + 1)) //Go for the other columns recursively 62 | return true; 63 | board[i][col] = 0; //When no place is vacant remove that queen 64 | } 65 | } 66 | return false; //when no possible order is found 67 | } 68 | bool checkSolution() { 69 | int board[N][N]; 70 | for(int i = 0; i 21 | using namespace std; 22 | 23 | int kadaneAlgo(int arr[], int n) 24 | { 25 | int globalMax,maxEndingHere,i; 26 | globalMax = arr[0]; 27 | maxEndingHere = arr[0]; 28 | for(i=1;i globalMax) 32 | globalMax = maxEndingHere; 33 | } 34 | return globalMax; 35 | } 36 | 37 | int main() 38 | { 39 | int arr[] = {1, 3, -4, 2, 1, -1, 3, -5}; 40 | int n = sizeof(arr)/sizeof(arr[0]); 41 | int result = kadaneAlgo(arr, n); 42 | 43 | cout<<"Max subarray sum = "< 20 | using namespace std; 21 | 22 | int LCS(string s1, string s2) 23 | { 24 | int i,j,max=-1; 25 | int l1 = s1.length(); 26 | int l2 = s2.length(); 27 | int res[l1+1][l2+1]; 28 | for(i=0;i<=l1;i++) 29 | { 30 | for(j=0;j<=l2;j++) 31 | { 32 | if(i==0 || j==0) 33 | { 34 | res[i][j]=0; 35 | } 36 | else if(s1[i-1] == s2[j-1]) 37 | { 38 | res[i][j] = res[i-1][j-1] + 1; 39 | if(res[i][j]>max) 40 | max = res[i][j]; 41 | } 42 | else 43 | res[i][j] = 0; 44 | } 45 | } 46 | return max; 47 | } 48 | 49 | int main() 50 | { 51 | string s1 = "welcome to ti9"; 52 | string s2 = "cheers to ti9 tourney"; 53 | cout< 21 | using namespace std; 22 | 23 | int main() 24 | { 25 | int m,n,i,j,max_len=-1; 26 | cin>>m>>n; 27 | int arr[m][n]; 28 | for(i=0;i>arr[i][j]; 31 | 32 | // Forming the substructure 33 | int sub[m+1][n+1]; 34 | for(i=0;i 6 | #include 7 | using namespace std; 8 | 9 | int minAverage(int arr[], int n, int k) 10 | { 11 | int i, j, min=INT_MAX; 12 | for(i=0;i act[j].end) 46 | { 47 | cout<<"Activity "< forward displacement i.e. (B > F) 19 | // forward displacement (F) > 0 20 | // backward displacement (B) > 0 21 | // time (T) > 0 22 | // distance (D) > 0 23 | // All input values must be positive integers only 24 | 25 | // Sample Input 0 26 | 27 | // 2 28 | // 6 9 3 18 29 | // 3 7 5 20 30 | // Sample Output 0 31 | 32 | // 162 33 | // 220 34 | 35 | #include 36 | using namespace std; 37 | 38 | int main() 39 | { 40 | int n; 41 | cin>>n; 42 | while(n--) 43 | { 44 | 45 | int f,b,t,d; 46 | cin>>f>>b>>t>>d; 47 | long long ans=0; 48 | int count=0,dist=0; 49 | while(true) 50 | { 51 | if(dist+b 23 | #include 24 | #include 25 | #include 26 | 27 | int main() { 28 | int n; 29 | scanf("%d", &n); 30 | int a[n]; 31 | for(int i=0; i 33 | #include 34 | #include 35 | 36 | bool canJump(const std::vector &nums) { 37 | auto lastPos = nums.size() - 1; 38 | for (auto i = nums.size() - 1; i >= 0; i--) { 39 | if (i + nums[i] >= lastPos) { 40 | lastPos = i; 41 | } 42 | } 43 | return lastPos == 0; 44 | } 45 | 46 | 47 | static void test(){ 48 | // Test 1 49 | std::vector num1={4,3,1,0,5}; 50 | assert(canJump(num1)==true); 51 | std::cout<<"Input: "; 52 | for(auto i: num1){ 53 | std::cout< num2={3,2,1,0,4}; 58 | assert(canJump(num2)==false); 59 | std::cout<<"Input: "; 60 | for(auto i: num2){ 61 | std::cout<= 0): 58 | # if full sample can't be taken 59 | if(remw - vals_s[i]['weight'] < 0): 60 | totval += vals_s[i]['value'] * (remw / vals_s[i]['weight']) 61 | else: 62 | totval += vals_s[i]['value'] 63 | # reducing remaining weight 64 | remw -= vals_s[i]['weight'] 65 | # moving to next dictionary 66 | i += 1 67 | 68 | print(float(totval)) 69 | -------------------------------------------------------------------------------- /Greedy Algorithms/KnapsackUsingStruct.cpp: -------------------------------------------------------------------------------- 1 | /*You are given an empty bag that is supposed to be filled with gold, and it can carry at max W kgs of gold in it. 2 | 3 | You are given N samples of gold, with the ith of them weighing Wi and having value Vi. 4 | 5 | Your task is to fill the bag with exactly W kgs of gold such that the total value of the gold inside the bag is maximum. 6 | 7 | You need not take the entire samples of gold, you can break them down and take fractions of those samples as well. 8 | For example, if you have two samples, one with weight 10 and value 10 and another with weight 5 and value 10, 9 | you can fill a 5 kg capacity bag with 2.5 kg of first sample and 2.5 kg of second sample. 10 | The value for such a bag will be the sum of values of all the pieces, i.e. for the first sample 2.5 kg has value 2.5 11 | and for the second sample 2.5 kg has value 5, hence the total value of the bag becomes 7.5 12 | 13 | INPUT 14 | First line contains two integers, N and W. 15 | Second onwards, there are N lines with each of them containing two integers, 16 | first one being the weight of the sample and the second one being the value of the sample 17 | 18 | OUTPUT 19 | Print one number, the maximum attainable value when the bag is filled with W kgs of gold. 20 | If it is not possible to fill the bag with W kgs of gold, print -1. 21 | 22 | CONSTRAINTS 23 | 1 ≤ N ≤ 105 24 | 1 ≤ W ≤ 109 25 | 1 ≤ weights, values ≤ 109 26 | 27 | Sample Input 0 28 | 29 | 3 10 30 | 5 5 31 | 3 10 32 | 4 4 33 | Sample Output 0 34 | 35 | 17.000000000000 36 | Explanation 0 37 | 38 | We can take 3 kgs of sample 2, 4 kgs of sample 1 and 3 kgs of sample 3 to attain the maximum value*/ 39 | 40 | 41 | 42 | 43 | 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | using namespace std; 51 | 52 | struct bag 53 | { 54 | long wgt,val; 55 | double frac; 56 | }; 57 | bool compare(bag a,bag b) 58 | { 59 | return a.frac>b.frac; 60 | } 61 | 62 | int main() { 63 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 64 | long n,w,i; 65 | cin>>n>>w; 66 | bag a[n]; 67 | for(i=0;i>a[i].wgt>>a[i].val; 70 | a[i].frac=(double)a[i].val/a[i].wgt; 71 | } 72 | sort(a,a+n,compare); 73 | double tot=0; 74 | for(i=0;iw) 82 | { 83 | tot += (double)w * a[i].frac; 84 | w=0; 85 | } 86 | } 87 | if(w!=0) 88 | cout<<"-1"; 89 | else 90 | cout< l * 9 or s == 0): 45 | print('-1') 46 | else: 47 | # Making empty array for the number 48 | num = [0] * l 49 | for j in range(l): 50 | # Maximising 51 | if(s >= 9): 52 | num[j] = 9 53 | s -= 9 54 | else: 55 | num[j] = s 56 | s = 0 57 | # Printing 58 | for j in num: 59 | print(j, end='') 60 | print() 61 | -------------------------------------------------------------------------------- /Greedy Algorithms/SmallestNumberGivenDigitsAndSum.py: -------------------------------------------------------------------------------- 1 | # Smallest number 2 | # The task is to find the smallest number with given sum of digits as s and number of digits as d. 3 | 4 | # Expected Time Complexity: O(d) 5 | 6 | # Input: 7 | # The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of a single line containing two space separated integers s and d, where s is digit sum and d is number of digits. 8 | 9 | # Output: 10 | # Corresponding to each test case, in a new line, print the smallest number if possible, else print -1. 11 | 12 | # Constraints: 13 | # 1 ≤ T ≤ 100 14 | # 1 ≤ s ≤ 100 15 | # 1 ≤ d ≤ 6 16 | 17 | # Example: 18 | # Input 19 | # 3 20 | # 9 2 21 | # 20 3 22 | # 63 3 23 | 24 | # Output 25 | # 18 26 | # 299 27 | # -1 28 | 29 | n = int(input()) 30 | for i in range(n): 31 | # Sum, number of digits 32 | a, b = map(int, input().split()) 33 | # first check, example: 3 digit number can't have sum more than 27 (999) 34 | if(a > b * 9): 35 | print('-1') 36 | else: 37 | # Making empty result array 38 | res = [0] * b 39 | # First digit (most sig) must be atleast 1, so reserving that 40 | a -= 1 41 | # Starting from behind, putting bigger numbers in the end 42 | for j in range(b - 1, 0, -1): 43 | # Get rid of 9 to reduce overall number 44 | if(a >= 9): 45 | res[j] = 9 46 | a -= 9 47 | else: 48 | res[j] = a 49 | a = 0 50 | # Reusing the reserved 1 51 | res[0] = a + 1 52 | 53 | # Printing result 54 | for e in res: 55 | print(e, end='') 56 | print() 57 | -------------------------------------------------------------------------------- /Hash table/Group_anagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 3 | 4 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 11 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 12 | Example 2: 13 | 14 | Input: strs = [""] 15 | Output: [[""]] 16 | Example 3: 17 | 18 | Input: strs = ["a"] 19 | Output: [["a"]] 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= strs.length <= 104 25 | 0 <= strs[i].length <= 100 26 | strs[i] consists of lower-case English letters. 27 | */ 28 | 29 | 30 | 31 | 32 | 33 | class Solution { 34 | public: 35 | vector> groupAnagrams(vector& strs) 36 | { 37 | unordered_map>Map; 38 | 39 | for (int i=0; i>results; 47 | for (auto a:Map) 48 | results.push_back(a.second); 49 | 50 | return results; 51 | 52 | } 53 | }; -------------------------------------------------------------------------------- /Linked Lists/Singly Linked List/FindLoopAndMidElement.cpp: -------------------------------------------------------------------------------- 1 | // Linked List program to: 2 | // Search for an element in a LL 3 | // Find the mid element of the LL 4 | // Detect of any loop is present in the LL 5 | 6 | 7 | #include 8 | using namespace std; 9 | 10 | struct Node 11 | { 12 | struct Node* next; 13 | int data; 14 | }; 15 | 16 | Node* insert(Node* head, int data) 17 | { 18 | Node* newNode = (Node*)malloc(sizeof(Node)); 19 | Node* temp = head; 20 | newNode->data = data; 21 | newNode->next = NULL; 22 | if(head==NULL) 23 | return newNode; 24 | while(head->next!=NULL) 25 | head = head->next; 26 | head->next = newNode; 27 | return temp; 28 | } 29 | 30 | void display(Node* head) 31 | { 32 | Node* temp = head; 33 | while(temp!=NULL) 34 | { 35 | cout<data<next; 37 | } 38 | } 39 | 40 | int count(Node* head) 41 | { 42 | if(head==NULL) 43 | return 0; 44 | else 45 | return 1+count(head->next); 46 | } 47 | 48 | bool search(Node* head, int data) 49 | { 50 | if(head==NULL) 51 | return false; 52 | else 53 | { 54 | if(head->data==data) 55 | return true; 56 | else 57 | return search(head->next, data); 58 | } 59 | } 60 | 61 | int middle(Node* head) 62 | { 63 | Node *ptr1 = head; 64 | Node *ptr2 = head; 65 | if(head==NULL) 66 | return 0; 67 | while(ptr2!=NULL && ptr2->next!=NULL) 68 | { 69 | ptr2 = ptr2->next->next; 70 | ptr1 = ptr1->next; 71 | } 72 | return ptr1->data; 73 | } 74 | 75 | bool has_cycle(Node* head) { 76 | Node* ptr1 = head; 77 | Node* ptr2 = head; 78 | if(head==NULL || head->next==NULL) 79 | return false; 80 | 81 | while(ptr1!=NULL && ptr2!=NULL && ptr2->next!=NULL) 82 | { 83 | ptr1 = ptr1->next; 84 | ptr2 = ptr2->next->next; 85 | if(ptr2==ptr1) 86 | return true; 87 | } 88 | return false; 89 | } 90 | 91 | int main() 92 | { 93 | cout << "Hello World" << endl; 94 | cout<<"Creating a list"<2->3->4->5 33 | // Explanation 0 34 | 35 | // Initially the list will be empty and then we will add 5. After that we will add 4 infront of 5. 36 | //Similarly 3 infront of 4 and so on. 37 | 38 | 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | typedef struct node str; 45 | struct node 46 | { 47 | int data; 48 | str *next; 49 | }; 50 | 51 | str* insert(str *head, int item) 52 | { 53 | if(head==NULL) 54 | { 55 | head=(str *)malloc(sizeof(str)); 56 | head->data=item; 57 | head->next=NULL; 58 | } 59 | else 60 | { 61 | str *new=(str *)malloc(sizeof(str)); 62 | new->data=item; 63 | new->next=head; 64 | head=new; 65 | } 66 | return head; 67 | } 68 | 69 | void printlist(str *head) 70 | { 71 | str *ptr=head; 72 | while(ptr->next != NULL) 73 | { 74 | printf("%d->",ptr->data); 75 | ptr=ptr->next; 76 | } 77 | printf("%d",ptr->data); 78 | } 79 | int main() { 80 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 81 | int n,i,ele; 82 | scanf("%d",&n); 83 | str *head=NULL; 84 | for(i=0;i 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | typedef struct LinkedListNode LinkedListNode; 22 | 23 | struct LinkedListNode { 24 | int val; 25 | LinkedListNode *next; 26 | }; 27 | 28 | LinkedListNode* _insert_node_into_singlylinkedlist(LinkedListNode *head, LinkedListNode *tail, int val) { 29 | if(head == NULL) { 30 | head = (LinkedListNode *) (malloc(sizeof(LinkedListNode))); 31 | head->val = val; 32 | head->next = NULL; 33 | tail = head; 34 | } 35 | else { 36 | LinkedListNode *node = (LinkedListNode *) (malloc(sizeof(LinkedListNode))); 37 | node->val = val; 38 | node->next = NULL; 39 | tail->next = node; 40 | tail = tail->next; 41 | } 42 | return tail; 43 | } 44 | 45 | //BODY STARTS HERE 46 | 47 | 48 | /* 49 | * Complete the function below. 50 | */ 51 | /* 52 | For your reference: 53 | LinkedListNode { 54 | int val; 55 | LinkedListNode *next; 56 | }; 57 | */ 58 | void ReversePrint(LinkedListNode* head) { 59 | 60 | } 61 | 62 | 63 | //BODY ENDS HERE 64 | 65 | int main() 66 | { 67 | int head_size = 0; 68 | 69 | LinkedListNode* head = NULL; 70 | LinkedListNode* head_tail = NULL; 71 | 72 | scanf("%d\n", &head_size); 73 | for(int i = 0; i < head_size; i++) { 74 | int head_item; 75 | scanf("%d", &head_item); 76 | head_tail = _insert_node_into_singlylinkedlist(head, head_tail, head_item); 77 | 78 | if(i == 0) { 79 | head = head_tail; 80 | } 81 | } 82 | 83 | 84 | ReversePrint(head); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /Miscellaneous/7DivisiblePairs.cpp: -------------------------------------------------------------------------------- 1 | /*You are given an array A[N] of size N. 2 | We define a 7-Divisible Pair as a pair of integers (i,j) such that Ai + Aj is divisible by 7. 3 | Formally, a pair of integers (i,j) is a 7-Divisible pair if ( Ai + Aj ) % 7 = 0. 4 | Your task is to find the total number of 7-Divisible pairs from the given array. 5 | 6 | INPUT 7 | 8 | First line contains N the size of the array. (1 ≤ N ≤ 105). 9 | Second line contains the array elements that all lie between 1 and 105. 10 | 11 | OUTPUT 12 | 13 | Output a single integer that denotes the number of pairs divisible by 7. 14 | 15 | Sample Input 0 16 | 17 | 5 18 | 9 3 7 4 14 19 | 20 | Sample Output 0 21 | 22 | 2 23 | 24 | */ 25 | 26 | #include 27 | using namespace std; 28 | 29 | 30 | int main(){ 31 | unsigned int n,count1=0,count2=0,count3=0,count4=0,count5=0,count6=0,count7=0; 32 | cin>>n; 33 | int a[n]; 34 | for(int i=0;i>a[i]; 36 | 37 | for(int i=0;i 1 and A > 0 where A and P both should be integers. Now he wonders, there is a possibility that he does not exist at all because he does not satisfy the A^P expressibility condition. Given the values of A and P, find out if X exists or not. 4 | 5 | // Input Format 6 | 7 | // Input contains the value of integer X. 8 | 9 | // Constraints 10 | 11 | // 0 < X < 2x10^9 12 | 13 | // Output Format 14 | 15 | // Output "yes" if X can be expressed as A^P and "no" otherwise. 16 | 17 | // Sample Input 0 18 | 19 | // 4 20 | // Sample Output 0 21 | 22 | // yes 23 | // Explanation 0 24 | 25 | // Yes as 2^2 = 4 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | using namespace std; 33 | 34 | int check(unsigned int n) 35 | { 36 | if(n<=1) 37 | return 1; 38 | for(int x=2;x<=sqrt(n);x++) 39 | { 40 | unsigned p=x; 41 | while(p<=n) 42 | { 43 | p*=x; 44 | if(p==n) 45 | return 1; 46 | } 47 | } 48 | return 0; 49 | } 50 | 51 | int main() { 52 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 53 | int n; 54 | cin>>n; 55 | int flag=check(n); 56 | if(flag==1) 57 | { 58 | cout<<"yes"; 59 | } 60 | else 61 | cout<<"no"; 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Miscellaneous/ConsecutivePrimeSum.cpp: -------------------------------------------------------------------------------- 1 | // Consecutive Prime Sum 2 | 3 | // Some prime numbers can be expressed as Sum of other consecutive prime numbers. 4 | 5 | // For example 6 | 7 | // 5 = 2 + 3 8 | // 17 = 2 + 3 + 5 + 7 9 | // 41 = 2 + 3 + 5 + 7 + 11 + 13 10 | 11 | // Your task is to find out how many prime numbers which satisfy this property are present in the range 3 to N subject to a constraint that summation should always start with number 2. 12 | 13 | // Write code to find out number of prime numbers that satisfy the above mentioned property in a given range. 14 | 15 | // Input Format: 16 | // Each test case contains a number N <= 1000000000 17 | 18 | // Output Format: 19 | // Print the total number of all such prime numbers which are less than or equal to N. 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | using namespace std; 27 | 28 | int isPrime(int n) 29 | { 30 | for(int i=2;i<=(int)sqrt(n);i++) 31 | { 32 | if(n%i==0) 33 | return 0; 34 | } 35 | return 1; 36 | } 37 | 38 | int main() { 39 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 40 | int i,j,n,ct=0,sum=2; 41 | cin>>n; 42 | for(i=3;sum0): 70 | m+=1 71 | elif(l[i]==0 and l[i+1]<0): 72 | v+=1 73 | return v 74 | 75 | if __name__ == '__main__': 76 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 77 | 78 | n = int(input()) 79 | 80 | s = input() 81 | 82 | result = countingValleys(n, s) 83 | 84 | fptr.write(str(result) + '\n') 85 | 86 | fptr.close() 87 | -------------------------------------------------------------------------------- /Miscellaneous/DigitsInFactorial.py: -------------------------------------------------------------------------------- 1 | # As simple as the title, given a number N, print the number of digits in N! 2 | 3 | # N! is defined as : N! = 1*2*3...(N-1)*N 4 | 5 | # 0! = 0 and 1! = 1. 6 | 7 | # No number ever contains any leading zeros. 8 | 9 | # Input Format 10 | # Input contains only one number, N. 11 | # Constraints 12 | # 1 <= N <= 1000 13 | 14 | # Output Format 15 | # Output one number that is equal to the number of digits in N! 16 | 17 | # Sample Input 0 18 | # 6 19 | 20 | # Sample Output 0 21 | # 3 22 | 23 | # Explanation 0 24 | 25 | # 6! = 1x2x3x4x5x6 = 720 which has 3 digits. So the answer is 3. 26 | 27 | 28 | import math 29 | 30 | x = int(input()) 31 | count = 0 32 | if x > 0: 33 | for i in range(2, x + 1): 34 | count += math.log10(i) 35 | 36 | print(math.floor(count) + 1) 37 | else: 38 | print(0) 39 | 40 | # Explanation: Take log on both sides. log(1*2*3*4*5*6) = log(1)+log(2)+log(3)... = log(720) 41 | # floor(log(720))+1 = number of digits in the factorial 42 | -------------------------------------------------------------------------------- /Miscellaneous/EsotericChairs.py: -------------------------------------------------------------------------------- 1 | # You invited n guests to dinner! 2 | # You plan to arrange one or more circles of chairs. 3 | # Each chair is going to be either occupied by one guest, or be empty. 4 | # You can make any number of circles. 5 | 6 | # Your guests happen to be a little bit shy, so the i-th guest wants to have a least li free chairs to the left of his chair, and at least ri free chairs to the right. 7 | # The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. 8 | # Note that when a guest is the only one in his circle, the li chairs to his left and ri chairs to his right may overlap. 9 | 10 | # What is smallest total number of chairs you have to use? 11 | 12 | # Input Format 13 | # First line contains one integer n— number of guests. 14 | 15 | # Next n lines contain n pairs of space-separated integers li and ri. 16 | 17 | # Sample Input 0 18 | # 4 19 | # 1 2 20 | # 2 1 21 | # 3 5 22 | # 5 3 23 | 24 | # Sample Output 0 25 | # 15 26 | 27 | # Explanation 0 28 | # In the second sample the only optimal answer is to use two circles: a circle with 5 chairs accomodating guests 1 and 2, 29 | # and another one with 10 chairs accomodating guests 3 and 4. 30 | 31 | n = int(input()) 32 | a = [] 33 | b = [] 34 | # input 35 | for i in range(n): 36 | x, y = map(int, input().split()) 37 | a.append(x) 38 | b.append(y) 39 | 40 | 41 | # sorting because then distances between two most similar people (by difference of chairs) will be lowest possible 42 | a = sorted(a) 43 | b = sorted(b) 44 | 45 | # counting total chairs in between people 46 | tot = 0 47 | for i in range(n): 48 | tot += max(a[i], b[i]) 49 | 50 | # adding num of people 51 | print(tot+n) 52 | -------------------------------------------------------------------------------- /Miscellaneous/Factors57.py: -------------------------------------------------------------------------------- 1 | # Factor57 2 | 3 | # Develop a Python method change(amount) that for any integer amount in the range from 24 to 1000 4 | # returns a list consisting of numbers 5 and 7 only, such that their sum is equal to amount. 5 | # For example, change(28) may return [7, 7, 7, 7], while change(49) may return [7, 7, 7, 7, 7, 7, 7] 6 | # or [5, 5, 5, 5, 5, 5, 5, 7, 7] or [7, 5, 5, 5, 5, 5, 5, 5, 7]. 7 | 8 | def change(amount): 9 | if not (24 <= amount <= 1000): 10 | return [0] 11 | k = int(3 * amount / 7) 12 | return [5] * (3*amount-7*k) + [7] * (5*k-2*amount) 13 | 14 | # print(change (24)) 15 | # print(change (28)) 16 | # print(change (49)) 17 | # print(change (55)) 18 | n = int(input()) 19 | print(change(n)) 20 | 21 | 22 | # Explanation: 23 | # If we call our target number n, count the number of 5s in the solution list and call it r, and count the number of 7s and call it s, we can restate the problem as finding nonnegative integers r, s for which 24 | 25 | # 5 * r + 7 * s = n 26 | # We first want to solve that equation for n=1 and allow r or s to be negative. I quickly used continued fractions to solve that, a technique similar to the extended Euclidean algorithm. I'll skip the details, but I quickly came up with 27 | 28 | # 5 * 3 + 7 * -2 = 1 29 | # We now multiply both sides of that equation by n and get 30 | 31 | # 5 * (3*n) + 7 * (-2*n) = n 32 | # Since we found one solution, number theory tells us there are actually infinitely many solutions, all of them in the form 33 | 34 | # 5 * (3*n - 7*k) + 7 * (-2*n + 5*k) = n 35 | # where k is an arbitrary integer. We are almost done, but we need to find k so that those multipliers are nonnegative. We also want to make our solution list as short as possible, so we want as many 7s and as few 5s as possible. So we require the multiplier of 5 to be nonnegative and desire it to be small which means we want k to be large. So we require 36 | 37 | # 3 * n - 7 * k >= 0 38 | # Solve that for k and we get 39 | 40 | # k <= 3 * n / 7 41 | # The largest integer that satisfies that is 42 | 43 | # k = int(3 * n / 7) 44 | # which explains the next-to-last line in my code. So we want 3*n-7*k number of 5s in our list and -2*n+5*k which is 5*k-2*n number of 7s in our result list. We finally use Python's list multiplier syntax, which means that if mylist is a list value, then mylist * t is a list containing t copies of mylist concatenated to each other. Therefore I used that notation twice to return a list with the desired number of 5s followed by the desired number of 7s. 45 | 46 | # Finally, number theory tells us that we get nonnegative values for those list multipliers for any value of n that is at least (5-1) * (7-1) which is 24. That explains the lower bound in the problem. There is no upper bound in the mathematical problem--I assume the computing problem gives an upper bound of 1000 to allow for quick checking. -------------------------------------------------------------------------------- /Miscellaneous/NobleInteger.py: -------------------------------------------------------------------------------- 1 | # Noble Integer 2 | 3 | # Given an integer array, find if an integer p exists in the array 4 | # such that the number of integers greater than p in the array equals to p 5 | 6 | # If such an integer is found return 1 else return -1. 7 | 8 | 9 | class Solution: 10 | # @param A : list of integers 11 | # @return an integer 12 | def solve(self, A): 13 | A = sorted(A) 14 | size = len(A) 15 | i = 0 16 | while i < size: 17 | temp = A[i] 18 | # Checking for the same number being repeated multiple times 19 | # Example: 0,0,2,2,3 should be -1 (as 2 isn't greater than 2) 20 | while(i < size - 1 and A[i + 1] == temp): 21 | i += 1 22 | if(temp == size - i - 1): 23 | return 1 24 | i += 1 25 | return -1 26 | 27 | 28 | """ 29 | Testing Code for this problem 30 | """ 31 | 32 | s = Solution() 33 | a = [0, 0, 2, 2, 3] 34 | print(s.solve(a)) 35 | 36 | # output == [1,2,3,5] 37 | -------------------------------------------------------------------------------- /Miscellaneous/NotExactlyGCD.c: -------------------------------------------------------------------------------- 1 | /* 2 | GCD, not exactly 3 | 4 | In math, GCD, the greatest common divisor is an easy task to calculate for 2 positive numbers. 5 | 6 | A common divisor of two positive numbers is a number which divides both numbers. 7 | 8 | However your teacher decides to give you a more difficult task, in this task you need to find the largest divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range. 9 | 10 | You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. 11 | 12 | Input Format 13 | 14 | The first line has a and b, the two integers as described above. 15 | 16 | The second line contains one integer n, representing the number of queries. 17 | 18 | In the n lines that follow, each line contains one query consisting of two integers, low and high. 19 | 20 | Output Format 21 | 22 | Print n lines. 23 | 24 | The i-th of them should have the result of the i-th query in the input. 25 | 26 | If there is no common divisor in the given range for any query, print -1. 27 | 28 | Sample Input 0 29 | 30 | 9 27 31 | 3 32 | 1 5 33 | 10 11 34 | 9 11 35 | Sample Output 0 36 | 37 | 3 38 | -1 39 | 9 40 | */ 41 | 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | int gcd_max(long int n1, long int n2, long int lo, long int hi) 48 | { 49 | long int i,gcd=-1; 50 | if(lo>hi) 51 | return -1; 52 | for(i=hi;i>=lo;i--) 53 | { 54 | if(n1%i==0 && n2%i==0) 55 | return i; 56 | } 57 | return gcd; 58 | } 59 | 60 | int main() { 61 | 62 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 63 | long int n1,n2,n,i,lo,hi; 64 | scanf("%ld",&n1); 65 | scanf("%ld",&n2); 66 | scanf("%ld",&n); 67 | for(i=0;i 32 | #include 33 | #include 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | 39 | int main() { 40 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 41 | int n,i,ans=0; 42 | cin>>n; 43 | for(i=1;i<=n;i++) 44 | { 45 | // cout<<"Adding "< 30 | #include 31 | #include 32 | #include 33 | #include 34 | using namespace std; 35 | int modulo_prime(int x,int y,int m,int n) 36 | { 37 | while(x!=y) 38 | { 39 | if(x>y) 40 | y+=n; 41 | else 42 | x+=m; 43 | } 44 | return x; 45 | } 46 | int main() { 47 | 48 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 49 | int m,n,x,y,x1,x2,y1,y2,a,b,c,temp; 50 | cin>>m>>n; 51 | cin>>x>>y>>x1>>y1>>x2>>y2; 52 | a=modulo_prime(x,y,m,n); 53 | b=modulo_prime(x1,y1,m,n); 54 | c=modulo_prime(x2,y2,m,n); 55 | cout<<2*a+b-c; 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Miscellaneous/SquareInACircle.c: -------------------------------------------------------------------------------- 1 | // Square in a Circle 2 | 3 | // A square is kept inside a circle. It keeps expanding untill all four of its vertices touch the circumfernce of the circle. Another smaller circle is kept inside the square now and it keeps expanding untill its circumference touches all four sides of the square. The outer and the inner circle form a ring. Find the area of this ring. 4 | 5 | // Input 6 | // Input consists of multiple test cases. 7 | // Each test case contains one integer a denoting the side-length of the square between the two circles. 8 | 9 | // Output 10 | // Print the area of the ring. 11 | 12 | // Sample Input 0 13 | 14 | // 3 15 | // 3 16 | // 4 17 | // 5 18 | // Sample Output 0 19 | 20 | // 7.068583 21 | // 12.566371 22 | // 19.634954 23 | 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | int main() { 31 | 32 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 33 | int t; 34 | double a; 35 | scanf("%d",&t); 36 | for(int i=1;i<=t;++i) 37 | { 38 | scanf("%lf",&a); 39 | double r1=a/2; 40 | double c=sqrt(2*a*a); 41 | double r2=c/2; 42 | double a=(3.14159265358979323846)*(r2*r2-r1*r1); 43 | printf("%0.6lf\n",a); 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Miscellaneous/SumOfPairs.py: -------------------------------------------------------------------------------- 1 | # Count the number of pairs in an array having the given sum 2 | 3 | # Given an array of integers, and a number ‘sum’, chef wants to find the number of pairs of integers in the array whose sum is equal to ‘sum’. 4 | 5 | # Examples: 6 | 7 | # Input : arr[] = {1, 5, 7, -1}, 8 | # sum = 6 9 | # Output : 2 10 | # Pairs with sum 6 are (1, 5) and (7, -1) 11 | 12 | # Input : arr[] = {1, 5, 7, -1, 5}, 13 | # sum = 6 14 | # Output : 3 15 | # Pairs with sum 6 are (1, 5), (7, -1) & 16 | # (1, 5) 17 | 18 | # Input : arr[] = {1, 1, 1, 1}, 19 | # sum = 2 20 | # Output : 6 21 | # There are 3! pairs with sum 2. 22 | 23 | # Input : arr[] = {10, 12, 10, 15, -1, 7, 6, 24 | # 5, 4, 2, 1, 1, 1}, 25 | # sum = 11 26 | # Output : 9 27 | 28 | 29 | # cook your dish here 30 | # Brute Force Method [O(n^2)] 31 | n = int(input()) 32 | arr = list(map(int,input().split())) 33 | sum = int(input()) 34 | count = 0 35 | 36 | for i in range(0, n): 37 | for j in range(i+1, n): 38 | if arr[i]+arr[j]==sum: 39 | count+=1 40 | print(count) 41 | 42 | 43 | # Map Approach [O(n)] : 44 | # Idea is to create a hashmap to store freq of the elements, and lookup those elements while traversing the array to check if their sum is equal to the given sum or not 45 | # GeeksforGeeks Explanation: https://youtu.be/bvKMZXc0jQU 46 | 47 | def getPairsCount(arr, n, sum): 48 | 49 | m = [0] * 1000 50 | 51 | # Store counts of all elements in map m 52 | for i in range(0, n): 53 | m[arr[i]] # Stores the frequency of the number in the array 54 | m[arr[i]] += 1 55 | 56 | twice_count = 0 57 | 58 | # Iterate through each element and increment the count (Every pair is counted twice) 59 | for i in range(0, n): 60 | 61 | twice_count += m[sum - arr[i]] 62 | 63 | # if (arr[i], arr[i]) pair satisfies the condition, then we need to ensure that the count is decreased by one such that the (arr[i], arr[i]) pair is not considered 64 | if (sum - arr[i] == arr[i]): 65 | twice_count -= 1 66 | 67 | # return the half of twice_count 68 | return int(twice_count / 2) 69 | 70 | n = int(input()) 71 | arr = list(map(int,input().split())) 72 | sum = int(input()) 73 | 74 | print(getPairsCount(arr, n, sum)) -------------------------------------------------------------------------------- /Miscellaneous/SumOfPrimes.cpp: -------------------------------------------------------------------------------- 1 | // N as Sum of Primes 2 | 3 | // Given a number N, print "YES" if N can be expressed as a sum of 2 prime numbers and "NO" otherwise. 4 | 5 | // Input Format 6 | 7 | // One number, N. 8 | 9 | // Constraints 10 | 11 | // 1 <= N <= 10^5. 12 | 13 | // Output Format 14 | 15 | // "YES" or "NO" 16 | 17 | // Sample Input 0 18 | 19 | // 5 20 | // Sample Output 0 21 | 22 | // YES 23 | // Explanation 0 24 | 25 | // 5 = 2 + 3 26 | 27 | // Sample Input 1 28 | 29 | // 11 30 | // Sample Output 1 31 | 32 | // NO 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | using namespace std; 40 | int check(int n) 41 | { 42 | int flag=0; 43 | for(int i=2;i<=n/2;i++) 44 | { 45 | if(n%i==0) 46 | { 47 | flag=1; 48 | break; 49 | } 50 | } 51 | if(flag==0||n==1) 52 | return 1; 53 | else 54 | return 0; 55 | } 56 | 57 | int main() { 58 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 59 | int n; 60 | cin>>n; 61 | int temp=n; 62 | int flag=0; 63 | for(int i=2;i<=n/2;i++) 64 | { 65 | if(check(i)==1&&check(n-i)==1) 66 | { 67 | flag=1; 68 | break; 69 | } 70 | } 71 | if(flag==1) 72 | cout<<"YES"; 73 | else 74 | cout<<"NO"; 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Miscellaneous/TrailingZerosOfFactorial.py: -------------------------------------------------------------------------------- 1 | # Trailing Zeros of Factorial 2 | 3 | # The most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to check their function periodically. 4 | 5 | # The technicians faced a very interesting problem recently. Given a set of BTSes to visit, they needed to find the shortest path to visit all of the given points and return back to the central company building. Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. After a long time, one of the programmers found this problem in a conference article. Unfortunately, he found that the problem is so called "Traveling Salesman Problem" and it is very hard to solve. If we have N BTSes to be visited, we can visit them in any order, giving us N! possibilities to examine. The function expressing that number is called factorial and can be computed as a product 6 | 7 | # 1.2.3.4....N. The number is very high even for a relatively small N. 8 | 9 | # The programmers understood they had no chance to solve the problem. But because they have already received the research grant from the government, they needed to continue with their studies and produce at least some results. So they started to study behavior of the factorial function. 10 | 11 | # For example, they defined the function Z. For any positive integer N, Z(N) is the number of zeros at the end of the decimal form of number N!. They noticed that this function never decreases. If we have two numbers N1y: 37 | m=x 38 | else: 39 | m=y 40 | ans = ab^bc 41 | print("{0:b}".format(ans).zfill(m)) -------------------------------------------------------------------------------- /Patterns/AlphabetRangoli.py: -------------------------------------------------------------------------------- 1 | # You are given an integer, X. 2 | # Your task is to print an alphabet rangoli of size X. 3 | # (Rangoli is a form of Indian folk art based on creation of patterns.) 4 | 5 | # Different sizes of alphabet rangoli are shown below: 6 | 7 | # #size 3 8 | 9 | # ----c---- 10 | # --c-b-c-- 11 | # c-b-a-b-c 12 | # --c-b-c-- 13 | # ----c---- 14 | 15 | # The center of the rangoli has the first alphabet letter a, and the boundary has the Xth alphabet letter (in alphabetical order). 16 | 17 | # Input Format 18 | # Only one line of input containing , the size of the rangoli. 19 | 20 | # Constraints 21 | # 0 44 | #include 45 | #include 46 | #include 47 | #include 48 | using namespace std; 49 | 50 | 51 | int main() { 52 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 53 | int n; 54 | cin>>n; 55 | int i,j,k,x,g,z,u,a,e,b,ct=0,q; 56 | u=n; 57 | int s=n; 58 | int l=n; 59 | z=1; 60 | for(i=1;i<=n;i++) 61 | { 62 | s=n; 63 | for(j=1;j<=i;j++) 64 | { 65 | cout<0;j--) 68 | { 69 | cout<i;j--) 73 | cout<i;j--) 91 | { 92 | cout< 38 | using namespace std; 39 | int main() { 40 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 41 | int n,i,j; 42 | cin>>n; 43 | long long int a[n+1][n+1]; 44 | for(i=1;i<=n;i++) 45 | { 46 | for(j=1;j<=i;j++) 47 | { 48 | if(j==1||j==i) 49 | { 50 | a[i][j]=1; 51 | cout< 32 | #include 33 | #include 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | 39 | int main() { 40 | int n,i=0,prime=2,j,flag; 41 | cin>>n; 42 | int total=(n*(n+1))/2; 43 | int arr[total]; 44 | arr[i++]=2; 45 | while(i!=total) 46 | { 47 | prime++; 48 | flag=1; 49 | for(j=2;j<=sqrt(prime);j++) 50 | { 51 | if(prime%j==0) 52 | { 53 | flag=0; 54 | break; 55 | } 56 | } 57 | if(flag==1) 58 | { 59 | arr[i++]=prime; 60 | continue; 61 | } 62 | } 63 | int k=0; 64 | for(i=1;i<=n;i++) 65 | { 66 | for(j=1;j<=i;j++) 67 | cout< 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | 34 | int main() { 35 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 36 | string str,s1="",s2=""; 37 | int i,j; 38 | cin>>str; 39 | int len=str.length(); 40 | for(i=1;i<=len;i++) 41 | { 42 | s2=""; 43 | s1+=str[i-1]; 44 | for(j=0;j 39 | #include 40 | #include 41 | #include 42 | #include 43 | using namespace std; 44 | 45 | 46 | int main() { 47 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 48 | int n,c; 49 | cin>>n>>c; 50 | while(n>0) 51 | { 52 | if(n%2==0) 53 | { 54 | if(c==2) 55 | c=3; 56 | else if(c==3) 57 | c=2; 58 | } 59 | else 60 | { 61 | if(c==1) 62 | c=2; 63 | else if(c==2) 64 | c=1; 65 | } 66 | n--; 67 | } 68 | cout< 35 | #include 36 | #include 37 | int main() 38 | { 39 | char** str_arr; 40 | char* result; //don't forget to allocate sufficient memory to result string 41 | int i; 42 | //your code here 43 | str_arr = (char**)malloc(sizeof(char*)*5); 44 | result = (char*)malloc(sizeof(char)*200); 45 | for(i=0;i<5;i++) 46 | str_arr[i] = (char*)malloc(sizeof(char)*10); 47 | for(i=0;i<5;i++) 48 | { 49 | gets(str_arr[i]); //,10,stdin); 50 | } 51 | for (i = 0; i < 5; i++) 52 | strcat(result, str_arr[i]); 53 | puts(result); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Pointers/PointerArrays2D.c: -------------------------------------------------------------------------------- 1 | // 2D Array Using Pointers 2 | 3 | // So far we saw how to use pointers to declare an array, but can we use pointers to declare a 2D array? The answer is yes. 4 | 5 | // Recall that by allocating more memory to a pointer we created a linear array. 6 | 7 | // What would happen if we created an array of pointers and allocated linear memory to each pointer in the array? 8 | 9 | // int *arr[10]; 10 | // for (i = 0; i < 10; i++) arr[i] = (int*) malloc(sizeof(int) * 10); 11 | // The above code would result in the creation of a 2D array of dimensions 10x10 since each pointer points to a row of size 10 and there are 10 such pointers. 12 | 13 | // Similarly, to create an NxM matrix, we use : 14 | 15 | // int *arr[N]; 16 | // for (i = 0; i < N; i++) arr[i] = (int*) malloc(sizeof(int) * M); 17 | // To complete this task, write a program to take as input a square matrix of size NxN and print yes if the matrix is a diagonal matrix and no otherwise. 18 | 19 | // A diagonal matrix is one all of whose elements except that lie on the diagonals are zero. 20 | 21 | // Sample Input 0 22 | 23 | // 3 24 | // 1 0 1 25 | // 0 2 0 26 | // 1 0 1 27 | // Sample Output 0 28 | 29 | // yes 30 | // Sample Input 1 31 | 32 | // 3 33 | // -1 0 1 34 | // 0 2 0 35 | // 1 0 1 36 | // Sample Output 1 37 | 38 | // yes 39 | 40 | 41 | #include 42 | #include 43 | #include //this library contains the function malloc. 44 | int main() 45 | { 46 | int i, j, N, flag=1; 47 | scanf("%d", &N); 48 | int *matrix[N]; 49 | for (i = 0; i < N; i++) matrix[i] = (int*) malloc(sizeof(int) * N); 50 | for (i = 0; i < N; i++) 51 | { 52 | for (j = 0; j < N; j++) 53 | scanf("%d", &matrix[i][j]); 54 | } 55 | //your code here 56 | for(i=0;i 2 -> 1 -> 0. Hence, 3 moves. 22 | 23 | // For the case 2, we can either go 4 -> 3 -> 2 -> 1 -> 0 or 4 -> 2 -> 1 -> 0. The 2nd option is more optimal. Hence, 3 moves. 24 | 25 | int main() 26 | { 27 | int max=1000001; 28 | int i, j, nums[max]; 29 | 30 | //Initializing the array 31 | for(i=0;i(nums[i-1]+1)) 41 | nums[i]=nums[i-1]+1; 42 | for(j=1; j<=i && j*i>q; 49 | for(i=0; i>n; 53 | cout< 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | struct Stack 10 | { 11 | queue q1; 12 | queue q2; 13 | 14 | void enque(int x) 15 | { 16 | q2.push(x); 17 | while(!q1.empty()) 18 | { 19 | q2.push(q1.front()); 20 | q1.pop(); 21 | } 22 | queue temp = q1; 23 | q1 = q2; 24 | q2 = temp; 25 | } 26 | 27 | int dequeue() 28 | { 29 | // int x; 30 | // while(!q1.empty()) 31 | // { 32 | // x = q1.front(); 33 | // q1.pop(); 34 | // } 35 | // return x; 36 | return q1.back(); 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | struct Stack s; 43 | s.enque(1); 44 | s.enque(2); 45 | s.enque(3); 46 | s.enque(4); 47 | s.enque(5); 48 | 49 | cout<<"\nElement removed is: "< 29 | #include 30 | #include 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | string min(int n) 36 | { 37 | if(n==1) 38 | return "int"; 39 | else 40 | return "min(int, " + min(n-1) + ")"; 41 | } 42 | 43 | int main() { 44 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 45 | int n,i; 46 | cin>>n; 47 | cout<=0 and arr[j]>last): 38 | arr[j+1] = arr[j] 39 | j = j-1 40 | arr[j+1]=last 41 | 42 | # a function that prints array of certain size 43 | def printArray(arr,n): 44 | for i in range(n): 45 | print arr[i], 46 | -------------------------------------------------------------------------------- /Recursion/SumOfAllDigits.cpp: -------------------------------------------------------------------------------- 1 | // Sum of all Digits 2 | 3 | // You are given an integer I in the following format : 4 | // You are given two integers P and Q. 5 | // Integer I can be obtained by appending Q instances of P together. 6 | // For example, if P = 619 and Q = 4, then I = 619619619619. 7 | 8 | // Your task is, given P and Q find the sum of all the digits of I. 9 | // That sounds too simple, so lets take it up a notch. 10 | // Lets say the sum of all digits is S, then run the following pseudocode : 11 | 12 | // int SumOfDigits(S) : 13 | // K <- Sum of Digits of S 14 | // if K is a single digit number, return K 15 | // else return SumOfDigits(K) 16 | // INPUT 17 | // Input consist of two numbers P and Q separated by a space. 18 | 19 | // OUTPUT 20 | // Print a single digit, the final digit when the numbers of I are continuously added. 21 | 22 | // CONSTRAINTS 23 | // 1 ≤ P ≤ 10100000 24 | // **1 ≤ Q ≤ **105 25 | 26 | // Sample Input 0 27 | 28 | // 148 3 29 | // Sample Output 0 30 | 31 | // 3 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | using namespace std; 39 | 40 | long int sumofdigits(long int n) 41 | { 42 | int d; 43 | d=n%10; 44 | if(n<10) 45 | return d; 46 | else 47 | return d+sumofdigits(n/10); 48 | } 49 | 50 | long int sumuptosingledigit(long int n) 51 | { 52 | int k=sumofdigits(n); 53 | if(k<10) 54 | return k; 55 | else 56 | return sumofdigits(k); 57 | } 58 | 59 | int main() { 60 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 61 | long int m,n; 62 | cin>>n; 63 | cin>>m; 64 | int sum1=sumofdigits(n); 65 | cout< 0): 38 | tot += n % 10 39 | n //= 10 40 | return tot 41 | 42 | 43 | def sumOfDigits(n): 44 | k = sumDigits(n) 45 | if k > 9: 46 | return sumOfDigits(k) 47 | else: 48 | return k 49 | 50 | 51 | num = sumDigits(a) * b 52 | print(sumOfDigits(num)) 53 | -------------------------------------------------------------------------------- /Recursion/Tower_of_Hanoi.c: -------------------------------------------------------------------------------- 1 | /* Tower of Hanoi is a mathematical puzzle whit three rods and n number of disks. 2 | 3 | The objective of this puzzle is to move the entire stack from one rod to another rod 4 | with the help of the third rod. 5 | 6 | These are the following simple rules of the puzzle: 7 | 8 | 1. We can only move one disk at a time. 9 | 10 | 2. We can only move the upper most disk from one of the stacks and placing it on top of another stack. 11 | 12 | 3. Disks should be placed in ascending order i.e. uppermost most disk should be the smallest and 13 | the lowermost should be the largest disk. 14 | 15 | OUTPUT: 16 | 17 | (If we take number of disks 3 then the output of the program will be following: ) 18 | 19 | Enter the number of disk:3 20 | A to C 21 | A to B 22 | C to B 23 | A to C 24 | B to A 25 | B to C 26 | A to C 27 | 28 | (If we take number of disks 2 then the output of the program will be following: ) 29 | 30 | Enter the number of disk:2 31 | A to B 32 | A to C 33 | B to C 34 | */ 35 | 36 | #include 37 | #include 38 | void TOH(int n,char A,char B,char C) 39 | { 40 | if(n==1) 41 | { 42 | printf("%c to %c\n",A,C); //if the number of disk is one in that case we can directly move the disk from A to C 43 | } 44 | else 45 | /* if the number of disks is greater than one in that case, we will 1st move the (n-1) Disks from rod A to rod B with 46 | the help of the Rod C then we will move the remaining one disk from rod A to rod C then finally we will move 47 | (n-1) disks from rod B to rod C */ 48 | { 49 | 50 | TOH(n-1,A,C,B); //recursive call 51 | TOH(1,A,B,C); 52 | TOH(n-1,B,A,C); 53 | } 54 | } 55 | int main(void) 56 | { 57 | int n; 58 | char c1 = 'A', c2 ='B', c3 = 'C'; 59 | printf("Enter the number of disk:"); 60 | scanf("%d",&n); 61 | TOH(n,c1,c2,c3); 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Recursion/combinationStrings.cpp: -------------------------------------------------------------------------------- 1 | //Given an input string of numbers, find all combinations of numbers that can be formed using digits in the same order. 2 | 3 | 4 | //Sample input: 5 | // '1214' 6 | // Output: 7 | // 1214 8 | //121 4 9 | //12 14 10 | //12 1 4 11 | //1 214 12 | //1 21 4 13 | //1 2 14 14 | //1 2 1 4 15 | 16 | 17 | //Sample Input: 18 | //'123' 19 | //Output: 20 | //123 21 | //12 3 22 | //1 23 23 | //1 2 3 24 | 25 | 26 | 27 | 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | void comb(string input,int i,string output) 34 | { 35 | if(i==input.length()) 36 | { 37 | cout<>input; 54 | cout<<"\n"; 55 | output=""; 56 | int len = 0; 57 | comb(input,0,output); 58 | } -------------------------------------------------------------------------------- /Recursion/gcd.cpp: -------------------------------------------------------------------------------- 1 | //Finding the Greatest Common Divisor using C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | int gcd(int a, int b) { 7 | if (b == 0){ 8 | return a; 9 | } 10 | return gcd(b, a % b); 11 | } 12 | 13 | int main() { 14 | int a = 92, b = 36; 15 | cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b) << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Recursion/powersum.cpp: -------------------------------------------------------------------------------- 1 | //Find the number of ways that a given integer,x, can be expressed as the sum of the nth powers of unique, natural numbers. 2 | //For example, if x=13 and n=2, we have to find all combinations of unique squares adding up to 13. The only solution is 2^2+3^2. 3 | //Problem link:- https://www.hackerrank.com/challenges/the-power-sum/problem 4 | 5 | 6 | // Sample Input: 7 | // x=10, n=2 8 | // Output: 9 | // 1 (1^2+3^2) 10 | 11 | // Sample Input: 12 | // x=100, n=3 13 | // Output 14 | // 1 (1^3+2^3+3^3+4^3) 15 | 16 | 17 | 18 | 19 | 20 | 21 | #include 22 | using namespace std; 23 | 24 | int ps(int x,int n,int index) 25 | { 26 | //Return value of "pow" function is float and subtracting a float from an integer will not guarantee correct value. 27 | //That is why the value after subtracting is stored inside an int variable. 28 | //If you write '(x - pow(index, n))' in place of 'value' while calling the function, it will give you an error 29 | //because subtract will start getting float values. 30 | int value = (x - pow(index, n)); 31 | if(value<0) 32 | return 0; 33 | else if(value==0) 34 | return 1; 35 | //At each value, you have two options. 1. Choose that value 2. Skip that value. 36 | //If you choose it then call the function after subtracting pow(index,n) from x 37 | //if you don't choose it, then call the funtion with same x value but incrementing x. 38 | else 39 | return ps(x,n,index+1) + ps(value,n,index+1); 40 | } 41 | 42 | int main() 43 | { 44 | int x,n; 45 | cin>>x; 46 | cin>>n; 47 | int c=ps(x,n,1); 48 | cout< 13 | using namespace std; 14 | 15 | bool RatInMaze(char maze[][100],int sol[100][100],int i,int j,int n,int m){ 16 | // Base case 17 | if(i==n-1 && j==m-1){ 18 | // Print the path 19 | sol[i][j] = 1; 20 | for(int i=0;i> m; 60 | cout << "Enter maze breadth: "; 61 | cin >> n; 62 | for(int i=0;i> str; 65 | for(int j=0;j 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | void swap(int *x, int *y) 31 | { 32 | int temp = *x; 33 | *x = *y; 34 | *y = temp; 35 | } 36 | 37 | using namespace std; 38 | int main() { 39 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 40 | int n,i,j; 41 | cin>>n; 42 | int d[n],m[n],y[n]; 43 | for(i=0;i>d[i]>>m[i]>>y[i]; 45 | for(i=0;iy[j+1]) 50 | { 51 | swap(y[j],y[j+1]); 52 | swap(m[j],m[j+1]); 53 | swap(d[j],d[j+1]); 54 | } 55 | } 56 | } 57 | for(i=0;im[i]) 62 | { 63 | swap(m[i],m[j]); 64 | swap(d[i],d[j]); 65 | } 66 | } 67 | } 68 | for(i=0;id[i]) 73 | { 74 | swap(d[i],d[j]); 75 | } 76 | } 77 | } 78 | // for(i=0;i 35 | #include 36 | #include 37 | #include 38 | typedef struct date date; 39 | struct date 40 | { 41 | int day; 42 | int month; 43 | int year; 44 | }; 45 | int main() { 46 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 47 | int n,i,j; 48 | scanf("%d",&n); 49 | date arr[n],temp; 50 | for(i=0;i arr[j+1].year) 57 | { 58 | temp = arr[j]; 59 | arr[j]=arr[j+1]; 60 | arr[j+1]=temp; 61 | } 62 | else if((arr[j].year == arr[j+1].year) && (arr[j].month > arr[j+1].month)) 63 | { 64 | temp = arr[j]; 65 | arr[j]=arr[j+1]; 66 | arr[j+1]=temp; 67 | } 68 | else if((arr[j].month == arr[j+1].month) && (arr[j].day > arr[j+1].day)) 69 | { 70 | temp = arr[j]; 71 | arr[j]=arr[j+1]; 72 | arr[j+1]=temp; 73 | } 74 | } 75 | } 76 | for(i=0;i 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | int parenthesis(string s) 20 | { 21 | stack st; 22 | int l = s.length(); 23 | int i; 24 | char ch; 25 | for(i=0;i 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int maxHistogram(vector v) 12 | { 13 | int maxArea = 0; 14 | int area = 0; 15 | int i; 16 | int top; 17 | stack s; 18 | 19 | for(i=0;i=v[s.top()]) 22 | { 23 | s.push(i++); 24 | } 25 | else 26 | { 27 | top = s.top(); 28 | s.pop(); 29 | 30 | if(s.empty()) 31 | area=v[top]*i; 32 | else 33 | area=v[top]*(i-s.top()-1); 34 | 35 | if(area>maxArea) 36 | maxArea = area; 37 | } 38 | } 39 | while(s.empty() == false) 40 | { 41 | top = s.top(); 42 | s.pop(); 43 | if(s.empty()) 44 | area=v[top]*i; 45 | else 46 | area=v[top]*(i-s.top()-1); 47 | 48 | if(area>maxArea) 49 | maxArea = area; 50 | } 51 | return maxArea; 52 | } 53 | 54 | int main() 55 | { 56 | vector v = {6, 2, 5, 4, 5, 1, 6}; 57 | cout << "Maximum area is " << maxHistogram(v); 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Stacks/MaxElementInStackArrays.c: -------------------------------------------------------------------------------- 1 | // You are given N queries:- 2 | // 1. X- Push the element X at top of the stack 3 | // 2. Delete the element at top of the stack 4 | // 3. Print the maximum element of the stack 5 | 6 | // Input Format:- 7 | // N, N lines follows each query 8 | 9 | // Output format:- 10 | // Print max element for each query of type 3 11 | 12 | // Sample Input 0 13 | 14 | // 10 15 | // 1 97 16 | // 2 17 | // 1 20 18 | // 2 19 | // 1 26 20 | // 1 20 21 | // 2 22 | // 3 23 | // 1 91 24 | // 3 25 | // Sample Output 0 26 | 27 | // 26 28 | // 91 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | int main() { 36 | int n,x,r; 37 | int a[100000],at=-1,b[100000],bt=-1; 38 | scanf("%d",&n); 39 | 40 | while(n--) 41 | { 42 | scanf("%d",&x); 43 | 44 | switch(x) 45 | { 46 | case 1: scanf("%d",&a[++at]); 47 | if(bt==-1 || b[bt]<=a[at]) 48 | b[++bt]=a[at]; 49 | break; 50 | case 2: 51 | if(a[at--]==b[bt]) bt--; 52 | break; 53 | case 3: 54 | printf("%d\n",b[bt]); 55 | } 56 | } 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Stacks/MaxElementInStackLinkedLists.c: -------------------------------------------------------------------------------- 1 | // You are given N queries:- 2 | // 1. X- Push the element X at top of the stack 3 | // 2. Delete the element at top of the stack 4 | // 3. Print the maximum element of the stack 5 | 6 | // Input Format:- 7 | // N, N lines follows each query 8 | 9 | // Output format:- 10 | // Print max element for each query of type 3 11 | 12 | // Sample Input 0 13 | 14 | // 10 15 | // 1 97 16 | // 2 17 | // 1 20 18 | // 2 19 | // 1 26 20 | // 1 20 21 | // 2 22 | // 3 23 | // 1 91 24 | // 3 25 | // Sample Output 0 26 | 27 | // 26 28 | // 91 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | typedef struct node stack; 35 | struct node 36 | { 37 | int data; 38 | stack *next; 39 | }*top,*top1; 40 | int max; 41 | void insert(int val) 42 | { 43 | stack *new=(stack *)malloc(sizeof(stack)); 44 | new->data = val; 45 | if(top==NULL) 46 | { 47 | new->next=NULL; 48 | top=new; 49 | stack *new1=(stack *)malloc(sizeof(stack)); 50 | new1->data=val; 51 | new1->next=NULL; 52 | top1=new1; 53 | max=new1->data; 54 | } 55 | else 56 | { 57 | new->next=top; 58 | top=new; 59 | if(top->data >= max) 60 | { 61 | stack *new1=(stack *)malloc(sizeof(stack)); 62 | new1->data = top->data; 63 | new1->next=top1; 64 | top1=new1; 65 | } 66 | } 67 | } 68 | 69 | void pop() 70 | { 71 | stack *ptr=top; 72 | top=top->next; 73 | if(ptr->data == top1->data) 74 | { 75 | stack *ptr1=top1; 76 | top1=top1->next; 77 | free(ptr1); 78 | } 79 | free(ptr); 80 | } 81 | 82 | int findmax() 83 | { 84 | return top1->data; 85 | } 86 | int main() { 87 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 88 | int n; 89 | scanf("%d",&n); 90 | int choice,val; 91 | while(n--) 92 | { 93 | scanf("%d",&choice); 94 | if(choice==1) 95 | { 96 | scanf("%d",&val); 97 | insert(val); 98 | } 99 | else if(choice==2) 100 | { 101 | pop(); 102 | } 103 | else if(choice==3) 104 | { 105 | max=findmax(); 106 | printf("%d\n",max); 107 | } 108 | } 109 | return 0; 110 | } 111 | -------------------------------------------------------------------------------- /Stacks/ParenthesisDepth.cpp: -------------------------------------------------------------------------------- 1 | // Find maximum depth of nested parenthesis in a string 2 | 3 | // We are given a string having parenthesis like below 4 | // “( ((X)) (((Y))) )” 5 | // We need to find the maximum depth of balanced parenthesis, like 4 in above example. Since ‘Y’ is surrounded by 4 balanced parenthesis. 6 | // If parenthesis are unbalanced then return -1. 7 | 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | int parenthesis(string ex) 14 | { 15 | int l = ex.length(); 16 | int i,ct=0,maxct=0; 17 | stack s; 18 | char ch; 19 | for(i=0;imaxct) 37 | maxct = ct; 38 | } 39 | if(s.empty()) 40 | return maxct; 41 | else 42 | return -1; 43 | } 44 | 45 | int main() 46 | { 47 | string expr = "( p((q)) ((s)t) )"; 48 | cout< 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | struct Queue 12 | { 13 | stack s1; 14 | stack s2; 15 | 16 | void enque(int x) 17 | { 18 | s1.push(x); 19 | } 20 | 21 | int dequeue() 22 | { 23 | if(s1.empty()) 24 | return 0; 25 | else 26 | { 27 | while(!s1.empty()) 28 | { 29 | s2.push(s1.top()); 30 | s1.pop(); 31 | } 32 | } 33 | int x = s2.top(); 34 | s2.pop(); 35 | return x; 36 | } 37 | }; 38 | 39 | int main() 40 | { 41 | struct Queue q; 42 | q.enque(1); 43 | q.enque(2); 44 | q.enque(3); 45 | q.enque(4); 46 | q.enque(5); 47 | 48 | cout<<"\nElement removed is: "< 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | 39 | int main() { 40 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 41 | string str; 42 | cin>>str; 43 | int i; 44 | int len=str.length(); 45 | // cout< A 7 | // 2 -> B 8 | // .... 9 | // .... 10 | // 26 -> Z 11 | // 27 -> AA 12 | // Input Format 13 | 14 | // One integer denoting the column number. 15 | 16 | // Constraints 17 | 18 | // The integer size will be less than 32-bits. 19 | 20 | // Output Format 21 | 22 | // Output the corresponding column title. 23 | 24 | // Sample Input 0 25 | 26 | // 27 27 | // Sample Output 0 28 | 29 | // AA 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | 39 | int main() { 40 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 41 | int n; 42 | cin>>n; 43 | int rem[100],div,i=0,j; 44 | while(n>0) 45 | { 46 | rem[i]=n%26; 47 | if(rem[i]==0) 48 | { 49 | rem[i]=26; 50 | n-=26; 51 | } 52 | n/=26; 53 | i++; 54 | } 55 | for(j=i-1;j>=0;j--) 56 | printf("%c",rem[j]+64); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Strings/DiscoverTheRightNumber.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a column title as appears in an Excel Spreadsheet, return its corresponding column number. 3 | For Example : 4 | 5 | A -> 1 6 | B -> 2 7 | .... 8 | .... 9 | Z -> 26 10 | AA -> 27 11 | Input Format 12 | 13 | One string denoting the column title of an excel spreadsheet. 14 | 15 | Constraints 16 | 17 | The answer will always fit in a 32-bit integer. 18 | 19 | Output Format 20 | 21 | Output an integer. 22 | 23 | Sample Input 0 24 | 25 | AA 26 | Sample Output 0 27 | 28 | 27 29 | ''' 30 | 31 | 32 | a = input() 33 | l = [] 34 | b = 0 35 | t = 0 36 | for i in a: 37 | l = l + [i] 38 | while(l): 39 | a = l.pop() 40 | if t == 0: 41 | b = b + (ord(a) - 64) 42 | else: 43 | b = b + (ord(a) - 64) * pow(26, t) 44 | t = t + 1 45 | print(b) 46 | -------------------------------------------------------------------------------- /Strings/DiscoverTheSubstring.java: -------------------------------------------------------------------------------- 1 | // Discover the Substring 2 | 3 | // strstr is a function that returns 1 if one string is present as substring in another and 0 otherwise. You are to write a program to print the number of times one string is present in the other as a substring. 4 | 5 | // Input Format 6 | 7 | // Two lines of input consisting of two strings. 8 | 9 | // Constraints 10 | 11 | // 1 <= length of strings <= 100 12 | 13 | // Output Format 14 | 15 | // Output one number, the number of times any one string appears in the other. 16 | 17 | // Sample Input 0 18 | 19 | // banana 20 | // ana 21 | // Sample Output 0 22 | 23 | // 2 24 | // Explanation 0 25 | 26 | // b(ana)na and ban(ana) so answer is 2 27 | 28 | // Sample Input 1 29 | 30 | // a 31 | // adamant 32 | // Sample Output 1 33 | 34 | // 3 35 | // Explanation 1 36 | 37 | // (a)damant, ad(a)mant and adam(a)nt. So answer is 3. 38 | 39 | import java.io.*; 40 | import java.util.*; 41 | 42 | public class Solution { 43 | 44 | public static void main(String[] args) { 45 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 46 | Scanner sc = new Scanner(System.in); 47 | int n; 48 | String str; 49 | String findStr; 50 | str=sc.nextLine(); 51 | findStr=sc.nextLine(); 52 | if(str.length()len(s): 42 | sb,s=s,sb 43 | 44 | results = 0 45 | sub_len = len(sb) 46 | for i in range(len(s)): 47 | if s[i:i+sub_len] == sb: 48 | results += 1 49 | print(results) -------------------------------------------------------------------------------- /Strings/Lapindrome.py: -------------------------------------------------------------------------------- 1 | # Lapindromes 2 | 3 | # Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have the same characters with same frequency. Also, abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves contain the same characters but their frequencies do not match. 4 | # Your task is simple. Given a string, you need to tell if it is a lapindrome. 5 | 6 | # Input: 7 | # First line of input contains a single integer T, the number of test cases. 8 | # Each test is a single line containing a string S composed of only lowercase English alphabet. 9 | # Output: 10 | # For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not. 11 | # Constraints: 12 | # 1 ≤ T ≤ 100 13 | # 2 ≤ |S| ≤ 1000, where |S| denotes the length of S 14 | # Example: 15 | # Input: 16 | # 6 17 | # gaga 18 | # abcde 19 | # rotor 20 | # xyzxy 21 | # abbaab 22 | # ababc 23 | 24 | 25 | # Output: 26 | # YES 27 | # NO 28 | # YES 29 | # YES 30 | # NO 31 | # NO 32 | 33 | t = int(input()) 34 | for i in range(t): 35 | word = input() 36 | word_len = len(word) 37 | mid = word_len//2 38 | if((word_len %2) ==0 ): 39 | str1 = word[0:mid] 40 | str2 = word[mid:] 41 | else: 42 | str1 = word[0:mid] 43 | str2 = word[mid+1:] 44 | 45 | str1 = sorted(str1) 46 | str2 = sorted(str2) 47 | if(str1 == str2): 48 | print("YES") 49 | else: 50 | print("NO") -------------------------------------------------------------------------------- /Strings/MinimizeWasteCells.cpp: -------------------------------------------------------------------------------- 1 | // Previously, it was important for every company to have a motto. 2 | 3 | // Now, it is important for every company to have a banner. 4 | 5 | // Since companies want to save their resources, they decided to convert their motto into a banner. 6 | 7 | // How this works is, you create a square matrix of size N x N, and fill in the elements of this matrix using the motto in row-major order. 8 | 9 | // The remaining spaces in the matrix are called waste cells and are to be represented as '?'. 10 | 11 | // You have to choose N in such a way that the number of waste cells is minimized. 12 | 13 | // Input 14 | // Input consists of one line only, containing the company motto 15 | 16 | // Output 17 | // Output must consist of the matrix formed from the input string 18 | 19 | // Notes 20 | // The length of the input string will not exceed 1000 21 | 22 | // Sample Input 0 23 | 24 | // nike - just do it! 25 | // Sample Output 0 26 | 27 | // nike 28 | // - jus 29 | // t do 30 | // it!?? 31 | // ????? 32 | // Sample Input 1 33 | 34 | // oneplus - never settle! 35 | // Sample Output 1 36 | 37 | // onepl 38 | // us - 39 | // never 40 | // sett 41 | // le!?? 42 | 43 | 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | using namespace std; 51 | 52 | 53 | int main() { 54 | char s[1001]; 55 | cin.getline(s,1001); 56 | int l=strlen(s); 57 | int n,i,j,k=0; 58 | n=ceil(sqrt(l)); 59 | for(i=0;i=l) 64 | cout<<"?"; 65 | else 66 | cout< 24 | #include 25 | #include 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | int main() { 31 | char ch[100000]; 32 | int a[100000][2],j=0,i,k,temp; 33 | cin>>ch; 34 | for(i=0;ch[i]!='\0';i++) 35 | { 36 | if(ch[i]=='a' || ch[i]=='e' || ch[i]=='i' || ch[i]=='o' || ch[i]=='u' || ch[i]=='A' || ch[i]=='E' || ch[i]=='I' || ch[i]=='O' || ch[i]=='U') 37 | { 38 | a[j][0]=ch[i]; 39 | a[j][1]=i; 40 | j++; 41 | } 42 | } 43 | for(i=0,k=j-1;i 35 | #include 36 | #include 37 | #include 38 | #include 39 | using namespace std; 40 | 41 | 42 | int main() { 43 | char s[1000]; 44 | int p; 45 | int flag = 0; 46 | cin>>p; 47 | cin>>s; 48 | int i; 49 | int c[26] = {0}; 50 | for(i=0; s[i]!='\0'; i++) 51 | c[s[i]-'a']+=1; 52 | for(int i=0;i<26;i++) 53 | { 54 | if(c[i]!=0 && c[i]!=p) 55 | { 56 | flag = 1; 57 | break; 58 | } 59 | } 60 | if(flag==0){ 61 | cout<<"YES"; 62 | } 63 | else{ 64 | cout<<"NO"; 65 | } 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Strings/StringConversion.cpp: -------------------------------------------------------------------------------- 1 | // String Conversion 2 | 3 | // The string "GOTISPATHETIC" is written in a zigzag pattern on a given number of rows like this: 4 | 5 | // G---S---H---C- 6 | // -O-I-P-T-E-I-- 7 | // --T---A---T--- 8 | // And then read line by line: GSHCOIPTEITAT 9 | 10 | // Write the code that will take a string and make this conversion given a number of rows. 11 | 12 | // Input Format 13 | 14 | // One string and one integer- the number of rows. 15 | 16 | // Output Format 17 | 18 | // One string 19 | 20 | // Sample Input 0 21 | 22 | // GOTISPATHETIC 23 | // 3 24 | // Sample Output 0 25 | 26 | // GSHCOIPTEITAT 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | 36 | int main() { 37 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 38 | int i,n,l,row=0,direction=0; 39 | string str; 40 | cin>>str; 41 | cin>>n; 42 | string a[n]; 43 | l=str.length(); 44 | for(i=0;i 12 | #include 13 | void allTrim(char *p) 14 | { 15 | char *m,*j; 16 | j=p; 17 | m=p; 18 | while(*m==' ') 19 | { 20 | m++; 21 | } //eliminates left spaces 22 | while(*m!='\0') 23 | { 24 | while(*m!='\0' && *m!=' ') //copy words 25 | { 26 | *j=*m; 27 | j++; 28 | m++; 29 | } 30 | if(*m=='\0') break; 31 | *j=' '; 32 | j++; 33 | while(*m==' ') m++; 34 | } 35 | if(j>p) 36 | { 37 | if(*(j-1)==' ') j--; 38 | } 39 | *j='\0'; 40 | } 41 | 42 | int main() 43 | { 44 | char a[2000]; 45 | printf("Enter a string:"); 46 | fgets(a,2000,stdin); 47 | a[strlen(a)-1]='\0'; 48 | allTrim(a); 49 | printf("(%s)",a); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Strings/leftTrim.c: -------------------------------------------------------------------------------- 1 | /* 2 | LEFT TRIM 3 | This program eliminates extra spaces from left side of the string. 4 | 5 | INPUT FORMAT : one string 6 | OUTPUT FORMAT : one string 7 | SAMPLE INPUT : left trim program. 8 | SAMPLE OUTPUT :(left trim program.) 9 | */ 10 | 11 | #include 12 | #include 13 | void leftTrim(char *p) 14 | { 15 | char *q; 16 | q=p; 17 | while(*q==' ') 18 | { 19 | q++; 20 | } 21 | if(q>p) //if there were extra spaces on left, q would have been increased 22 | { 23 | while(*q!='\0') 24 | { 25 | *p=*q; 26 | q++; 27 | p++; 28 | } 29 | *p='\0'; 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | char a[1000]; 36 | printf("Enter a string:"); 37 | fgets(a,1000,stdin); 38 | a[strlen(a)-1]='\0'; 39 | leftTrim(a); 40 | printf("(%s)",a); 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Strings/rightTrim.c: -------------------------------------------------------------------------------- 1 | /* 2 | RIGHT TRIM 3 | This program eliminates extra spaces from right side of the string. 4 | 5 | INPUT FORMAT : one string 6 | OUTPUT FORMAT : one string 7 | SAMPLE INPUT : right trim program 8 | SAMPLE OUTPUT :(right trim program) round brackets are added in the output so that you can see extra spaces got eliminated from right side of the string. 9 | */ 10 | 11 | #include 12 | #include 13 | void rightTrim(char *p) 14 | { 15 | char *q; 16 | q=p; 17 | while(*q!='\0') 18 | { 19 | q++; 20 | } 21 | q--; //because q was pointing '\0' 22 | while(q>=p && *q==' ') q--; 23 | *(q+1)='\0'; 24 | } 25 | 26 | int main() 27 | { 28 | char a[1000]; 29 | printf("Enter a string:"); 30 | fgets(a,1000,stdin); 31 | a[strlen(a)-1]='\0'; 32 | rightTrim(a); 33 | printf("(%s)",a); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Structures/EmployeeSheetSTL.cpp: -------------------------------------------------------------------------------- 1 | // You are working for a company. Define a struct as follows : 2 | 3 | // struct Employee{ 4 | // char name[55]; 5 | // int salary; 6 | // } 7 | // Given data of n employees, you are to use any sorting algorithm to sort them according to their salary in ascending order, and print them in the format "name salary". 8 | 9 | // NOTE : Participants using Java shall use classes instead of structs. 10 | 11 | // It is guaranteed that all names are distinct. If two people have the same salary, the one with lexicographically smaller name must come before the other. 12 | 13 | // NOTE : you are not allowed to make any global variables. You must create another function to do the sorting and pass your employee array as a pointer to that function to sort it. 14 | 15 | // Input Format 16 | 17 | // First line contains a number N, number of employees. 18 | // Next N lines contain one string and one integer each. 19 | 20 | // Constraints 21 | 22 | // 1 <= name of employee <= 50 23 | // 1 <= N <= 1000 24 | // 1 <= salary <= 1000 25 | 26 | // Output Format 27 | 28 | // Print the data of all employees in the format "name salary" with details of one employee on one line. 29 | 30 | // Sample Input 0 31 | 32 | // 5 33 | // Abhinav 100 34 | // Nischay 50 35 | // Sarthak 25 36 | // Abhiram 150 37 | // Praneeth 200 38 | // Sample Output 0 39 | 40 | // Sarthak 25 41 | // Nischay 50 42 | // Abhinav 100 43 | // Abhiram 150 44 | // Praneeth 200 45 | 46 | 47 | #include 48 | using namespace std; 49 | 50 | struct salary 51 | { 52 | char a[50]; 53 | int marks; 54 | }; 55 | bool compare(salary d, salary b) 56 | { 57 | if(d.marks == b.marks) 58 | { 59 | bool cmp = strcmp(d.a, b.a) >= 0 ? false : true; 60 | return cmp; 61 | 62 | } 63 | return (d.marks < b.marks); 64 | } 65 | int main() { 66 | int n; 67 | cin>>n; 68 | salary names[n]; 69 | for(int i=0; i>names[i].a; 72 | cin>>names[i].marks; 73 | } 74 | 75 | sort(names, names + n, compare); 76 | for(int i=0; i 35 | #include 36 | #include 37 | #include 38 | typedef struct date date; 39 | struct date 40 | { 41 | int day; 42 | int month; 43 | int year; 44 | }; 45 | int main() { 46 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 47 | int n,i,j; 48 | scanf("%d",&n); 49 | date arr[n],temp; 50 | for(i=0;i arr[j+1].year) 57 | { 58 | temp = arr[j]; 59 | arr[j]=arr[j+1]; 60 | arr[j+1]=temp; 61 | } 62 | else if((arr[j].year == arr[j+1].year) && (arr[j].month > arr[j+1].month)) 63 | { 64 | temp = arr[j]; 65 | arr[j]=arr[j+1]; 66 | arr[j+1]=temp; 67 | } 68 | else if((arr[j].month == arr[j+1].month) && (arr[j].day > arr[j+1].day)) 69 | { 70 | temp = arr[j]; 71 | arr[j]=arr[j+1]; 72 | arr[j+1]=temp; 73 | } 74 | } 75 | } 76 | for(i=0;i 28 | #include 29 | #include 30 | #include 31 | #include 32 | #define scan(x) scanf(" %d", &x) 33 | struct TreeNode { 34 | int x; 35 | struct TreeNode* L; 36 | struct TreeNode* R; 37 | }; 38 | typedef struct TreeNode TreeNode; 39 | TreeNode* newNode(int _x) { 40 | TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode)); 41 | node->x = _x; 42 | node->L = node->R = NULL; 43 | return node; 44 | } 45 | TreeNode* insert(TreeNode* node, int val) { 46 | if (node == NULL) return newNode(val); 47 | if (val <= node->x) node->L = insert(node->L, val); 48 | else node->R = insert(node->R, val); 49 | return node; 50 | } 51 | 52 | /*******************************************************************/ 53 | void postorder(TreeNode* Root) 54 | { 55 | if(Root==NULL) 56 | return; 57 | postorder(Root->L); 58 | postorder(Root->R); 59 | printf("%d ", Root->x); 60 | } 61 | void preorder(TreeNode* Root) 62 | { 63 | if(Root==NULL) 64 | return; 65 | printf("%d ", Root->x); 66 | preorder(Root->L); 67 | preorder(Root->R); 68 | } 69 | void inorder(TreeNode* Root) 70 | { 71 | if(Root==NULL) 72 | return; 73 | inorder(Root->L); 74 | printf("%d ", Root->x); 75 | inorder(Root->R); 76 | } 77 | /*******************************************************************/ 78 | 79 | int main() { 80 | int val, N; scan(N); 81 | TreeNode* Root = NULL; 82 | for (int i = 1; i <= N; i++) { 83 | scan(val); 84 | Root = insert(Root, val); 85 | } 86 | preorder(Root); 87 | printf("\n"); 88 | inorder(Root); 89 | printf("\n"); 90 | postorder(Root); 91 | } -------------------------------------------------------------------------------- /Trees/HeightOfBinaryTree.c: -------------------------------------------------------------------------------- 1 | // Output Format 2 | 3 | // Output one integer that is the height of the binary search tree. 4 | 5 | // Sample Input 0 6 | // 10 7 | // 2 8 5 1 10 5 9 9 3 5 8 | 9 | // Sample Output 0 10 | // 6 11 | 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | struct TreeNode{ 19 | int x; 20 | struct TreeNode* L; 21 | struct TreeNode* R; 22 | }; 23 | 24 | typedef struct TreeNode TreeNode; 25 | 26 | TreeNode* newNode(int y){ 27 | TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); 28 | node->x = y; 29 | node->L = node->R = NULL; 30 | return node; 31 | } 32 | 33 | int height(TreeNode *root){ 34 | if(root==NULL) 35 | return 0; 36 | else{ 37 | int ldepth = height(root->L); 38 | int rdepth = height(root->R); 39 | if(ldepth>rdepth) 40 | { 41 | return ldepth+1; 42 | } 43 | else 44 | return rdepth+1; 45 | } 46 | } 47 | 48 | TreeNode* insert(TreeNode* node, int val) 49 | { 50 | if(node==NULL) return newNode(val); 51 | if(val<=node->x){ 52 | node->L = insert(node->L, val); 53 | }else{ 54 | node->R = insert(node->R, val); 55 | } 56 | return node; 57 | } 58 | 59 | int main() { 60 | int val, N; 61 | scanf("%d", &N); 62 | TreeNode* Root= NULL; 63 | for(int i=1;i<=N; i++){ 64 | scanf("%d", &val); 65 | Root = insert(Root, val); 66 | } 67 | printf("%d", height(Root)); 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Trees/InOrder.c: -------------------------------------------------------------------------------- 1 | // Your task is to implement the following function : 2 | 3 | // void inorder(TreeNode*) 4 | // You will be working with the following structure : 5 | 6 | // struct TreeNode { 7 | // int x; 8 | // struct TreeNode* L; 9 | // struct TreeNode* R; 10 | // } 11 | // You may only edit the BODY of the code, leaving the HEAD and the TAIL as it is. 12 | 13 | // Sample Input 0 14 | 15 | // 7 16 | // 4 2 1 3 6 7 5 17 | // Sample Output 0 18 | 19 | // 1 2 3 4 5 6 7 20 | 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #define scan(x) scanf(" %d", &x) 28 | struct TreeNode { 29 | int x; 30 | struct TreeNode* L; 31 | struct TreeNode* R; 32 | }; 33 | typedef struct TreeNode TreeNode; 34 | TreeNode* newNode(int _x) { 35 | TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode)); 36 | node->x = _x; 37 | node->L = node->R = NULL; 38 | return node; 39 | } 40 | TreeNode* insert(TreeNode* node, int val) { 41 | if (node == NULL) return newNode(val); 42 | if (val <= node->x) node->L = insert(node->L, val); 43 | else node->R = insert(node->R, val); 44 | return node; 45 | } 46 | 47 | /*********************************************************/ 48 | 49 | void inorder(TreeNode* Root) 50 | { 51 | if(Root==NULL) 52 | return; 53 | inorder(Root->L); 54 | printf("%d ", Root->x); 55 | inorder(Root->R); 56 | } 57 | 58 | /*******************************************************/ 59 | 60 | int main() { 61 | int val, N; scan(N); 62 | TreeNode* Root = NULL; 63 | for (int i = 1; i <= N; i++) { 64 | scan(val); 65 | Root = insert(Root, val); 66 | } 67 | inorder(Root); 68 | } -------------------------------------------------------------------------------- /Trees/PostOrder.c: -------------------------------------------------------------------------------- 1 | // Your task is to implement the following function : 2 | 3 | // void postorder(TreeNode*) 4 | // You will be working with the following structure : 5 | 6 | // struct TreeNode { 7 | // int x; 8 | // struct TreeNode* L; 9 | // struct TreeNode* R; 10 | // } 11 | // You may only edit the BODY of the code, leaving the HEAD and the TAIL as it is. 12 | 13 | // Sample Input 0 14 | 15 | // 7 16 | // 4 2 1 3 6 7 5 17 | // Sample Output 0 18 | 19 | // 1 3 2 5 7 6 4 20 | 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #define scan(x) scanf(" %d", &x) 28 | struct TreeNode { 29 | int x; 30 | struct TreeNode* L; 31 | struct TreeNode* R; 32 | }; 33 | typedef struct TreeNode TreeNode; 34 | TreeNode* newNode(int _x) { 35 | TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode)); 36 | node->x = _x; 37 | node->L = node->R = NULL; 38 | return node; 39 | } 40 | TreeNode* insert(TreeNode* node, int val) { 41 | if (node == NULL) return newNode(val); 42 | if (val <= node->x) node->L = insert(node->L, val); 43 | else node->R = insert(node->R, val); 44 | return node; 45 | } 46 | 47 | /*******************************************************************/ 48 | void postorder(TreeNode* Root) 49 | { 50 | if(Root==NULL) 51 | return; 52 | postorder(Root->L); 53 | postorder(Root->R); 54 | printf("%d ", Root->x); 55 | } 56 | /*******************************************************************/ 57 | 58 | int main() { 59 | int val, N; scan(N); 60 | TreeNode* Root = NULL; 61 | for (int i = 1; i <= N; i++) { 62 | scan(val); 63 | Root = insert(Root, val); 64 | } 65 | postorder(Root); 66 | } -------------------------------------------------------------------------------- /Trees/PostOrderFromPreAndInorder.cpp: -------------------------------------------------------------------------------- 1 | /* Given two strings for inorder and preorder traversals. 2 | Print the postorder traversal result from the above two strings. 3 | 4 | First string is inorder traversal result, while second one is preorder traversal result. 5 | 6 | Sample Input:- 7 | DBEAFC 8 | ABDECF 9 | 10 | Sample Output:- 11 | DEBFCA */ 12 | 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | using namespace std; 21 | typedef struct tree tree; 22 | struct tree 23 | { 24 | char data; 25 | tree *left; 26 | tree *right; 27 | }; 28 | int search(char ch[], int start, int end, char value) 29 | { 30 | int i,idx; 31 | for(i=start;i<=end;i++) 32 | if(ch[i]==value) 33 | { 34 | idx=i; 35 | break; 36 | } 37 | return idx; 38 | } 39 | tree *newval(char val) 40 | { 41 | tree *node= (tree *)malloc(sizeof(tree)); 42 | node->data=val; 43 | node->left=NULL; 44 | node->right=NULL; 45 | return node; 46 | } 47 | tree *buildtree(char in[], char pre[], int start, int end) 48 | { 49 | if(start>end) 50 | return NULL; 51 | static int preidx=0; 52 | tree *node= newval(pre[preidx++]); 53 | if(start==end) 54 | return node; 55 | int inidx= search(in,start, end,node->data); 56 | node->left= buildtree(in,pre,start,inidx-1); 57 | node->right= buildtree(in,pre,inidx+1,end); 58 | return node; 59 | } 60 | void postorder(tree *root) 61 | { 62 | if(root!=NULL) 63 | { 64 | postorder(root->left); 65 | postorder(root->right); 66 | cout<data; 67 | } 68 | } 69 | int main() { 70 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 71 | char pre[100],in[100]; 72 | cin>>in>>pre; 73 | int len=strlen(in); 74 | tree *root = buildtree(in,pre,0,len-1); 75 | postorder(root); 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /Trees/PreOrder.c: -------------------------------------------------------------------------------- 1 | // Your task is to implement the following function : 2 | 3 | // void preorder(TreeNode*) 4 | // You will be working with the following structure : 5 | 6 | // struct TreeNode { 7 | // int x; 8 | // struct TreeNode* L; 9 | // struct TreeNode* R; 10 | // } 11 | // You may only edit the BODY of the code, leaving the HEAD and the TAIL as it is. 12 | 13 | // Sample Input 0 14 | 15 | // 7 16 | // 4 2 1 3 6 7 5 17 | // Sample Output 0 18 | 19 | // 4 2 1 3 6 5 7 20 | 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #define scan(x) scanf(" %d", &x) 28 | struct TreeNode { 29 | int x; 30 | struct TreeNode* L; 31 | struct TreeNode* R; 32 | }; 33 | typedef struct TreeNode TreeNode; 34 | TreeNode* newNode(int _x) { 35 | TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode)); 36 | node->x = _x; 37 | node->L = node->R = NULL; 38 | return node; 39 | } 40 | TreeNode* insert(TreeNode* node, int val) { 41 | if (node == NULL) return newNode(val); 42 | if (val <= node->x) node->L = insert(node->L, val); 43 | else node->R = insert(node->R, val); 44 | return node; 45 | } 46 | 47 | /*******************************************************************/ 48 | 49 | void preorder(TreeNode* Root) 50 | { 51 | if(Root==NULL) 52 | return; 53 | printf("%d ", Root->x); 54 | preorder(Root->L); 55 | preorder(Root->R); 56 | } 57 | 58 | /*******************************************************************/ 59 | 60 | int main() { 61 | int val, N; scan(N); 62 | TreeNode* Root = NULL; 63 | for (int i = 1; i <= N; i++) { 64 | scan(val); 65 | Root = insert(Root, val); 66 | } 67 | preorder(Root); 68 | } -------------------------------------------------------------------------------- /Trees/TraversalsAndHeight.cpp: -------------------------------------------------------------------------------- 1 | // Program to print inorder, preorder and postorder of the given tree and also find the height of the tree recursively 2 | 3 | #include 4 | using namespace std; 5 | 6 | struct Node 7 | { 8 | int data; 9 | struct Node *left; 10 | struct Node *right; 11 | }; 12 | 13 | Node* insert(Node* root, int data) 14 | { 15 | Node* newNode = (Node*)malloc(sizeof(Node)); 16 | newNode->data = data; 17 | newNode->left = NULL; 18 | newNode->right = NULL; 19 | if(root==NULL) 20 | return newNode; 21 | else if(datadata) 22 | root->left = insert(root->left, data); 23 | else 24 | root->right = insert(root->right, data); 25 | return root; 26 | } 27 | 28 | void inorder(Node* root) 29 | { 30 | if(root==NULL) 31 | return; 32 | inorder(root->left); 33 | cout<data<<"->"; 34 | inorder(root->right); 35 | } 36 | 37 | void preorder(Node* root) 38 | { 39 | if(root==NULL) 40 | return; 41 | cout<data<<"->"; 42 | preorder(root->left); 43 | preorder(root->right); 44 | } 45 | 46 | void postorder(Node* root) 47 | { 48 | if(root==NULL) 49 | return; 50 | postorder(root->left); 51 | postorder(root->right); 52 | cout<data<<"->"; 53 | } 54 | 55 | int height(Node *root){ 56 | if(root==NULL) 57 | return 0; 58 | else 59 | { 60 | int ldepth = height(root->left); 61 | int rdepth = height(root->right); 62 | if(ldepth>rdepth) 63 | return ldepth+1; 64 | else 65 | return rdepth+1; 66 | } 67 | } 68 | 69 | int main() 70 | { 71 | cout<<"This is my 1st tree program!"<