├── .gitignore ├── Code ├── Python │ ├── readme.md │ ├── Factorial.py │ ├── selection_sort.py │ ├── factorial_without_recursion.py │ ├── Brian_Kernighan's_Algorithm.py │ ├── linearsearch.py │ ├── TrimorphicNumber.py │ ├── palindrome_number.py │ ├── Count_of_rotations.py │ ├── check_pangram.py │ ├── josephus_problem.py │ ├── SlidingWindowMax.py │ ├── Kth_Minimum_in_Array.py │ ├── inverseArray.py │ ├── left_rotation.py │ ├── GCD.py │ ├── trapping_rainwater.py │ ├── RotationCount.py │ ├── merge_to_palindrome.py │ ├── Anagram.py │ ├── StockSpan.py │ ├── peak_element.py │ ├── Three_Sum.py │ ├── Transpose_of_matrix.py │ └── Balanced_brackets.py ├── C++ │ ├── a.out │ ├── fibonacci.cpp │ ├── factorial.cpp │ ├── gcd.cpp │ ├── insertion_at_start.cpp │ ├── permutation_of_a_string.cpp │ ├── wave_print.cpp │ ├── check_prime.cpp │ ├── insertion _at_end.cpp │ ├── peak_value_linear_search.cpp │ ├── longest_subarray_with_sum_k.cpp │ ├── Uique_prime_factor.cpp │ ├── phone_keypad.cpp │ ├── print_subsets.cpp │ ├── spiral_print.cpp │ ├── reverse_a_string_using_stack.cpp │ ├── josephus_problem.cpp │ ├── row_wise_sum.cpp │ ├── factorial_using_recursion.cpp │ ├── perfect_number.cpp │ ├── Geek-onacciNumber.cpp │ ├── binary_string_to_decimal.cpp │ ├── fibonacci_dp.cpp │ ├── Trimorphic_number.cpp │ ├── sorted_zig_zag_array.cpp │ ├── unbounded_knapsack.cpp │ ├── string_to_lowercase_and_uppercase.cpp │ ├── insertion_sort.cpp │ ├── unsorted_zig_zag_array.cpp │ ├── reverse_words_of_string.cpp │ ├── Linear_search.cpp │ ├── reverse_string.cpp │ ├── modular_exponentiation.cpp │ ├── selection_sort.cpp │ ├── Duplicate_in_array.cpp │ ├── longest_prefix_suffix.cpp │ ├── inverse_of_an_array.cpp │ ├── palindrome_number.cpp │ ├── rabin_karp.cpp │ ├── repeating_and_missing_number.cpp │ ├── Middle_of_the_LinkedList.cpp │ ├── Topological_sort.cpp │ ├── unique_permutaions_of_string.cpp │ ├── prime_number.cpp │ ├── queue_using_stacks.cpp │ ├── Sieves_prime.cpp │ ├── couting_sort.cpp │ ├── Climbing_Stairs.cpp │ ├── long_factorial.cpp │ ├── Largest_Rectangle.cpp │ ├── bucket_sort.cpp │ ├── Brian_Kernighan.cpp │ ├── splitarraylargestsum.cpp │ ├── max_count.cpp │ ├── merge_in_constant_space.cpp │ ├── DFS.cpp │ ├── Union_of_two_unsorted_array.cpp │ ├── shell_sort.cpp │ ├── searching_a_word_in_trie.cpp │ ├── Kth_Symbol_Grammar.cpp │ └── circle_sort.cpp └── Java │ ├── RedBlackTree.java │ ├── Dfs_Traversal.java │ ├── factorial.java │ ├── GCD.java │ ├── Taylorseries.java │ ├── inverseofarray.java │ ├── Swap_even_odd_bits.java │ ├── Longest_Common_Prefix.java │ ├── sqrt.java │ ├── Uniquefactor.java │ ├── dublicate.java │ ├── check_prime.java │ ├── Bin_Dec.java │ ├── Kamenetsky_Formula.java │ ├── revindivstring.java │ ├── Anagram.java │ ├── trimorphic_number.java │ ├── triautomorphic_number.java │ ├── reverse_string.java │ ├── greedyalgo.java │ ├── peakvalueinarray.java │ ├── smith_number.java │ ├── K Largest Elements.java │ ├── matrixop_add.java.java │ ├── root_to_leaf_path_sum.java │ ├── piglatin_convertor.java │ ├── matrixop_sub.java.java │ └── Palindrome_number.java ├── Trie └── readme.md ├── .github ├── ISSUE_TEMPLATE │ ├── addition-of-algo.md │ ├── addition-of-question.md │ ├── implementation-of-ds-or-any-other-ds.md │ └── correction-bug-report.md ├── workflows │ ├── pr-labeler.yml │ ├── greetings.yml │ ├── Auto_message_on_pr_open.yml │ ├── Auto_message_on_pr_merge.yml │ └── Auto_message_on_creatingissues.yml └── pull_request_template.md ├── Algorithm ├── Special_algo │ └── readme.md ├── Greedy │ └── readme.md ├── Hashing │ └── readme.md ├── Searching_Sorting │ ├── Binary_search.java │ └── dnf_sort.cpp └── Recursion │ └── readme.md ├── LICENSE ├── GUIDLINES.md ├── Heap └── readme.md ├── maximumSum.java ├── string └── Number_of_deletions_to_make_pallindrome.py ├── 2D_Array └── readme.md ├── Stack └── readme.md ├── pronic_Number.cpp └── Queue └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_store -------------------------------------------------------------------------------- /Code/Python/readme.md: -------------------------------------------------------------------------------- 1 | # Codes in the Python language 2 | -------------------------------------------------------------------------------- /Code/C++/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mustafa-Hassan2001/Algo-Tree/HEAD/Code/C++/a.out -------------------------------------------------------------------------------- /Code/Java/RedBlackTree.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mustafa-Hassan2001/Algo-Tree/HEAD/Code/Java/RedBlackTree.java -------------------------------------------------------------------------------- /Code/Java/Dfs_Traversal.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mustafa-Hassan2001/Algo-Tree/HEAD/Code/Java/Dfs_Traversal.java -------------------------------------------------------------------------------- /Trie/readme.md: -------------------------------------------------------------------------------- 1 | # Trie 2 | 3 | A trie is a tree and each node in it contains the number of pointers equal to the number of 4 | characters of the alphabet. For example, if we assume that all the strings are formed with English 5 | alphabet characters “a” to “z” then each node of the trie contains 26 pointers. 6 | 7 | ## Questions : 8 | * Searching a word in trie ----> [C++](/Code/C++/searching_a_word_in_trie.cpp) 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/addition-of-algo.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Addition of New Algorithm 3 | about: add algorithm to this issue only 4 | title: '' 5 | labels: algo 6 | assignees: '' 7 | --- 8 | 9 | ## **Algorithm Name** 10 | 11 | - A clear and concise description of Algo 12 | 13 | ## **Describe the solution you'd like** 14 | 15 | - A clear and concise description of what you want to happen. 16 | 17 | ## Language: **If You are interested to work on this issue then Mention Language Used** 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Code/C++/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | In Fibonacci series, the current number is the sum of previous two numbers. 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int fib(int n){ 9 | if(n==0 || n==1) 10 | return n; 11 | int ans = fib(n-1)+fib(n-2); 12 | return ans; 13 | } 14 | 15 | int main() { 16 | 17 | int n; 18 | cin >> n; 19 | cout< 6 | using namespace std; 7 | 8 | int fact(int n){ 9 | if(n==0) 10 | return 1; 11 | int ans = n*fact(n-1); 12 | 13 | return ans; 14 | } 15 | 16 | int main() { 17 | 18 | int n; 19 | cin >> n; 20 | cout< [Java](/Code/Java/Long_Factorial.java) 4 | * Kahns_algorithm ----> [C++](/Code/C++/Kahns_algorithm.cpp) 5 | * Luhns_algorithm ----> [C++](/Code/C++/Luhns_algorithm.cpp) 6 | * Dutch National Flag Algorithm ----> [Java](/Code/Java/Segregate01and2.java) 7 | * Josephus Problem ----> [Python](/Code/Python/josephus_problem.py) 8 | * Trapping_Rainwater ----> [Python](/Code/Python/trapping_rainwater.py) 9 | * Multiplying large integer number algorithm ----> [C++](/Code/C++/Multiplying_large_integer_number.cpp) -------------------------------------------------------------------------------- /Code/C++/gcd.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int gcd(int a,int b){ 9 | if(b==0){ 10 | return a; 11 | } 12 | 13 | return gcd(b,a%b); 14 | } 15 | 16 | int main(){ 17 | 18 | int n1,n2; 19 | cin >>n1 >> n2; 20 | 21 | cout< [C++](/Code/C++/Huffman_encoding.cpp) 12 | * Find Minimum number of Coins ----> [Java](/Code/Java/greedyalgo.java) 13 | * Jump Game ----> [Java](/Code/Java/Jump_Game.java) -------------------------------------------------------------------------------- /Code/C++/insertion_at_start.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; 8 | 9 | int arr[10000]; 10 | 11 | for(int i=0;i> arr[i]; 13 | } 14 | 15 | int element; 16 | cin >> element; 17 | 18 | cout<<"Initial array \n"; 19 | for(int i=0;i=1;i--){ 25 | arr[i] = arr[i-1]; 26 | } 27 | 28 | arr[0] = element; 29 | 30 | cout<<"Final array \n"; 31 | for(int i=0;i<=n;i++){ 32 | cout< 7 | using namespace std; 8 | 9 | void permutation(char a[], int i){ 10 | 11 | if(a[i]=='\0'){ 12 | cout<> a; 26 | permutation(a,0); 27 | return 0; 28 | } 29 | 30 | /* 31 | 32 | Input : abc 33 | 34 | Output : 35 | abc 36 | acb 37 | bac 38 | bca 39 | cba 40 | cab 41 | 42 | Time Complexity: O(n*n!) 43 | Space Complexity: O(n*n!) 44 | 45 | */ -------------------------------------------------------------------------------- /.github/workflows/Auto_message_on_pr_merge.yml: -------------------------------------------------------------------------------- 1 | name: congratulations Message on PR merge 2 | 3 | on: 4 | pull_request_target: 5 | types: [closed] 6 | 7 | jobs: 8 | auto-response: 9 | runs-on: ubuntu-latest 10 | 11 | if: github.event.pull_request.merged == true 12 | steps: 13 | - uses: derekprior/add-autoresponse@master 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | with: 17 | respondableId: ${{ github.event.pull_request.node_id }} 18 | response: "Congratulations 🎉🎊, Your PR has been Merged and Thank you @${{ github.event.pull_request.user.login }} for taking out your valuable time in order to contribute to AlgoTree. Looking forward for more such amazing contributions :)" 19 | author: ${{ github.event.pull_request.user.login }} 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Code/Java/factorial.java: -------------------------------------------------------------------------------- 1 | /* 2 | Factorial is the product of all positive integers less than or equal to a given positive integer 3 | and denoted by that integer and an exclamation point. 4 | Thus, factorial seven is written 5!, meaning 1 × 2 × 3 × 4 × 5. 5 | Factorial zero is defined as equal to 1. 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class Factorial { 11 | public static void main(String[] args) { 12 | Scanner sc = new Scanner(System.in); 13 | int n = sc.nextInt(); 14 | System.out.println(fact(n)); 15 | } 16 | public static int fact(int n){ 17 | if(n==0) 18 | return 1; 19 | 20 | return n*fact(n-1); 21 | } 22 | } 23 | 24 | /* 25 | Test Cases: 26 | Input: 5 27 | Output: 120 28 | 29 | Input: 0 30 | Output: 1 31 | 32 | Time Complexity: O(n) 33 | Space Complexity: O(n) 34 | */ -------------------------------------------------------------------------------- /Code/C++/wave_print.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void waveprint(int a[][30], int r, int c){ 5 | for(int column = 0; column < c; column++){ 6 | if(column%2==0){ 7 | // even -->print top to botom 8 | 9 | for(int row = 0; row < r; row++){ 10 | cout << a[row][column]<<" "; 11 | } 12 | } 13 | else{ 14 | // odd --> print bottom to top 15 | for(int row = r-1; row>=0;row--){ 16 | cout<> r >>c; 31 | 32 | for(int i = 0; i < r; i++ ){ 33 | for(int j =0; j < c; j++){ 34 | cin >> a[i][j]; 35 | } 36 | } 37 | 38 | waveprint(a,r,c); 39 | 40 | 41 | return 0; 42 | } 43 | 44 | 45 | /* 46 | Test case : 47 | 48 | Input : 3 3 49 | 1 2 3 50 | 4 5 6 51 | 7 8 9 52 | 53 | Output : 1 4 7 8 5 2 3 6 9 54 | */ -------------------------------------------------------------------------------- /Code/Python/selection_sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PROBLEM STATEMENT: 3 | Implementation of Selection Sort for an array in Python 4 | ''' 5 | 6 | def selectionSort(array): 7 | size = len(array) 8 | 9 | for step in range(size): 10 | curr_index = step 11 | 12 | for i in range(step + 1, size): 13 | if array[i] < array[curr_index]: 14 | curr_index = i 15 | 16 | array[step], array[curr_index] = array[curr_index], array[step] 17 | 18 | arr = [-8, 24, 3, 0, 16] 19 | selectionSort(arr) 20 | print('Sorted Array in Ascending Order : ') 21 | print(arr) 22 | 23 | 24 | ''' 25 | Sorted Array in Ascending Order : 26 | [-8, 0, 3, 16, 24] 27 | ''' 28 | 29 | ''' 30 | Time Complexity: O(n^2) as there are two nested loops. 31 | 32 | Auxiliary Space: O(1) 33 | The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation. 34 | ''' 35 | -------------------------------------------------------------------------------- /Code/Java/GCD.java: -------------------------------------------------------------------------------- 1 | /*GCD of two number is the largest number by which the given number is divisable 2 | 3 | i.e. 4 | 5 | if the given two numbers are A(>0) and B(>0) and their GCD is G 6 | then A%G==0 and B%G==0 and G is the Biggest number*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class EuclideanGCD { 11 | public static void main(String[] args) { 12 | Scanner sc=new Scanner(System.in); 13 | int firstNumber=sc.nextInt(); 14 | int secondNumber=sc.nextInt(); 15 | System.out.println(GCD(firstNumber,secondNumber)); 16 | } 17 | public static int GCD(int A,int B){ 18 | if(B==0){ 19 | return(A); 20 | } 21 | return(GCD(B,(B%A))); 22 | } 23 | } 24 | /* 25 | Test Cases: 26 | Input: 12 16 27 | Output:4 28 | 29 | Input: 4 1 30 | Output: 1 31 | 32 | Time Complexity: O(log(max(a,b))) 33 | Space Complexity: 1 34 | */ 35 | -------------------------------------------------------------------------------- /Code/Python/factorial_without_recursion.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PROBLEM STATEMENT: 3 | Given a number, the task is to print its factorial. 4 | A factorial of a number 'n' is the product of numbers from 1 to n. 5 | ''' 6 | 7 | # A function to calculate factorial of a number and to print it 8 | def Factorial(n): 9 | fact = 1 10 | while n > 0: 11 | fact = fact*n 12 | n -= 1 13 | print(fact) 14 | 15 | # Driver Code 16 | n = int(input("Enter a number: ")) 17 | print("Factorial of", n, "is:", end=" ") 18 | # A function call to print factorial 19 | Factorial(n) 20 | 21 | ''' 22 | TEST CASES: 23 | 1. 24 | Input: 25 | Enter a number: 5 26 | Output: 27 | Factorial of 5 is: 120 28 | 29 | 2. 30 | Input: 31 | Enter a number: 8 32 | Output: 33 | Factorial of 8 is: 40320 34 | 35 | TIME COMPLEXITY: O(n), for traversing the numbers from 1 to n 36 | where, 'n' denotes the number entered by the user. 37 | SPACE COMPLEXITY: O(1), no extra space used. 38 | ''' 39 | -------------------------------------------------------------------------------- /.github/workflows/Auto_message_on_creatingissues.yml: -------------------------------------------------------------------------------- 1 | name: Auto message on Creating Issue. 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | jobs: 8 | greeting: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Create comment for issue 12 | if: github.event_name =='issues' 13 | uses: peter-evans/create-or-update-comment@v1 14 | with: 15 | issue-number: ${{tojson(github.event.issue.number)}} 16 | body: | 17 | Hi 😄, @${{ github.actor }} Thanks for creating issue at AlgoTree, do read and follow the [Code of Conduct](https://github.com/Algo-Phantoms/Algo-Tree/blob/main/CODE_OF_CONDUCT.md) and the [Contribution Guidelines](https://github.com/Algo-Phantoms/Algo-Tree/blob/main/GUIDLINES.md) while contributing. Refer to PR's which has been merged earlier in AlgoTree [Click Here](https://github.com/Algo-Phantoms/Algo-Tree/pulse#merged-pull-requests) Like, How many File they have changed?, Which type of files need to be change? and many more. 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Code/C++/check_prime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | #define ll long long 6 | 7 | const int n = 1000000; 8 | bitset<1000000> b; 9 | vector primes; 10 | 11 | void sieve() { 12 | 13 | //set all bits 14 | b.set(); 15 | 16 | b[0]=b[1] = 0; 17 | 18 | for(ll i=2; i<=n;i++){ 19 | if(b[i]){ 20 | primes.push_back(i); 21 | for(ll j=i*i; j<=n;j = j+i){ 22 | b[j]=0; 23 | } 24 | } 25 | } 26 | } 27 | 28 | bool isPrime(ll no){ 29 | if(no<=n){ 30 | return b[no]== 1? true : false; 31 | } 32 | 33 | for(ll i=0;primes[i]*(ll)primes[i]<=no;i++){ 34 | if(no%primes[i] ==0 ){ 35 | return false; 36 | } 37 | } 38 | return true; 39 | } 40 | int main(){ 41 | 42 | sieve(); 43 | int n; 44 | cin >> n; 45 | 46 | if(isPrime(n)){ 47 | cout<<"yes"; 48 | } 49 | else { 50 | cout<<"no"; 51 | } 52 | 53 | return 0; 54 | } 55 | 56 | /* 57 | Test case : 58 | 59 | Input : 45 60 | Output : no 61 | 62 | */ -------------------------------------------------------------------------------- /Code/Python/Brian_Kernighan's_Algorithm.py: -------------------------------------------------------------------------------- 1 | """ 2 | Brian Kernighan's Algorithm 3 | Given a number "num", you to give the number of setbits in the number. 4 | The setbit is "1" in the binary form of given number. 5 | For example: number of set bits in 5 is 2 since its binary 6 | representation is '101' where count of 1 is 2. 7 | """ 8 | def countBits(num): 9 | # variable for number of setbits 10 | cnt = 0 11 | 12 | # number of times this loop run, will give the number of setbits 13 | while(num): 14 | num = num&(num-1) #n&(n-1) will unset the rightmost bit 15 | cnt += 1 16 | return cnt 17 | 18 | 19 | # taking input number from user 20 | num = int(input()) 21 | 22 | # calling the function count to count the setbits 23 | print(countBits(num)) 24 | 25 | 26 | """ 27 | Test Cases 28 | 1. 29 | Input - 12 30 | Output - 2 31 | 32 | 2. 33 | Input - 101 34 | Output - 4 35 | 36 | Time complexity: O(logn) where n is the input number whose set bit is to be count 37 | Space complexity: O(1), since no extra space is used 38 | 39 | """ -------------------------------------------------------------------------------- /Code/Python/linearsearch.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | Linear search, also known as sequential search, is a search algorithm which examines each element in the order it is presented to find the specified data. 4 | 5 | ''' 6 | #Linear Search Function 7 | def linearSearch(item,l): 8 | found = False 9 | position = 0 10 | #Traversing through array and checking if element is present 11 | while position < len(l) and not found: 12 | if l[position] == item: 13 | found = True 14 | position = position + 1 15 | return found 16 | 17 | #Obtaining the list from input 18 | l = list(map(int,input().strip().split())) 19 | item = int(input()) 20 | 21 | #Calling the linear search fuction 22 | itemFound = linearSearch(item,l) 23 | 24 | #Displaying the output 25 | if itemFound: 26 | print ('True') 27 | else: 28 | print ('False') 29 | 30 | ''' 31 | 32 | Test Case : 33 | 34 | Input : 100 56 789 456 321 35 | 789 36 | 37 | Output : True 38 | 39 | Input : 1000 2000 3000 5000 40 | 4000 41 | 42 | Output : False 43 | 44 | Time Complexity: O(n) 45 | 46 | Space Complexity : O(1) 47 | 48 | ''' 49 | -------------------------------------------------------------------------------- /Code/C++/insertion _at_end.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | At any point in time, we know the index of the last element of the Array, 3 | as we've kept track of it in our length variable. All we need to do for inserting an element 4 | at the end is to assign the new element to one index past (n-1) the current last element. 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | 12 | int n; 13 | cin >> n; 14 | 15 | int arr[10000]; 16 | 17 | 18 | for(int i=0;i> arr[i]; 20 | } 21 | 22 | int element; 23 | cin >> element; 24 | cout<<"Initial array \n"; 25 | for(int i=0;i 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int n; 13 | cout << "Enter the number of elements in the array : "; 14 | cin >> n; 15 | vector v(n); 16 | cout << "\nEnter the elements of the array : \n"; 17 | for (int i = 0; i < n; i++) 18 | { 19 | cin >> v[i]; 20 | } 21 | 22 | int peak; 23 | for(int i=0;i=v[1]) || (i==n-1 && v[n-1]>=v[n-2]) || (v[i]>=v[i-1] && v[i]>=v[i+1]) ) 26 | { 27 | peak = v[i]; 28 | break; 29 | } 30 | } 31 | cout << "Peak element : " << peak << "\n"; 32 | return 0; 33 | } 34 | 35 | /** 36 | Eg. : 37 | Input: 38 | 7 39 | 10 20 15 2 23 90 67 40 | 41 | Output: 42 | Peak element : 20 43 | 44 | Time Complexity : O(N) 45 | Space Complexity : O(N) 46 | **/ 47 | -------------------------------------------------------------------------------- /Code/C++/longest_subarray_with_sum_k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int longestsubarry(int arr[],int n,int k){ 6 | 7 | // csum, index 8 | unordered_map m; 9 | int pre = 0; 10 | 11 | int len = 0; 12 | 13 | for(int i=0;i> n>>k; 40 | 41 | int arr[n]; 42 | 43 | for(int i=0;i> arr[i]; 45 | } 46 | 47 | cout< 6 | using namespace std; 7 | 8 | void unique_prime(int n){ 9 | int arr[n+1]; 10 | memset(arr , 1 , n+1); 11 | //first find all prime factors till n by sieves method 12 | for(int i = 2 ; i <= sqrt(n) ; i++) { 13 | if(arr[i]==0){ 14 | continue; 15 | } 16 | for(int j = i*i ; j <=n ; j += i){ 17 | arr[j] = 0; 18 | 19 | } 20 | } 21 | //now check which prime number are factor of n 22 | cout<<"All unique prime factors of "<> num; 34 | unique_prime(num); 35 | } 36 | 37 | /* Sample Input 38 | Enter the number: 5446 39 | Sample output 40 | All Unique prime factors of 5446 are: 2 7 389 41 | */ 42 | /* Time complaxity : O(n + n(log(logn))) 43 | Space Complaxity : O(n) 44 | */ 45 | -------------------------------------------------------------------------------- /Code/C++/phone_keypad.cpp: -------------------------------------------------------------------------------- 1 | /*Problem Statement: 2 | Given an integer array containing digits from [0, 9], 3 | the task is to print all possible letter combinations that the numbers could represent. */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | char keypad[][10]={" ","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"}; 9 | 10 | void generate_names(char *in,char *out,int i,int j) 11 | { 12 | //Base case 13 | if(in[i]=='\0') 14 | { 15 | out[j]='\0'; 16 | cout<>in; 32 | char out[100]; //Denotes the output string 33 | generate_names(in,out,0,0); 34 | return 0; 35 | } 36 | /* Testcases : 37 | 1) Input : 23 38 | Output : 39 | DG 40 | DH 41 | DI 42 | EG 43 | EH 44 | EI 45 | FG 46 | FH 47 | FI 48 | 2) Input : 67 49 | Output : 50 | PT 51 | PU 52 | PV 53 | QT 54 | QU 55 | QV 56 | RT 57 | RU 58 | RV 59 | ST 60 | SU 61 | SV 62 | Time Complexity : O(4^n) 63 | Space Complexity : O(n) 64 | Here, n denotes the no of characters present in the input string 65 | */ 66 | 67 | -------------------------------------------------------------------------------- /Code/Python/SlidingWindowMax.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Description: 3 | Given an array of N elements and a value K (K <= N) , calculate maximum summation 4 | of K consecutive elements in the array. 5 | ''' 6 | # Python Code: 7 | 8 | # number of entries in array 9 | n=int(input()) 10 | # number of consecutive elements 11 | k=int(input()) 12 | 13 | # Whole array input 14 | lst = list(map(int,input().strip().split()))[:n] 15 | 16 | sum=0 17 | if(n==k): 18 | for i in range(0,n): 19 | sum+= lst[i] 20 | 21 | print (sum) 22 | 23 | if(n>k): # calculate sum of first window of size K 24 | mxsum=0 25 | wnsum=0 26 | for i in range(0,k): 27 | mxsum+= lst[i] 28 | 29 | wnsum=mxsum # calculate sum of remaining windows 30 | for i in range(k,n): 31 | wnsum+=(lst[i]-lst[i-k]) 32 | if(wnsum>mxsum): 33 | mxsum=wnsum 34 | 35 | print (mxsum) 36 | 37 | 38 | ''' 39 | Test Cases Standard I/O 40 | 41 | 1. if N == K 42 | 43 | N= 5 44 | K= 5 45 | lst= { 1 2 3 4 5 } 46 | 47 | Output : 15 48 | 49 | 2. if N > K 50 | 51 | N= 5 52 | K= 3 53 | lst= { 5 2 -1 0 3 } 54 | 55 | Output : 6 56 | 57 | 58 | Time Complexity : O(N) # here N= number of entries in the array 59 | Space Complexity : O(1) 60 | ''' 61 | 62 | 63 | -------------------------------------------------------------------------------- /Code/C++/print_subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a character array of size n, print all the subsets of the set . 3 | 4 | Approach: 5 | 6 | * Start from num = 2^n - 1 upto 0. 7 | * Consider the binary representation of num with n bits. 8 | * Start from the leftmost bit which represents 1, the second bit represents 2 and so on until nth bit which represents n. 9 | * Print the number corresponding to the bit if it is set. 10 | * Perform the above steps for all values of num until it is equal to 0. 11 | 12 | */ 13 | 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | void subset(char c[]){ 19 | 20 | int l = strlen(c)-1; 21 | // 2^n - total subsets 22 | int tot = 1<> n; 40 | char c[n]; 41 | cin >> c; 42 | subset(c); 43 | return 0; 44 | } 45 | 46 | /* 47 | 48 | Test Case : 49 | 50 | Input : 51 | 3 52 | ABC 53 | 54 | Output : 55 | 56 | A 57 | B 58 | AB 59 | 60 | Time Complexity: O(n*2^n) 61 | Space Complexity: O(1) 62 | 63 | */ -------------------------------------------------------------------------------- /Code/Java/Taylorseries.java: -------------------------------------------------------------------------------- 1 | /* 2 | Here for Finding sum of Taylor Series of e^x, we Create 2 functions, one for 3 | calculating factorial [factorial(x)] with help of recursion to make good time & Space Complexity 4 | and other [ex(x,n)] for calculating value of Taylor Series. 5 | */ 6 | 7 | package taylor; 8 | import java.util.Scanner; 9 | 10 | public class Taylorseries { 11 | public static void main(String[] args){ 12 | Scanner scan = new Scanner(System.in); 13 | System.out.println("Enter Value of x :"); 14 | int x = scan.nextInt(); 15 | System.out.println("Enter Value of n :"); 16 | int n = scan.nextInt(); 17 | int ans = ex(x,n); 18 | System.out.println("Value of Taylor Series of e^x is : "+ans); 19 | } 20 | public static int ex(int x, int n){ 21 | int ans = 1; 22 | for (int i = 1;i<=(n-1);i++){ 23 | ans += (x/factorial(i)); 24 | } 25 | return ans; 26 | } 27 | public static int factorial(int x){ 28 | if (x == 0){ 29 | return 1; 30 | }else { 31 | return (x*factorial(x-1)); 32 | } 33 | } 34 | } 35 | /* 36 | Test Cases: 37 | Input: 7 8 38 | Output: 12 39 | 40 | Input: 3 25 41 | Output: 5 42 | 43 | Time Complexity: O(n) 44 | Space Complexity: O(1) 45 | */ 46 | -------------------------------------------------------------------------------- /Code/C++/spiral_print.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void spiralprint(int a[][30], int r, int c){ 5 | 6 | //start row 7 | int sr = 0; 8 | 9 | //end row 10 | int er = r-1; 11 | 12 | // start coloumn 13 | int sc = 0; 14 | 15 | //end column 16 | int ec = c-1; 17 | int ele = 0; 18 | while(ele < r*c){ 19 | 20 | // top row 21 | for(int i=sc; i<=ec;i++){ 22 | cout << a[sr][i] <<" "; 23 | ele++; 24 | } 25 | sr++; 26 | if(ele == r*c) 27 | break; 28 | 29 | // last column 30 | for(int i=sr; i<=er;i++){ 31 | cout << a[i][ec] <<" "; 32 | ele++; 33 | } 34 | ec--; 35 | if(ele == r*c) 36 | break; 37 | 38 | // last row 39 | for(int i=ec; i>=sc;i--){ 40 | cout << a[er][i] <<" "; 41 | ele++; 42 | } 43 | er--; 44 | if(ele == r*c) 45 | break; 46 | 47 | // first coloumn 48 | for(int i=er;i>=sr;i--){ 49 | cout << a[i][sc] <<" "; 50 | ele++; 51 | } 52 | sc++; 53 | 54 | } 55 | 56 | } 57 | 58 | int main() { 59 | 60 | int a[30][30]; 61 | 62 | int r, c; 63 | cin >> r >>c; 64 | 65 | for(int i = 0; i < r; i++ ){ 66 | for(int j =0; j < c; j++){ 67 | cin >> a[i][j]; 68 | } 69 | } 70 | 71 | spiralprint(a,r,c); 72 | 73 | return 0; 74 | } 75 | 76 | /* 77 | Test Cases : 78 | 79 | Input : 3 3 80 | 1 2 3 81 | 4 5 6 82 | 7 8 9 83 | 84 | Output : 1 2 3 6 9 8 7 4 5 85 | */ -------------------------------------------------------------------------------- /GUIDLINES.md: -------------------------------------------------------------------------------- 1 | ## To raise the `Pull Request` 2 | 3 | 1. Make 1 `Pull Request` for 1 `issue`. Otherwise, you may lose points. 4 | 5 | 2. Mention `Issue number` while creating Pull Request in the `description box` or link the issue from the right options. This helps to link the PR with the respective issue. 6 | 7 | 3. Always update the readme for the respective code added in the appropriate folder. 8 | 9 | 4. **CODE FORMAT** 10 | 11 | ``` 12 | 1. Include a description of code in Multiline Comments 13 | 2. Write code in the allotted language. 14 | `( Include single line comments about the code line wherever required)` 15 | 3. Include 2 Test case: 16 | "Test Case 17 | Input - 18 | Output - 19 | 20 | Input - 21 | Output - 22 | " 23 | 4. Include Time and Space Complexity 24 | ``` 25 | 26 | 5. Always take `Dynamic Input` from the user. 27 | 6. `Avoid Plagiarism` Never copy from other websites. 28 | This might affect your results on the leaderboard of gssoc'21. 29 | 7. `Merge your commits` when changes requested. 30 | 31 | 32 | 33 | ## To raise a `valid Issue` 34 | 1. Do `not` create `duplicate issues`. 35 | 2. Always look for issues previously created before creating an issue of a particular topic. (`Use Filters`) 36 | 3. All issues are assigned on `First Come, First Serve Basis`. 37 | -------------------------------------------------------------------------------- /Code/Python/Kth_Minimum_in_Array.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from heapq import heappop 3 | 4 | 5 | # Function to find the k'th smallest element in a list using min-heap 6 | def kthSmallest(arr, kth): 7 | 8 | # transform the input list into a min-heap 9 | heapq.heapify(arr) 10 | 11 | # pop from min-heap exactly `k-1` times 12 | while kth > 1: 13 | heappop(arr) 14 | kth = kth - 1 15 | 16 | # return the root of min-heap 17 | return arr[0] 18 | 19 | # Driver code 20 | if __name__ == '__main__': 21 | 22 | arr = [] 23 | n = int(input("Enter number of elements: ")) 24 | print("Enter elements: ") 25 | for i in range(n): 26 | element = int(input()) 27 | arr.append(element) 28 | 29 | k = int(input("Enter the number k: ")) 30 | print("K'th smallest element is", 31 | kthSmallest(arr, k)) 32 | 33 | 34 | ''' 35 | Time Complexity: O(N + klog(N)) (where N is number of elements in array and K is the position) 36 | Space Complexity: O(N) 37 | Example 1: 38 | Input: 39 | Enter number of elements: 40 | 6 41 | Enter elements: 42 | 7 10 4 3 20 15 43 | Enter the number k: 44 | 3 45 | Output: 46 | K'th smallest element is: 47 | 7 48 | Example 2: 49 | Input: 50 | Enter number of elements: 51 | 7 52 | Enter elements: 53 | 8 1 0 9 5 11 4 54 | Enter the number k: 55 | 4 56 | Output: 57 | K'th smallest element is: 58 | 5 59 | ''' 60 | -------------------------------------------------------------------------------- /Code/Java/inverseofarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | ---------------- INVERSE OF AN ARRAY ---------------------- 3 | If the array elements are swapped with their corresponding indices, 4 | then the array finally results is called as inverse of an array. 5 | */ 6 | 7 | package peakval; 8 | import java.util.Scanner; 9 | 10 | public class peakvalueinarray { 11 | public static void main(String[] args) { 12 | Scanner scan = new Scanner(System.in); 13 | System.out.println("Enter Size of Arraay"); 14 | int n = scan.nextInt(); 15 | int[] arr = new int[n]; 16 | // Taking Array Elements 17 | for (int i = 0; i < n; i++) { 18 | arr[i] = scan.nextInt(); 19 | } 20 | inversearrray(arr); 21 | } 22 | 23 | public static void inversearrray(int[] arr){ 24 | int[] ans = new int[arr.length]; 25 | for (int i = 0; i 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | //function to reverse the string 15 | void reverse(string &s) 16 | { 17 | int i; 18 | //Creating empty stack 19 | stack str; 20 | //pushing each character of the string into the stack 21 | for(char ch:s) 22 | { 23 | str.push(ch); 24 | } 25 | //popping each character one by one from the stack 26 | for(i=0;i>s; 40 | //calling function 41 | reverse(s); 42 | //printing result 43 | cout< 19 | 20 | - [ ] I have placed my code file in the (/Code) Folder e.g. If it's a Code in JAVA then I have placed my code pr_name.java file in (/Code/Java/) Directory. 21 | - [ ] I have Added the Description, Approach, and Working of Code at the beginning of Code. 22 | - [ ] I have added 2 or more Testcases at the Bottom side of the Code. 23 | - [ ] I have Added Time and Space Complexity at the End of the Code. 24 | - [ ] I have Explained the Variables use in Complexity e.g. O(n) where n is the length of an array. 25 | - [ ] I have Updated the Readme Related to the Topics e.g., if the issue is regarding Matrix then Update the Readme.MD present in 2D_Array Folder. 26 | - [ ] I have added Proper Comments in between the Code for Better Explanation. 27 | - [ ] I have sorted the list of the Readme.MD where I have added the issue in the Alphabetical Order. 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Code/Python/inverseArray.py: -------------------------------------------------------------------------------- 1 | '''INVERSE OF AN ARRAY 2 | Problem statement: If the array elements are swapped with their correseponding 3 | indices,we get the inverse of an array 4 | NOTE: The elements must be unique and less than the length of array. 5 | ''' 6 | 7 | #inserts the elements in an array of size n 8 | def inputElements(n): 9 | arr=[] 10 | for i in range(n): 11 | #enter element to insert in array 12 | element=int(input()) 13 | arr.append(element) 14 | print("original array:",arr) 15 | return arr 16 | 17 | #function to find inverse of array 18 | def inverseArray(lst): 19 | inverted_array=[] 20 | for i in range(0,len(lst)): 21 | k=lst[i] 22 | inverted_array.insert(k,i) 23 | return inverted_array 24 | 25 | #main code 26 | # enter length of array 27 | array_length=int(input()) 28 | arr=inputElements(array_length) 29 | arr2=inverseArray(arr) 30 | print("Inverse of array :",arr2) 31 | 32 | ''' 33 | TestCases : 34 | Input : 35 | 5 36 | 2 37 | 4 38 | 1 39 | 0 40 | 3 41 | 42 | Output: 43 | original array: [2,4,1,0,3] 44 | Inverse of array: [3,2,0,4,1] 45 | 46 | Input : 47 | 4 48 | 1 49 | 3 50 | 0 51 | 2 52 | 53 | Output : 54 | Original array:[1,3,0,2] 55 | Inverse of array:[2,0,3,1] 56 | 57 | Time Complexity: O(n) for traversing array of characters where size is n 58 | Space Complexity:O(n),where n is size of array 59 | 60 | ''' 61 | -------------------------------------------------------------------------------- /Code/C++/josephus_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This is a theoretical computer science problem. 4 | There are n people in a circle waiting to be executed. 5 | Starting from any position, a person starts executing the k'th person ahead of him, 6 | then the person after the one who is executed repeats the same task, 7 | as there will be only one person surviving, we have to find the person who will remain alive. 8 | 9 | */ 10 | 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | void josephus(vector &v, int k, int idx, int &ans) 16 | { 17 | if (v.size() == 1) 18 | { // only one person will be left, which is the answer 19 | ans = v[0]; 20 | return; 21 | } 22 | 23 | idx = (idx + k - 1) % v.size(); 24 | v.erase(v.begin() + idx); 25 | josephus(v, k, idx, ans); 26 | } 27 | 28 | int main() 29 | { 30 | // use vector, if persons are not listed from 1 to n 31 | vector lst; 32 | int n, k, ans = 0; 33 | cin >> n >> k; 34 | lst.reserve(n); 35 | for (int i = 0; i < n; i++) 36 | { 37 | lst.push_back(i + 1); 38 | } 39 | // lst = {1,2,3,4,..,n} 40 | josephus(lst, k, 0, ans); 41 | cout << ans << endl; 42 | return 0; 43 | } 44 | 45 | /* 46 | 47 | Test Case: 48 | 49 | Input: 3 2 50 | Output: 3 51 | 52 | Input: 4 6 53 | Output: 3 54 | 55 | Input: 32 32 56 | Output: 27 57 | 58 | Time Complexity: O(n) 59 | Space Complexity: O(n) 60 | 61 | */ 62 | -------------------------------------------------------------------------------- /Code/C++/row_wise_sum.cpp: -------------------------------------------------------------------------------- 1 | /* ROW WISE SUM OF A 2D ARRAY : 2 | For a given 2-D integer type array of size (N x M), find and print the sum of each of the row elements in a single line, separated by a single space.*/ 3 | 4 | #include 5 | using namespace std; 6 | 7 | void row_wise_sum(int *arr,int r,int c) 8 | { 9 | for (int i = 0; i < r ; i++) 10 | { 11 | int sum = 0; 12 | for (int j = 0; j < c ; j++) 13 | { 14 | sum += *((arr + i * c) + j); 15 | } 16 | cout << sum << " "; 17 | } 18 | } 19 | 20 | int main() 21 | { 22 | int rows,cols; 23 | cout<<"Enter the number of rows and columns:"; 24 | cin >> rows >> cols; 25 | int arr[rows][cols]; 26 | 27 | cout<<"Enter the elements of the 2D array:\n"; 28 | for(int i = 0; i < rows; i++) 29 | { 30 | for(int j = 0; j < cols; j++) 31 | { 32 | cin >> arr[i][j]; 33 | } 34 | } 35 | 36 | cout<<"Row-wise Sum:"<>= 1; 35 | odd <<= 1; 36 | 37 | System.out.println(even | odd); 38 | } 39 | } 40 | 41 | /* TEST CASES 42 | 43 | 1)Input: 44 | Enter the number: 45 | 25 46 | Output: 47 | 38 48 | 49 | 2)Input: 50 | Enter the number: 51 | 32 52 | Output: 53 | 16 54 | 55 | 56 | Time Complexity: O(1) 57 | Space Complexity: O(1) 58 | */ 59 | 60 | 61 | -------------------------------------------------------------------------------- /Code/Python/left_rotation.py: -------------------------------------------------------------------------------- 1 | #Ques: Rotate an array of size n , x number of times. 2 | #language : Python 3 | #input: Enter size of array: ----->user will be asked for no. of elemnts which is to be insert in an array 4 | # Give data: ----->now user have to provide space seperated integers 5 | # Enter the number of times array should be rotated from left: ----->no. of times user want aray to be rotated from left 6 | 7 | 8 | #output: ---->prints spaces seperated integers rotated several times from left 9 | 10 | 11 | n = int(input('Enter size of array:')) 12 | rot = [] 13 | print('Give data: ') 14 | rot=list(map(int,input().split())) 15 | 16 | pos = int(input('Enter the number of times array should be rotated from left:')) 17 | 18 | for i in range(pos): 19 | temp = rot[0] 20 | for j in range(1, n): 21 | rot[j - 1] = rot[j] 22 | rot[n-1] = temp 23 | 24 | for k in range(0, n): 25 | print(rot[k],end=" ") 26 | 27 | #Time Complexity: O(n*k) size of array * no. of time array to be rotated 28 | #Space: O(1) fixed amount of space is required 29 | 30 | #e.g: 31 | # Enter size of array:7 32 | # Give data: 33 | # 12 11 3 13 5 6 7 34 | # Enter the position from where u want left rotation:2 35 | # 3 13 5 6 7 12 11 36 | 37 | 38 | # Enter size of array:5 39 | # Give data: 40 | # 1 2 3 4 5 41 | # Enter the position from where u want left rotation:2 42 | # 3 4 5 1 2 43 | -------------------------------------------------------------------------------- /Code/C++/factorial_using_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* In this Problem, our objective was to find the factorial of a number n entered by the user. 2 | Factorial of a number n is n! = n*(n-1)*(n-2)*........*1 3 | Using recursion we can write factorial of n as n! = n*(n-1)! 4 | We used n = 0 as our base case (0! = 1), i.e. 5 | if(n == 0) : return 1; 6 | */ 7 | 8 | #include // header file required for Input/Output in the program 9 | using namespace std; 10 | 11 | int factorial(int n) // Function to calculate this factorial 12 | { if(n == 0) // Base Case if n = 0 13 | return 1; // 0! = 1 14 | return n*factorial(n-1); // Multiplied the current number and recursed the factorial (n-1) 15 | } 16 | 17 | int main() // main function from where the execution of code starts 18 | { int n; // number for which we need to find factorial 19 | cin >> n; // number input by the user 20 | cout << factorial(n) < 11 | using namespace std; 12 | 13 | 14 | //function to check perfect number 15 | void check_perfect_number(int num) 16 | { 17 | 18 | int sum = 0; 19 | int i; 20 | 21 | 22 | //loop till half the number because further the multiples will be greater than the number itself. 23 | for(i = 1 ; i <= (num/2) ; i++) 24 | { 25 | int rem = num%i; 26 | 27 | if(rem == 0) 28 | sum = sum + i; 29 | } 30 | 31 | if(num == sum) 32 | cout<<"You entered a perfect number\n"; 33 | 34 | else 35 | cout<<"Not perfect number\n"; 36 | 37 | } 38 | 39 | //main 40 | int main(){ 41 | 42 | int number, sum = 0, rem, i; 43 | 44 | cout<<"Enter number:\n"; 45 | cin>>number; 46 | 47 | //function call 48 | check_perfect_number(number); 49 | 50 | return 0; 51 | 52 | } 53 | 54 | 55 | /* 56 | 57 | Test cases: 58 | 1. Input : Enter any number: 6 59 | Output : You entered a perfect number 60 | 61 | 62 | 2.Input: Enter any number: 15 63 | Output: Not perfect number 64 | 65 | Time complexity: O(n) 66 | Space Complexity : O(1) 67 | 68 | */ 69 | -------------------------------------------------------------------------------- /Code/Java/Longest_Common_Prefix.java: -------------------------------------------------------------------------------- 1 | /* Here is the code for finding the Longest Conmmon Prefix 2 | from the input provided by user. 3 | 4 | _______________________________________________________________ 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class Main { 10 | private static String longestCommonPrefix(String[] strs) { 11 | String lcp = ""; 12 | 13 | if(strs.length == 0 || strs == null) { 14 | return lcp; 15 | } 16 | 17 | int index = 0; 18 | 19 | for(char c : strs[0].toCharArray()) { 20 | for(int i = 1; i < strs.length; i++) { 21 | if(index >= strs[i].length() || c != strs[i].charAt(index)) { 22 | return lcp; 23 | } 24 | } 25 | lcp += c; 26 | index++; 27 | } 28 | 29 | return lcp; 30 | } 31 | public static void main(String[] args) 32 | { 33 | Scanner sc = new Scanner(System.in); 34 | String str = sc.nextLine(); 35 | String[] words = str.split("\\s+"); 36 | System.out.println(longestCommonPrefix(words)); 37 | } 38 | } 39 | 40 | /* 41 | Time complexity: 42 | O(N) as depends on the characters given in the string 43 | 44 | Space complexity: 45 | O(1) Takes constant space. 46 | */ 47 | 48 | /* 49 | Test cases: 50 | Input: small smile smell 51 | Output: sm 52 | 53 | Input: flight flock fly 54 | Output: fl 55 | */ 56 | 57 | -------------------------------------------------------------------------------- /Code/Python/GCD.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | GCD(GREATEST COMMON DIVISOR) 4 | 5 | APPROACH: 6 | 7 | The solution is to use Euclidean algorithm which is the main algorithm used for the calculation of GCD of two numbers. 8 | The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number. This step is repeated 9 | until second number becomes zero . When second number becomes 0 , the first number is the GCD of the two given numbers as 10 | every number divides 0. 11 | 12 | """ 13 | 14 | #recursive function that returns GCD of 2 numbers 15 | def gcd (a, b): 16 | if (b == 0): #every number divides 0 so return a 17 | return a 18 | else: 19 | return gcd (b, a % b) 20 | 21 | #input 1st number 22 | a =int (input ("Enter the first number: ")) 23 | #input 2nd number 24 | b =int (input ("Enter the second number: ")) 25 | 26 | #call to GCD(A,B) 27 | gcd_ans = gcd(a, b) 28 | #prints the GCD of two numbers given by the user 29 | print("GCD of two number is: ", gcd_ans) 30 | 31 | 32 | """ 33 | TESTCASES : 34 | 35 | TESTCASE-1: 36 | INPUT : 2 37 | 4 38 | OUTPUT : GCD of two number is: 2 39 | TESTCASE-2: 40 | INPUT : 2 41 | 5 42 | OUTPUT : GCD of two number is: 1 43 | TESTCASE-3: 44 | INPUT : 0 45 | 4 46 | OUTPUT : GCD of two number is: 4 47 | 48 | 49 | TIME COMPLEXITY = O(log(max(a,b))) 50 | SPACE COMPLEXITY= O(1) 51 | """ -------------------------------------------------------------------------------- /Code/Java/sqrt.java: -------------------------------------------------------------------------------- 1 | /* 2 | By using Binary Search, 3 | When x is equal to square of mid then square root is mid Hence, Retuen Mid, 4 | But If x Becomes Just Greater than swaure of mid then Square rool become mid -1 5 | i.e just less by one from mid 6 | Here answer is updated when mid*mid is smaller than x, 7 | and move closer to sqrt(x) 8 | */ 9 | package squareroot; 10 | import java.util.Scanner; 11 | 12 | public class sqrt { 13 | public static void main(String[] args) 14 | { 15 | Scanner scan = new Scanner(System.in); 16 | int x = scan.nextInt(); 17 | System.out.println(floorSqrt(x)); 18 | } 19 | 20 | public static int floorSqrt(int x) 21 | { 22 | if (x == 0 || x == 1) { 23 | return x; 24 | } 25 | // Using Binary Search 26 | int start = 1, end = x, ans=0; 27 | while (start <= end) 28 | { 29 | int mid = (start + end) / 2; 30 | if (mid*mid == x) { 31 | return mid; 32 | } 33 | if (mid*mid < x) { 34 | start = mid + 1; 35 | ans = mid; 36 | } else { 37 | end = mid - 1; 38 | } 39 | } 40 | return ans; 41 | } 42 | } 43 | /* 44 | Test Cases: 45 | Input: 9 46 | Output: 3 47 | 48 | Input: 8 49 | Output: 2 50 | 51 | Time Complexity: O(log n) where n is the given number 52 | Space Complexity: O(1) 53 | */ 54 | -------------------------------------------------------------------------------- /Code/C++/Geek-onacciNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Description : 3 | Geek created a random series and given a name geek-onacci series. Given four 4 | integers x, y, z, N. x, y, z represents the first three numbers of geek-onacci series. 5 | Find the Nth number of the series. The nth number of geek-onacci series is a sum of the 6 | last three numbers (summation of N-1th, N-2th, and N-3th geek-onacci numbers). 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | //function to find geek number 13 | int geek_num(int a, int b, int c, int n) 14 | { 15 | int sum; 16 | for (int i = 4; i <= n; i++) 17 | { 18 | sum = a + b + c; 19 | a = b; 20 | b = c; 21 | c = sum; 22 | } 23 | return sum; 24 | } 25 | 26 | int main() 27 | { 28 | int a, b, c, n; 29 | cout << "Enter first , second , third and Nth number : " << endl; 30 | cin >> a >> b >> c >> n; 31 | cout << "Nth number of the series : " << endl; 32 | //function call 33 | cout << geek_num(a, b, c, n) << endl; 34 | 35 | return 0; 36 | } 37 | 38 | /* 39 | Time complexity : O(log n) 40 | Space complexity : O(1) 41 | */ 42 | 43 | /* 44 | Test Case 1 : 45 | Input : 46 | Enter first , second , third and Nth number : 47 | 1 3 2 4 48 | Output : 49 | Nth number of the series : 50 | 6 51 | 52 | Test Case 2 : 53 | Input : 54 | Enter first , second , third and Nth number : 55 | 1 3 2 6 56 | Output : 57 | Nth number of the series : 58 | 19 59 | */ -------------------------------------------------------------------------------- /Code/Java/Uniquefactor.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find all unique prime factors of any number n where (n>1) for example if n is 20 then output will be (2,5). 3 | Firstly we will check from i = 2 to n whether that i is a factor of n or not ? 4 | if i is a factor of n then we check it is prime or not using isPrime Method in Java which return boolean type output 5 | */ 6 | 7 | package bhagwat; 8 | import java.util.Scanner; 9 | 10 | public class Uniquefactor { 11 | public static void main(String[] args){ 12 | Scanner scan = new Scanner(System.in); 13 | System.out.println("Enter Number : "); 14 | int n = scan.nextInt(); 15 | System.out.println(); 16 | System.out.println("Unique Prime Factors of "+n+" are :"); 17 | for (int i = 2;i<=n;i++){ 18 | if (n%i == 0 && isPrime(i)){ 19 | System.out.print(i+" "); 20 | } 21 | } 22 | } 23 | public static boolean isPrime(int n){ 24 | if (n == 2){ 25 | return true; 26 | } 27 | if (n>2) { 28 | for (int i = 2; i < n; i++) { 29 | if (n % i == 0) { 30 | return false; 31 | } 32 | } 33 | }else { 34 | return false; 35 | } 36 | return true; 37 | } 38 | } 39 | /* 40 | Test Cases: 41 | Input: 10 42 | Output: 2 5 43 | 44 | Input: 48 45 | Output: 2 3 46 | 47 | Time Complexity: O(n) 48 | Space Complexity: O(1) 49 | */ -------------------------------------------------------------------------------- /Code/C++/binary_string_to_decimal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A string containing only 0's and 1's is called a binary string. 3 | The equivalent decimal of a binary number is the sum of 2 raised to the power of the positional values where 1 is present. 4 | The least significant bit is assigned positional value 0. 5 | The following program illustrates how to convert a binary string to its equivalent decimal 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | int main() 13 | { 14 | string s; 15 | 16 | // Taking input the binary string from the user 17 | cin >> s; 18 | 19 | // Assigning a variable to store the size of the string 20 | int n = s.size(); 21 | 22 | // Initializing a variable named decimal to 0 which stores the decimal equivalent of the inputted binary string 23 | int decimal = 0; 24 | 25 | // Running a loop to convert the binary to its equivalent decimal 26 | for(int i = n-1;i >= 0;i--) 27 | { 28 | // Updating the variable decimal if the ith position of the string has value '1' 29 | if(s[i] == '1') 30 | decimal += (int)pow(2,abs(i-(n-1))); 31 | } 32 | 33 | // Printing the equivalent decimal of the inputted binary string 34 | cout << decimal; 35 | 36 | return 0; 37 | 38 | } 39 | 40 | /* 41 | TEST CASES: 42 | 43 | Sample input : 1100 44 | Standard output: 12 45 | 46 | Sample input : 1000 47 | Standard output: 8 48 | 49 | Sample input : 100010 50 | Standard output: 34 51 | 52 | Time Complexity : O(n) where n is the size of string 53 | Space Complexity: O(n) 54 | */ 55 | -------------------------------------------------------------------------------- /Code/C++/fibonacci_dp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | In Fibonacci series, the current number is the sum of previous two numbers. 3 | One approach is bottom-up: these methods start with lower values of input and keep building the solutions for higher values. 4 | The other approach is top-down. In this method, we preserve the recursive calls and use the 5 | values if they are already computed. 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | 12 | int top_down(int n, int dp[]){ 13 | // save 14 | if(n==0 || n==1){ 15 | dp[n] = n; 16 | return dp[n]; 17 | } 18 | 19 | // check 20 | if(dp[n]!=-1){ 21 | return dp[n]; 22 | } 23 | int ans = top_down(n-1, dp)+top_down(n-2,dp); 24 | dp[n] = ans; 25 | 26 | return dp[n]; 27 | 28 | } 29 | 30 | int bottom_up(int n){ 31 | int dp[100]; 32 | 33 | // initialization with base case 34 | dp[0] = 0; 35 | dp[1] = 1; 36 | 37 | for(int i=2;i<=n;i++){ 38 | // recursive relation 39 | dp[i] = dp[i-1] + dp[i-2]; 40 | } 41 | 42 | return dp[n]; 43 | } 44 | int main() { 45 | 46 | int n; 47 | int dp[100]; 48 | 49 | cin >> n; 50 | 51 | //initilize with -1 52 | for(int i=0;i<100;i++){ 53 | dp[i] = -1; 54 | } 55 | 56 | cout<<"Top down - "< 14 | using namespace std; 15 | int main() 16 | { 17 | int n,c; 18 | cout<<"Enter the Number\n"; 19 | cin>>n; 20 | 21 | //c is assigned as the cube of the given number 22 | c=n*n*n; 23 | 24 | /* The last digit of a number is the remainder left behind when the 25 | number is divided by 10 and % operation is used to find the remainder 26 | obtained when one number is divided by the other.*/ 27 | //This if condition checks if both n and c have same last digits 28 | if((n%10)==(c%10)) 29 | cout<<"The given number is Trimorphic"; 30 | else 31 | cout<<"The given number is not Trimorphic"; 32 | return 0; 33 | } 34 | 35 | /* TEST CASES 36 | 37 | 1)Input: 38 | Enter the Number 39 | 20 40 | 2)Output: 41 | The given number is Trimorphic 42 | 43 | 1)Input: 44 | Enter the Number 45 | 2 46 | 2)Output: 47 | The given number is not Trimorphic 48 | 49 | Time Complexity:O(1) 50 | Space Complexity:O(1) 51 | 52 | */ 53 | -------------------------------------------------------------------------------- /Code/C++/sorted_zig_zag_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach : First sort the array then, swap pairs of elements 3 | except the first element. Example - keep a[0], swap a[1] with a[2], swap a[3] with a[4], and so on. 4 | So, we will take array and its size as parameters, run a loop from i to size of the array 5 | and swap every pair of element using swap function. At the end of loop, we will print the array. 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | //helper function that converts given array in zig-zag form 12 | void zigzag(int a[] , int n) 13 | { 14 | for(int i = 1 ; i < n ; i += 2) 15 | { 16 | if(i+1 < n) 17 | swap(a[i] , a[i+1]); 18 | } 19 | 20 | cout << "\nZig - Zag array : "; 21 | for(int i = 0 ; i < n ; i++) 22 | cout << a[i] << " "; 23 | } 24 | 25 | int main() 26 | { 27 | int a[] = {4,3,7,8,6,2,1}; 28 | int n = sizeof(a)/sizeof(a[0]); 29 | sort(a , a+n); 30 | 31 | cout << "Original array : "; 32 | for(int i=0 ; i 7 | using namespace std; 8 | int Knapsack(int w[], int val[], int n, int W) 9 | { 10 | //Initialization of the array 11 | int dp[n + 1][W + 1]; 12 | 13 | //Base conditions 14 | for (int i = 0; i < n + 1; i++) 15 | { 16 | for (int j = 0; j < W + 1; j++) 17 | { 18 | if (i == 0 || j == 0) 19 | dp[i][j] = 0; 20 | } 21 | } 22 | 23 | for (int i = 1; i < n + 1; i++) 24 | { 25 | for (int j = 1; j < W + 1; j++) 26 | { 27 | if (w[i - 1] <= j) 28 | dp[i][j] = max((val[i - 1] + dp[i][j - w[i - 1]]), dp[i - 1][j]); 29 | else 30 | dp[i][j] = dp[i - 1][j]; 31 | } 32 | } 33 | return dp[n][W]; 34 | } 35 | int main() 36 | { 37 | int n; 38 | cin >> n; 39 | int w[n], val[n]; 40 | for (int i = 0; i < n; i++) 41 | cin >> w[i] >> val[i]; 42 | int W; 43 | cin >> W; 44 | cout << Knapsack(w, val, n, W); 45 | } 46 | 47 | /* 48 | TEST CASE 1: 49 | 50 | INPUT: 51 | 5 52 | 10 200 53 | 5 60 54 | 3 90 55 | 2 10 56 | 1 6 57 | 20 58 | 59 | OUTPUT: 60 | 552 61 | 62 | TEST CASE 2: 63 | 64 | INPUT: 65 | 2 66 | 10 100 67 | 2 40 68 | 15 69 | 70 | OUTPUT: 71 | 280 72 | 73 | Time Complexity: O(N*W) 74 | Space Complexity: O(N*W) 75 | */ 76 | -------------------------------------------------------------------------------- /Code/C++/string_to_lowercase_and_uppercase.cpp: -------------------------------------------------------------------------------- 1 | /*program to convert string to lowercase and uppercase*/ 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | string lowercase(string s1){ 8 | for(int i=0;i=65 && s1[i]<=90) 11 | s1[i]=s1[i]+32;//conversion to lowercase 12 | } 13 | return s1; 14 | } 15 | 16 | 17 | string uppercase(string s1) 18 | { 19 | for(int i=0;i=97 && s1[i]<=122) 22 | { 23 | s1[i]=s1[i]-32;//convertion to uppercase case 24 | } 25 | } 26 | return s1; 27 | } 28 | 29 | int main() 30 | { 31 | string s1,lowercase_string,uppercase_string; 32 | getline(cin,s1); 33 | lowercase_string=lowercase(s1);//lowercase_string will contain the string with lowercase letter 34 | uppercase_string=uppercase(s1);//uppercase_string will contain the string with uppercase letter 35 | cout<<"Lowercase ->"<"<eloquent 46 | Uppercase ->ELOQUENT 47 | 48 | 49 | Test Case 2: 50 | 51 | input - DiVeRtIcuLaR 52 | output - Lowercase ->diverticular 53 | Uppercase ->DIVERTICULAR 54 | 55 | 56 | Time complexity: O(n) 57 | Space Complexity: O(n) 58 | 59 | 60 | */ 61 | -------------------------------------------------------------------------------- /Code/Java/dublicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Dublicate in the array. 3 | Here we will transverse all element of array in first start upto end. 4 | For every element,take its absolute value and if the abs(array[i])‘th element 5 | is positive, the element has not encountered before, else if negative the 6 | element has been encountered before print the absolute value of the 7 | current element. 8 | */ 9 | package array_dublicate; 10 | import java.util.Scanner; 11 | 12 | public class Dublicate_array { 13 | public static void main(String[] args){ 14 | Scanner scan = new Scanner(System.in); 15 | System.out.println("Enter Length of Array"); 16 | int n = scan.nextInt(); 17 | int[] arr = new int[n]; 18 | for (int i = 0 ; i < n ; i++){ 19 | arr[i] = scan.nextInt(); 20 | } 21 | System.out.println("The Dublicate Elemnts are :"); 22 | dublicate(arr); 23 | } 24 | public static void dublicate(int[] arr){ 25 | int len = arr.length; 26 | for (int i = 0; i < len; i++) { 27 | int j = Math.abs(arr[i]); 28 | if (arr[j] >= 0) { 29 | arr[j] = -arr[j]; 30 | }else { 31 | System.out.print(j + " "); 32 | } 33 | } 34 | } 35 | } 36 | /* 37 | Test Cases : 38 | Input: 5 39 | 1 2 2 3 1 40 | Output:2 1 41 | 42 | Input: 6 43 | 2 2 1 4 4 6 44 | Output:4 2 45 | 46 | Time Complexity: O(n) where n is the size of Array 47 | Space Complexity: O(1) 48 | */ -------------------------------------------------------------------------------- /Code/C++/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Insertion sort is a simple and efficient comparison sort. In this algorithm, each iteration removes 3 | an element from the input data and inserts it into the correct position in the list being sorted. The 4 | choice of the element being removed from the input is random and this process is repeated until 5 | all input elements have gone through. 6 | 7 | * Algorithm : 8 | Every repetition of insertion sort removes an element from the input data, and inserts it into the 9 | correct position in the already-sorted list until no input elements remain. Sorting is typically done 10 | in-place. The resulting array after k iterations has the property where the first k + 1 entries are 11 | sorted.Each element greater than x is copied to the right as it is compared against x. 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | int n; 20 | cin >> n; 21 | int a[n]; 22 | for(int i=0;i> a[i]; 24 | } 25 | 26 | for(int i = 1;i0 ; j-- ){ 28 | if(a[j] 9 | using namespace std; 10 | 11 | //helper function that converts given array in zig-zag form 12 | void zigzag(int a[], int n) 13 | { 14 | for(int i = 1 ; i < n ; i += 2) 15 | { 16 | if(i < n-1) 17 | swap(a[i], a[i+1]); 18 | } 19 | 20 | cout << "\nZig - Zag array : "; 21 | for(int i=0 ; i < n ; i++) 22 | cout << a[i] << " "; 23 | } 24 | 25 | int main() 26 | { 27 | int a[] = {4,3,7,8,6,2,1}; 28 | int n = sizeof(a)/sizeof(a[0]); 29 | 30 | cout << "Original array : "; 31 | for(int i = 0 ; i < n ; i++) 32 | cout << a[i] << " "; 33 | 34 | zigzag(a, n); 35 | 36 | return 0; 37 | } 38 | 39 | /* 40 | Test Case - 41 | 42 | Sample Input/Output (1): 43 | Original array : 4 3 7 8 6 2 1 44 | Zig - Zag array : 4 7 3 6 8 1 2 45 | 46 | Sample Input/Output (2): 47 | Original array : 14 13 17 18 16 12 11 48 | Zig - Zag array : 14 17 13 16 18 11 12 49 | 50 | Time Complexity : O(n) , where n is the number of elements. 51 | Space Complexity : O(1) 52 | 53 | If we want a sorted data we can first sort the array 54 | using sort() and then call the zigzag() function. 55 | */ 56 | -------------------------------------------------------------------------------- /Heap/readme.md: -------------------------------------------------------------------------------- 1 | # Heap 2 | 3 | A heap is a tree with some special properties. The basic requirement of a heap is that the value of 4 | a node must be ≥ (or ≤) than the values of its children. This is called **heap property**. A heap also 5 | has the additional property that all leaves should be at h or h – 1 levels (where h is the height of 6 | the tree) for some h > 0 (complete binary trees). That means heap should form a **complete binary tree**. 7 | 8 | ## Types of Heaps? 9 | 10 | Based on the property of a heap we can classify heaps into two types: 11 | 12 | * **Min heap:** The value of a node must be less than or equal to the values of its children 13 | * **Max heap:** The value of a node must be greater than or equal to the values of its children 14 | 15 | ## Heapifying an Element 16 | 17 | After inserting an element into heap, it may not satisfy the heap property. In that case we need to 18 | adjust the locations of the heap to make it heap again. This process is called **heapifying**. In max- 19 | heap, to heapify an element, we have to find the maximum of its children and swap it with the 20 | current element and continue this process until the heap property is satisfied at every node. 21 | 22 | ## Questions : 23 | 24 | * Heap Class ----> [C++](/Code/C++/heap_class.cpp) | [Java]() | [Python]() 25 | * Heap Sort ----> [C++](/Code/C++/heap_sort.cpp) 26 | * Merge K Sorted Arrays ----> [C++](/Code/C++/Merge_k_sorted_arrays.cpp) 27 | * Sliding Window Problem ----> [C++] (/Code/C++/Sliding_window_Maximum.cpp) 28 | * Top K Frequent Elements ----> [C++](/Code/C++/top_k_frequent_elements.cpp) 29 | * K-ary Heap ----> [C++](/Code/C++/k_ary_heap.cpp) -------------------------------------------------------------------------------- /Code/Java/check_prime.java: -------------------------------------------------------------------------------- 1 | /* 2 | Prime Numbers are those who dont's have any divisors other than 1 and itself, 3 | so, the number (n) which has any divisors in between 2 and (n-1) is not Prime Number 4 | so, firstly consider special case of 2 (2 is the only even prime) 5 | then, all other even No. except 2 as Not Prime 6 | Thus, we will check from 3 to (n-1) (all odd No. )for reminder to be 0, if reminder comes 0 at any one position 7 | so that will not be prime No. if not at any single position then it will reach upto end of isPrime Method & will be prime. 8 | */ 9 | package primeno; 10 | import java.util.Scanner; 11 | 12 | public class CheckPrime { 13 | public static void main(String[] args){ 14 | Scanner scan = new Scanner(System.in); 15 | System.out.println("Enter No : "); 16 | int n = scan.nextInt(); 17 | System.out.println(isPrime(n)); 18 | } 19 | public static boolean isPrime(int n) { 20 | if (n == 2){ 21 | return true; 22 | } else if (n%2==0){ 23 | return false; 24 | }else if (n<=1){ 25 | return false; 26 | } 27 | for (int i =3 ;i 11 | #include 12 | using namespace std; 13 | 14 | int main() { 15 | int size = 200, index = 0; 16 | char sentence[size], letter; 17 | stack s; 18 | // stack to store characters of the string 19 | 20 | cout << "Enter the sentence:" << endl; 21 | cin.getline(sentence, size); 22 | 23 | do { 24 | letter = sentence[index ++]; 25 | if (!isspace(letter) && (letter != '\n') && (letter != '\0')) { 26 | s.push(letter); 27 | // pushing into the stack if the character is not a space or newline 28 | } 29 | else { 30 | while (!s.empty()) { 31 | cout << s.top(); 32 | s.pop(); 33 | } 34 | // emptying the stack 35 | cout << letter; 36 | } 37 | 38 | } while (letter != '\0'); 39 | cout << endl; 40 | return 0; 41 | } 42 | 43 | /* 44 | Sample Input1: Get me food 45 | Sample Output1: teG em doof 46 | 47 | Sample Input2: happy birthday 48 | Sample Output2: yppah yadhtrib 49 | */ 50 | 51 | /* 52 | Time complexity = O(n) [since each pop or push takes O(1) times] 53 | Space Complexity = O(n) 54 | */ -------------------------------------------------------------------------------- /maximumSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement- 3 | We need to find maximum sum path from any node to any node in a binary tree. 4 | 5 | Algorithm- 6 | In order to check this we need to traverse through all the possible paths. 7 | We start traversing from the one node and we keep on storing the max result in a variable. 8 | 9 | */ 10 | 11 | import java.io.*; 12 | import java.util.*; 13 | 14 | //Creating basic tree data structure 15 | class Node { 16 | int val; 17 | Node left,right; 18 | // constructor 19 | 20 | Node(int data){ 21 | val=data; 22 | left=null; 23 | right=null; 24 | } 25 | } 26 | 27 | public class maximumSum { 28 | static int ans; 29 | public static void main(String[] args) throws IOException { 30 | Scanner sc=new Scanner(System.in); 31 | Node root=new Node(-10); 32 | root.left=new Node(9); 33 | root.right=new Node(20); 34 | root.right.left=new Node(15); 35 | root.right.right=new Node(7); 36 | 37 | ans=Integer.MIN_VALUE; 38 | maxSum(root); 39 | System.out.println(ans); 40 | 41 | sc.close(); 42 | return; 43 | } 44 | 45 | // An recursive function to find the maximum sum along any path. 46 | // Stores the result in a variable named as answer. 47 | public static int maxSum(Node root){ 48 | if (root == null) return 0; 49 | int left = Math.max(0, maxSum(root.left)); 50 | int right = Math.max(0, maxSum(root.right)); 51 | ans = Math.max(ans, left + right +root.val); 52 | return Math.max(left, right) +root.val; 53 | } 54 | } 55 | /* 56 | Time Complexity-O(n); 57 | Space Complexity-O(n); 58 | 59 | */ 60 | -------------------------------------------------------------------------------- /Code/C++/Linear_search.cpp: -------------------------------------------------------------------------------- 1 | // Linear Search in C++ 2 | // It is the simplest search algorithm 3 | // Algorithm:- 4 | 5 | // 1. looping through the array from left to right / 0 to n-1 6 | // 2. if element_want_to_search is equal to element_at_index i, we will return index and element_want_to_search is present in given array. 7 | // 3. if loop terminate it means element is not present. 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | int linear_search(int arr[],int n,int element) 15 | { 16 | int i; 17 | for(i=0;i>n; // Taking input of number of element in array 30 | int arr[n]; 31 | for(int i=0;i>arr[i]; // taking input of elements in array 34 | } 35 | int element; 36 | cin>>element; // taking input of element want to search 37 | if(linear_search(arr,n,element)==-1) 38 | { 39 | cout<<"\n"< 15 | using namespace std; 16 | 17 | //A function to reverse a string and print it 18 | void revstr(string str){ 19 | //size() is used to find the length of the string 20 | int len = str.size(); 21 | //Traversing half of the string 22 | for(int i = 0; i < len/2; i++){ 23 | //swapping 24 | swap(str[i], str[len - 1 - i]); 25 | } 26 | //Printing reversed string 27 | cout< 0){ 29 | int lastdigit = dummy % 10; 30 | dummy /= 10; 31 | dec += (lastdigit * Math.pow(2,count)); 32 | count++; 33 | } 34 | System.out.println(dec); 35 | } 36 | } 37 | /* 38 | Test Cases: 39 | Input: 10110 40 | Output: 22 41 | 42 | Input: 1110010 43 | Output: 114 44 | 45 | Time Complexity: O(n) where n is the Number of Digits in Decimal Number 46 | Space Complexity: O(1) 47 | */ 48 | -------------------------------------------------------------------------------- /Code/C++/modular_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Normal power algorithm would take O(power) time to calculate the answer. 3 | But here we use the fact that every number can be represented in power of 2! 4 | Consider 4^7 5 | 6 | Normal calculation = (4*4*... 7 Times) 7 | Modular exponentiation = (4^4)*(4^2)*(4^1) 8 | 9 | We use this power of 2s to our advantage. 10 | (4^2)=(4^1)^2 11 | (4^4)=(4^2)^2 12 | So, this reduces the number of multiplication, as we only need to sqaure the number (squaring is just single multiplication operation). 13 | */ 14 | 15 | #include 16 | using namespace std; 17 | 18 | long long modular_exponentiation(long long base,long long power,long long mod) 19 | { 20 | base=base%mod; 21 | long long answer=1; 22 | while(power>0) 23 | { 24 | if(power%2==1) 25 | { 26 | answer=(answer*base)%mod; 27 | } 28 | base=(base*base)%mod; 29 | power=power/2; 30 | } 31 | return answer; 32 | } 33 | 34 | int main() 35 | { 36 | long long base,power,mod; 37 | cout<<"Enter base: "; 38 | cin>>base; 39 | cout<<"Enter power: "; 40 | cin>>power; 41 | cout<<"Enter mod: "; 42 | cin>>mod; 43 | cout<<"("< 14 | using namespace std; 15 | 16 | int main() 17 | { 18 | 19 | 20 | int n,i,j,k; 21 | cin>>n; 22 | int a[n]; 23 | 24 | 25 | for(i=0;i>a[i]; 27 | } 28 | 29 | 30 | // move boundary of unsorted subarray one by one 31 | 32 | for(i=0;i= 0: 38 | res = min(res, dp[i][j]) 39 | if i < n: 40 | res = min(res, dp[i + 1][j]) 41 | if i > 0: 42 | res = min(res, dp[i - 1][j]) 43 | i -= 1 44 | j += 1 45 | return res 46 | 47 | # Driver Code 48 | if __name__ == "__main__": 49 | string = input('Enter string: ') 50 | print(noofDeletions(string)) 51 | 52 | # Time Complexity: O(n*n) 53 | # Space complexity: O(n*n) 54 | 55 | # Example 1: 56 | # input : malasiyala 57 | # output: 3 58 | 59 | # Example 2: 60 | # input : acdbdba 61 | # output: 1 62 | 63 | -------------------------------------------------------------------------------- /Code/C++/Duplicate_in_array.cpp: -------------------------------------------------------------------------------- 1 | /*Find Duplicate in array 2 | Problem Statement: Given an array with size "size", the elements inside the array can be present any number of times. 3 | Print all the elements whose frequency is greater than 1. 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | void print_repeat_numbers() 10 | { 11 | int size; 12 | //taking the size as input from user 13 | cin >> size; 14 | int input[size]; 15 | // taking input the elements of array 16 | for (int i = 0; i < size; i++) 17 | { 18 | cin >> input[i]; 19 | } 20 | 21 | //defining an onordered map for storing the frequencies 22 | unordered_map frequency; 23 | //incrementing the frequency for every repeated element 24 | for (int j = 0; j < size; j++) 25 | { 26 | frequency[input[j]]++; 27 | } 28 | 29 | cout << "Repeated elements are: "; 30 | 31 | //printing the numbers whose frequency is more than 1 i.e which is repeated 32 | for (auto x : frequency) 33 | { 34 | if (x.second > 1){ 35 | cout << x.first << " "; 36 | } 37 | } 38 | } 39 | 40 | int main() 41 | { 42 | print_repeat_numbers(); 43 | return 0; 44 | } 45 | 46 | /* 47 | Test Cases 48 | 1. 49 | Input : 50 | 5 51 | 1 2 3 2 3 52 | Output : 53 | Repeated elements are: 3 2 54 | 55 | 2. 56 | Input : 57 | 10 58 | 1 1 1 2 2 2 3 4 4 5 59 | Output : 60 | Repeated elements are: 1 2 4 61 | 62 | Time Complexity: O(size), for traversing the elements where size is the length of array 63 | Space Complexity: O(size), space is used for hashmap where size is the length of array 64 | */ 65 | -------------------------------------------------------------------------------- /Code/Python/RotationCount.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Descrption -> 3 | Given an array of distinct number enteries which are arranged in ascending order. 4 | If the array is rotated clockwise number of times. Then, calculate the total 5 | number of rotations in the respective array. 6 | ''' 7 | 8 | # program to find number of rotations in a sorted rotated array. 9 | 10 | # PYTHON CODE: 11 | 12 | def Total(lst,low, high): 13 | 14 | # When array in not rotated at all 15 | if (high < low): 16 | return 0 17 | 18 | # When array has single element left 19 | if (high == low): 20 | return low 21 | 22 | # calculating middle value 23 | mid = low + (high - low)/2; 24 | mid = int(mid) 25 | 26 | # checking minimum element 27 | if (mid < high and lst[mid+1] < lst[mid]): 28 | return (mid+1) 29 | 30 | #check if mid is middle element 31 | if (mid > low and lst[mid] < lst[mid - 1]): 32 | return mid 33 | 34 | #Move either left or right 35 | if (lst[high] > lst[mid]): 36 | return Total(lst, low, mid-1); 37 | 38 | return Total(lst, mid+1, high) 39 | 40 | # main code 41 | 42 | lst = list(map(int,input().strip().split())) 43 | n = len(lst) 44 | 45 | print(Total(lst, 0, n-1)) 46 | 47 | 48 | ''' 49 | Test Case 1: 50 | Input : lst = [4, 9, 11, 12, 5] 51 | Output : 4 52 | 53 | Test Case 2: 54 | Input : lst = [7, 9, 11, 12, 15] 55 | Output : 0 56 | 57 | Test Case 3: 58 | Input : lst = [15, 18, 2, 3, 6, 12] 59 | Output : 2 60 | 61 | Time Complexity: O(log n) # n = total number of elements in the array 62 | Space Complexity: O(1) 63 | ''' 64 | -------------------------------------------------------------------------------- /Code/Python/merge_to_palindrome.py: -------------------------------------------------------------------------------- 1 | #Ques: Find minimum number of merge operations required to make array palindrome 2 | #Language: Python 3 3 | 4 | #Basically, we are comparing array elements from both ends if they are equal then decrementing and incrementing both indexs otherwise we will merge elements of array which is minimum 5 | #input: ----->(n) size of array 6 | # ---->in next input line user have to provide space seperated integers 7 | 8 | #ouput: ---> will provide minimum numbers of merge operations to make array palindrome 9 | 10 | def isPalindrom(arr,n): 11 | i=0 12 | j=n-1 13 | while i [Java](/Code/Java/matrixop_add.java) 13 | * Checking Teoplitz Matrix Algorithm ----> [Java](/Code/Java/Toeplitz.java) 14 | * Clockwise Rotation ----> [C++](/Code/C++/2d_matrix_rotation_90degree_clockwise.cpp) 15 | * Inverse of a Matrix ----> [Java](/Code/Java/matrixop_inverse.java) 16 | * Matrix Operations ----> [C++](/Code/C++/matrix_operations.cpp) 17 | * Multiplication of two Matrices ----> [Java](/Code/Java/matrixop_mul.java) 18 | * Overall Median of Matrix ---> [Java](/Code/Java/overall_median_matrix.java) 19 | * Row-wise sum ----> [C++](/Code/C++/row_wise_sum.cpp) | [java](/Code/java/RowWise_Sum.java) 20 | * Spiral Print ----> [C++](/Code/C++/spiral_print.cpp) 21 | * Staircase Search ----> [C++](/Code/C++/staircase_search.cpp) 22 | * Substraction of two Matrices ----> [Java](/Code/Java/matrixop_sub.java) 23 | * Transpose of a Matrix --->[Java](/Code/Java/transpose.java) | [Python](/Code/Python/Transpose_of_matrix.py) 24 | * Wave Print ----> [C++](/Code/C++/wave_print.cpp) 25 | -------------------------------------------------------------------------------- /Algorithm/Hashing/readme.md: -------------------------------------------------------------------------------- 1 | # Hashing 2 | Hashing is a technique used for storing and retrieving information as quickly as possible. It is 3 | used to perform optimal searches and is useful in implementing symbol tables. 4 | 5 | ## Why Hashing? 6 | In the Trees chapter we saw that balanced binary search trees support operations such as insert, 7 | delete and search in O(logn) time. In applications, if we need these operations in O(1), then 8 | hashing provides a way. Remember that worst case complexity of hashing is still O(n), but it 9 | gives O(1) on the average. 10 | 11 | ## HashTable ADT 12 | The common operations for hash table are: 13 | 14 | * **CreatHashTable:** Creates a new hash table. 15 | * **HashSearch:** Searches the key in hash table. 16 | * **Hashlnsert:** Inserts a new key into hash table. 17 | * **HashDelete:** Deletes a key from hash table. 18 | * **DeleteHashTable:** Deletes the hash table. 19 | 20 | ## Components of Hashing 21 | Hashing has four key components: 22 | 23 | * Hash Table 24 | * Hash Functions 25 | * Collisions 26 | * Collision Resolution Techniques 27 | 28 | ## Hashing Techniques 29 | There are two types of hashing techniques: static hashing and dynamic hashing 30 | 31 | ### Static Hashing 32 | If the data is fixed then static hashing is useful. In static hashing, the set of keys is kept fixed and 33 | given in advance, and the number of primary pages in the directory are kept fixed. 34 | 35 | ### Dynamic Hashing 36 | If the data is not fixed, static hashing can give bad performance, in which case dynamic hashing is 37 | the alternative, in which case the set of keys can change dynamically. 38 | 39 | ## Questions : 40 | 41 | * Longest Subarray with sum k ----> [C++](/Code/C++/longest_subarray_with_sum_k.cpp) 42 | * Rabin Karp Algorithm ----> [C++](/Code/C++/rabin_karp.cpp) 43 | -------------------------------------------------------------------------------- /Stack/readme.md: -------------------------------------------------------------------------------- 1 | # Stack 2 | 3 | A stack is an ordered list in which insertion and deletion are done at one end, called 4 | top. The last element inserted is the first one to be deleted. Hence, it is called the Last in **First out 5 | (LIFO) or First in Last out (FILO) list**. 6 | 7 | When an element is 8 | inserted in a stack, the concept is called **push**, and when an element is removed from the stack, the 9 | concept is called **pop**. Trying to pop out an empty stack is called **underflow** and trying to push an 10 | element in a full stack is called **overflow**. 11 | 12 | ## Main stack operations 13 | 14 | - **Push (data):** Inserts data onto stack. 15 | - **Pop():** Removes and returns the last inserted element from the stack. 16 | 17 | ## Auxiliary stack operations 18 | 19 | - **Top():** Returns the last inserted element without removing it. 20 | - **Size():** Returns the number of elements stored in the stack. 21 | - **IsEmptyStack():** Indicates whether any elements are stored in the stack or not. 22 | - **IsFullStack():** Indicates whether the stack is full or not. 23 | 24 | ## Questions : 25 | 26 | - Balanced Bracket Problem ----> [C++](/Code/C++/balanced_bracket.cpp) | [Java](/Code/Java/Balanced_Bracket_Problem.java) | [Python](/Code/Python/Balanced_brackets.py) 27 | - Evaluation of postfix expression ----> [C++](/Code/C++/Postfixexpression.cpp) 28 | - Largest Rectangle ----> [C++](/Code/C++/Largest_Rectangle.cpp) 29 | - Reverse individual words of a string ----> [C++](/Code/C++/reverse_words_of_string.cpp) 30 | - Stack Class ----> [C++](/Code/C++/stack_class.cpp) 31 | - Stack using Linked List ----> [Python](/Code/Python/stack_using_linked_list.py) 32 | - Stock Span Problem ----> [C++](/Code/C++/Stock_Span_Problem.cpp) | [Java](/Code/Java/Stock_Span_Problem.Java) | [Python](/Code/Python/StockSpan.py) 33 | -------------------------------------------------------------------------------- /Code/Java/Kamenetsky_Formula.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * The Kamenetsky Formula is used to calculate the number of digits in the factorial of a number. 4 | * Formula: 5 | * number of digits in factorial = log10( ((n/e)^n) * sqrt(2*pi*n)) 6 | * which can be simplified to: 7 | * number of digits in factorial = n* log10(( n/ e)) + log10(2*pi*n)/2 8 | * where n is the number. 9 | * Reference paper: https://oeis.org/A034886 10 | */ 11 | 12 | import java.util.*; 13 | public class Kamenetsky_Formula 14 | { 15 | void main() 16 | { 17 | Scanner scanner = new Scanner(System.in); 18 | 19 | System.out.println("Enter number: "); 20 | int number = scanner.nextInt(); 21 | scanner.nextLine(); 22 | 23 | long number_of_digits; 24 | 25 | if(number<0) 26 | { 27 | number_of_digits = -1; 28 | System.out.println("Factorial of negative number cannot be calucated!"); 29 | } 30 | else if(number<=1) 31 | { 32 | number_of_digits = 1; 33 | System.out.println("Number of digits in factorial: "+number_of_digits); 34 | } 35 | else 36 | { 37 | number_of_digits = (long)(Math.floor(number * Math.log10(number / 2.718) + Math.log10(2 * 3.142 * number) / 2.0)) + 1; 38 | System.out.println("Number of digits in factorial: "+number_of_digits); 39 | } 40 | } 41 | } 42 | 43 | /* 44 | Test Cases- 45 | 46 | 1. 47 | Enter number: 48 | 10 49 | Number of digits in factorial: 7 50 | 51 | 2. 52 | Enter number: 53 | 1 54 | Number of digits in factorial: 1 55 | 56 | 3. 57 | Enter number: 58 | -9 59 | Factorial of negative number cannot be calucated! 60 | 61 | Time Complexity: O(1) 62 | */ 63 | 64 | 65 | -------------------------------------------------------------------------------- /Algorithm/Searching_Sorting/Binary_search.java: -------------------------------------------------------------------------------- 1 | package Algorithm.Searching_Sorting; 2 | 3 | // Java program to find number of 4 | // rotations in a sorted and rotated array. 5 | import java.util.*; 6 | import java.lang.*; 7 | import java.io.*; 8 | 9 | class Binary_search 10 | { 11 | // Returns count of rotations for an array 12 | // which is first sorted then rotated 13 | static int countRotations(int arr[], int low, 14 | int high) 15 | { 16 | 17 | // This condition is needed to handle 18 | // the case when array is not rotated 19 | 20 | if (high < low) 21 | return 0; 22 | 23 | // If there is only one element left 24 | if (high == low) 25 | return low; 26 | 27 | // Find mid 28 | int mid = low + (high - low)/2; 29 | 30 | // Check if element (mid+1) is minimum element 31 | if (mid < high && arr[mid+1] < arr[mid]) 32 | return (mid + 1); 33 | 34 | // Check if mid itself is minimum element 35 | if (mid > low && arr[mid] < arr[mid - 1]) 36 | return mid; 37 | 38 | // Decide whether we need to go to left half or right half 39 | if (arr[high] > arr[mid]) 40 | return countRotations(arr, low, mid - 1); 41 | 42 | return countRotations(arr, mid + 1, high); 43 | } 44 | 45 | // Driver program to test above functions 46 | public static void main (String[] args) 47 | { 48 | Scanner sc = new Scanner(System.in); 49 | int n = sc.nextInt(); 50 | int arr[ ]= new int[n]; 51 | for(int i=0;i 10 | #include 11 | using namespace std; 12 | 13 | /* Function to check whether number is pronic or not 14 | A number is pronic if the root of equation i^2+i-num=0 is real and integer. 15 | So, the discriminant of equation should be positive, odd and perfect square for number to be pronic*/ 16 | bool is_pronic(int num) 17 | { 18 | int dis = 1 + 4 * num; 19 | //checking discriminant is positive,odd and perfect square 20 | if (dis >= 0 && floor(sqrt(dis)) == sqrt(dis)) 21 | return true; 22 | else 23 | return false; 24 | } 25 | 26 | int main() 27 | { 28 | int ll, hl; 29 | cout << "Enter the range for which you want to print PRONIC NUMBERS:\n"; 30 | cout << "Enter lower limit:"; 31 | cin >> ll; 32 | cout << "Enter higher limit:"; 33 | cin >> hl; 34 | 35 | //Printing pronic numbers in given range 36 | cout << "Pronic numbers from " << ll << " to " << hl << " are:\n"; 37 | for (int i = ll; i <= hl; i++) 38 | { 39 | if (is_pronic(i)) 40 | cout << i << " "; 41 | } 42 | } 43 | 44 | /* 45 | 46 | Sample Input/Output: 47 | 48 | Input: 49 | Enter the range for which you want to print PRONIC NUMBERS: 50 | Enter lower limit:1 51 | Enter higher limit:1000 52 | 53 | Output: 54 | Pronic numbers from 1 to 1000 are: 55 | 2 6 12 20 30 42 56 72 90 110 132 156 182 210 240 272 306 342 380 420 462 506 552 600 650 702 756 812 870 930 992 56 | 57 | Time Complexity:O(n) where n is total numbers in range 58 | Time Complexity of is_pronic()=O(1) 59 | Space Complexity:O(1) 60 | 61 | */ 62 | -------------------------------------------------------------------------------- /Code/C++/longest_prefix_suffix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | -LONGEST PREFIX SUFFIX 3 | -Given a string, find the length of longest substring that is both prefix and suffix 4 | -overlapping of prefix and suffix not allowed 5 | 6 | -idea is to divide the given string from between and check if both string are equal 7 | -if so return the length of that substring 8 | -otherwise check for the shorter length 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | int main() 15 | { 16 | 17 | string s; 18 | // input from the user 19 | cin>>s; 20 | /*if length of given string is less 21 | than two, no such substring exist 22 | hence prints 0*/ 23 | if (s.length()<2) 24 | cout<<0; 25 | else 26 | { 27 | /*divide string into two equal parts 28 | and store starting indices of both*/ 29 | int l=0, i=s.length()/2; 30 | /*loop calculating the length of 31 | such substring*/ 32 | while (is.length()/2) 51 | cout< 14 | // create two arrays, ori and inv. 15 | // give input for ori array. 16 | // create a temporary variable then, and store the element from the original array. 17 | // In inv array for each value of temp, store the index of ori array. 18 | // Display the inverse array. 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | 24 | //This function returns inverse of the given array 25 | void inverse(int a[], int n, int b[]) 26 | { 27 | for (int i = 0; i < n; i++) 28 | { 29 | int temp = a[i]; 30 | b[temp] = i; 31 | } 32 | for (int i = 0; i < n; i++) 33 | cout << b[i] << " "; 34 | } 35 | 36 | int main() 37 | { 38 | // n is size of the array. 39 | int n; 40 | cin >> n; 41 | int ori[n]; 42 | // inverse array should be of same size as of the given array. 43 | int inv[n]; 44 | for (int i = 0; i < n; i++) 45 | { 46 | cin >> ori[i]; 47 | } 48 | //calling inverse function 49 | inverse(ori, n, inv); 50 | return 0; 51 | } 52 | 53 | /* 54 | Time complexity - O(n) 55 | 56 | 57 | Test cases :- 58 | 59 | Sample Input-1: 60 | 5 61 | 4 0 2 3 1 62 | Sample Output-1: 63 | 1 4 2 3 0 64 | 65 | Sample Input-2: 66 | 3 67 | 0 1 2 68 | Sample Output-2: 69 | 0 1 2 70 | */ 71 | 72 | -------------------------------------------------------------------------------- /Algorithm/Recursion/readme.md: -------------------------------------------------------------------------------- 1 | # Recursion 2 | Any function which calls itself is called recursive. A recursive method solves a problem by 3 | calling a copy of itself to work on a smaller problem. This is called the recursion step. The 4 | recursion step can result in many more such recursive calls. 5 | It is important to ensure that the recursion terminates. Each time the function calls itself with a 6 | slightly simpler version of the original problem. The sequence of smaller problems must 7 | eventually converge on the base case. 8 | 9 | * Recursive algorithms have two types of cases, **recursive cases** and **base cases**. 10 | * Every recursive function case must terminate at a base case. 11 | * Generally, iterative solutions are more efficient than recursive solutions [due to the overhead of function calls]. 12 | * A recursive algorithm can be implemented without recursive function calls using a stack, but it’s usually more trouble than its worth. That means any problem that can be solved recursively can also be solved iteratively. 13 | * For some problems, there are no obvious iterative algorithms. 14 | * Some problems are best suited for recursive solutions while others are not. 15 | 16 | ## Questions : 17 | 18 | * Factorial ----> [C++](https://github.com/Algo-Phantoms/Algo-Tree/blob/main/Code/C%2B%2B/factorial.cpp) | [Java](/Code/Java/factorial.java) 19 | * Fibonocci ----> [C++](https://github.com/Algo-Phantoms/Algo-Tree/blob/main/Code/C%2B%2B/fibonacci.cpp) 20 | * Josephus Problem ----> [C++](/Code/C++/josephus_problem.cpp) 21 | * Kth_Symbol_Grammar ----> [C++](https://github.com/Ayush12062000/Algo-Tree/blob/issue-645/Code/C%2B%2B/Kth_Symbol_Grammar.cpp) 22 | * Phone Keypad ----> [C++](/Code/C++/phone_keypad.cpp) 23 | * Tower of Hanoi ----> [C++](/Code/C++/tower_of_hanoi.cpp) | [Java] (/Code/Java/Tower_of_Hanoi.java) 24 | * Generate all valid parantheses ----> [Java](/Code/Java/valid_parantheses.java) 25 | 26 | -------------------------------------------------------------------------------- /Code/C++/palindrome_number.cpp: -------------------------------------------------------------------------------- 1 | /* Palindrome Number : 2 | Given an integer x, return true if x is palindrome integer. 3 | An integer is a palindrome when it reads the same backward as forward. 4 | This code is implemented without using extra space. 5 | In this we will be taking two point , leading and trailing which will be pointing 6 | in start and end of the number and then we will be comparing start and end , if 7 | found equal then we will move the pointers and we will compare till every digit is 8 | checked . So if condition satisfied then we will return true else return false. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | bool checkPalindrome(int num) 15 | { 16 | // divi = divisor 17 | int divi = 1; 18 | 19 | //finding the apt. divisor for the number 20 | while (num / divi >= 10) 21 | { 22 | divi *= 10; 23 | } 24 | 25 | while (num != 0) 26 | { 27 | int leading = num / divi; 28 | int trailing = num % 10; 29 | if (leading != trailing) 30 | { 31 | return false; 32 | } 33 | //reducing number to compare 34 | num = (num % divi) / 10; 35 | divi = divi / 100; 36 | } 37 | return true; 38 | } 39 | int main() 40 | { 41 | int num; 42 | cout << "Enter the number to check : " << endl; 43 | cin >> num; 44 | checkPalindrome(n) ? cout << "True" : cout << "False"; 45 | return 0; 46 | } 47 | 48 | /* 49 | Time complexity : O(log n) 50 | (here n is number of elements in array) 51 | Space complexity : O(1) 52 | */ 53 | 54 | /* 55 | Test Cases : 56 | Test case 1 : 57 | Input : 1001 58 | Output : True 59 | Test case 2 : 60 | Input : 1234 61 | Output : False 62 | */ 63 | 64 | -------------------------------------------------------------------------------- /Code/Java/revindivstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | Here we will take input of String and then we will find index of space occured in 3 | String, then upto that index we will reverse word & will add in temp String using 4 | Concatenation & at last will reverse last word & hence will return the string temp 5 | */ 6 | 7 | package com; 8 | import java.util.Scanner; 9 | 10 | public class revindivstring { 11 | public static void main(String[] args){ 12 | Scanner scan = new Scanner(System.in); 13 | System.out.println("Enter Sentence : "); 14 | //Taking Input of String 15 | String txt = scan.nextLine(); 16 | //String with Reversed Words Result Output 17 | System.out.println(RevIndivString(txt)); 18 | } 19 | public static String RevIndivString(String txt){ 20 | //Creating an Empty String to which the Reversed Words will be Concatenated 21 | String temp = ""; 22 | int carry = 0; 23 | for (int i = 0;i=carry;j--){ 29 | temp += txt.charAt(j); 30 | } 31 | //Adding Space for Next Reversed Word 32 | temp += ' '; 33 | // Carrying Starting Index of Next Word 34 | carry = i+1; 35 | } 36 | 37 | } 38 | //Concatenation Last Word in Reversed Order to String temp 39 | for (int i = txt.length()-1;i>=carry;i--){ 40 | temp += txt.charAt(i); 41 | } 42 | return temp; 43 | } 44 | } 45 | /* 46 | Test Cases: 47 | Input: He is Good 48 | Output: eH si dooG 49 | 50 | Input: I am krishna-NIT 51 | Output: I ma TIN-anhsirk 52 | 53 | Time Complexity: O(n) 54 | Space Complexity: O(1) 55 | 56 | 57 | */ -------------------------------------------------------------------------------- /Code/Java/Anagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Two strings are said to be an Anagram if all the characters of a string are equal and have same frequency but arranged in different order. 3 | The simple logic to solve is taking the two strings into a character array and sort both the arrays and again store it to the same string variable, 4 | if both the strings are equal then one string is said to be anagram of another. 5 | */ 6 | package p1; 7 | 8 | import java.util.*; 9 | public class Anagram { 10 | 11 | public static void main(String[] args) { 12 | 13 | Scanner sc = new Scanner(System.in); 14 | 15 | System.out.println("Enter string 1: "); 16 | String s = sc.next(); 17 | System.out.println("Enter string 2: "); 18 | String s1 = sc.next(); 19 | // storing the length of both the strings 20 | int l1 = s.length(),l2 = s1.length(); 21 | 22 | if(l1!=l2) { 23 | //if both are of unequal length then its for sure that they are not an anagram 24 | System.out.println("Two strings are not Anagram"); 25 | } 26 | else { 27 | char c1[] = s.toCharArray(),c2[] = s1.toCharArray(); 28 | 29 | s = ""; s1 = ""; 30 | //sorting both the array. 31 | Arrays.sort(c1);Arrays.sort(c2); 32 | 33 | for(char ch:c1) { 34 | s = s + ch; 35 | } 36 | 37 | for(char ch:c2) { 38 | s1 = s1 + ch; 39 | } 40 | if(s.compareTo(s1)==0) { 41 | System.out.println("Two strings are Anagram"); 42 | }else 43 | System.out.println("Two strings are not Anagram"); 44 | 45 | } 46 | } 47 | } 48 | 49 | 50 | /* 51 | Test Cases 52 | 1. 53 | INPUT: 54 | Enter string 1: prateek 55 | Enter string 2: eektarp 56 | OUTPUT: 57 | Two strings are Anagram 58 | 59 | 2. 60 | INPUT: 61 | Enter string 1: abcde 62 | Enter string 2: cdba 63 | OUTPUT: 64 | Two strings are not Anagram 65 | 66 | 67 | Time Complexity-O(nlog n) 68 | Space Complexity-O(n) 69 | where n: number of characters in string 70 | 71 | */ 72 | -------------------------------------------------------------------------------- /Code/Java/trimorphic_number.java: -------------------------------------------------------------------------------- 1 | /* 2 | * A trimorphic number is whose cube ends with the number itself. 3 | * Example: 4 | * 49*49*49 = 117649 5 | * which ends with 49 6 | * This code checks whehter the input number is trimorphic or not. 7 | */ 8 | import java.util.*; 9 | class trimorphic_number 10 | { 11 | void main() 12 | { 13 | //driver function 14 | 15 | Scanner scanner = new Scanner(System.in); 16 | 17 | System.out.println("Enter number: "); 18 | int number = scanner.nextInt(); 19 | scanner.nextLine(); 20 | 21 | if(is_trimorphic(number) == true) 22 | { 23 | System.out.println(number+" is a Trimorphic number!"); 24 | } 25 | else 26 | { 27 | System.out.println(number+" is not a Trimorphic number!"); 28 | } 29 | } 30 | 31 | boolean is_trimorphic(int number) 32 | { 33 | //this function checks whether number is trimorphic or not 34 | 35 | int cube = number*number*number; 36 | 37 | if((cube % Math.pow(10,no_of_digits(number))) == number) 38 | { 39 | return true; 40 | } 41 | else 42 | { 43 | return false; 44 | } 45 | } 46 | 47 | int no_of_digits(int number) 48 | { 49 | //this function counts the number of digits 50 | 51 | int count = 0; 52 | 53 | while(number!=0) 54 | { 55 | count++; 56 | number/=10; 57 | } 58 | 59 | return count; 60 | } 61 | } 62 | 63 | /* 64 | * Test Cases- 65 | * 66 | * 1. 67 | * Enter number: 68 | * 24 69 | * 24 is a Trimorphic number! 70 | * 71 | * 2. 72 | * Enter number: 73 | * 21 74 | * 21 is not a Trimorphic number! 75 | * 76 | * Time Complexity: O(n) 77 | * where n is the number of digits in the number 78 | * Space Complexity: O(1) 79 | */ 80 | -------------------------------------------------------------------------------- /Code/C++/rabin_karp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define int long long int 4 | 5 | const int mod = 1e9+7; 6 | const int p = 31; 7 | 8 | // binary exponentiation(a^b %m) - o(log b) 9 | int powr(int a, int b){ 10 | int res = 1; 11 | while(b){ 12 | 13 | if(b & 1LL){ 14 | res *= a; 15 | res %= mod; 16 | } 17 | b /= 2; 18 | a *= a; 19 | a %= mod; 20 | } 21 | return res; 22 | } 23 | 24 | int inv(int a){ 25 | 26 | //a^-1 % m 27 | //fermats little theorem 28 | return powr(a, mod-2); 29 | } 30 | 31 | // hash function 32 | int poly_hash_string(string s){ 33 | 34 | int p_powr = 1; 35 | int hash = 0; 36 | 37 | for(int i=0;i 18 | using namespace std; 19 | 20 | int main() 21 | { 22 | // n is the size of array 23 | int n; 24 | cin >> n; 25 | 26 | // taking array as input 27 | int a[n]; 28 | for ( int i = 0 ; i < n ; i++ ) 29 | cin >> a[i]; 30 | 31 | int i = 0; 32 | while ( i < n ) 33 | { 34 | // if element is at its position 35 | if ( a[i] == i + 1 || a[i] == a[ a[i] - 1 ] ) 36 | i++ ; 37 | else 38 | // if not swap 39 | swap ( a[i], a[ a[i] - 1 ] ); 40 | } 41 | 42 | int r = 0, m = 0; 43 | for ( int i = 0 ; i < n ; i++ ) 44 | { 45 | // find the element which is not at its position 46 | if ( a[i] != i + 1 ) 47 | { 48 | r = a[i]; 49 | m = i + 1; 50 | break; 51 | } 52 | } 53 | 54 | cout << "Repeating number is " << r << endl; 55 | cout << "Missing number is " << m; 56 | } 57 | 58 | /* 59 | Testcases 60 | Input : 61 | 5 62 | 4 1 3 2 1 63 | Output : Repeating number is 1 64 | Missing number is 5 65 | 66 | Input : 67 | 6 68 | 1 4 5 2 3 4 69 | Output : Repeating number is 4 70 | Missing number is 6 71 | 72 | Time complexity : O(n) 73 | Space complexity : O(1) 74 | 75 | where n is the size of the array 76 | */ 77 | -------------------------------------------------------------------------------- /Code/C++/Middle_of_the_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We need to write a program to print the middle element in the linked list. 3 | If the number of elements are odd then print the middle element. 4 | If the number of elements are even then print the right part of the middle pair. 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | class node{ 11 | public: 12 | int data; 13 | node* next; 14 | 15 | //constructor 16 | node(int x){ 17 | data = x; 18 | next = nullptr; 19 | } 20 | 21 | }; 22 | 23 | class LinkedList{ 24 | public: 25 | node* head; 26 | node* tail; 27 | 28 | //constructor 29 | LinkedList(){ 30 | head = nullptr; 31 | tail = nullptr; 32 | } 33 | 34 | void insert(int x){ 35 | node* n = new node(x); 36 | 37 | //only one node 38 | if(head == nullptr){ 39 | head = n; 40 | tail = n; 41 | } 42 | else{ 43 | tail->next = n; 44 | tail = n; 45 | } 46 | } 47 | }; 48 | 49 | int main(){ 50 | 51 | LinkedList l; 52 | 53 | //size of linked list 54 | int n; 55 | cin>>n; 56 | 57 | //values inside linked list 58 | for(int i=0;i>temp; 61 | l.insert(temp); 62 | } 63 | 64 | //middle index 65 | int mid=n/2; 66 | 67 | node *curr=l.head; 68 | int j=0; 69 | 70 | //To point to the middle element 71 | while(j!=mid) 72 | { 73 | curr=curr->next; 74 | j++; 75 | } 76 | 77 | cout<data< 9 | using namespace std; 10 | 11 | vector> adjList; 12 | stack s; 13 | bool *visited; 14 | 15 | // Number of Test Cases (Vertices) 16 | int n; 17 | 18 | void createGraph() 19 | { 20 | int x, y; 21 | adjList.resize(n); 22 | 23 | for (int j = 0; j < n; j++) 24 | { 25 | cin >> x >> y; 26 | adjList[x].push_back(y); 27 | } 28 | } 29 | 30 | void topoSortFun(int i) 31 | { 32 | visited[i] = true; 33 | for (int j = 0; j < adjList[i].size(); j++) 34 | { 35 | int key = adjList[i][j]; 36 | if (!visited[key]) 37 | topoSortFun(key); 38 | } 39 | s.push(i); 40 | } 41 | 42 | void topoSort() 43 | { 44 | memset(visited, false, sizeof(visited)); 45 | 46 | for (int i = 0; i < n; i++) 47 | { 48 | if (!visited[i]) 49 | topoSortFun(i); 50 | } 51 | } 52 | void display() 53 | { 54 | for (int i = 0; i < n; i++) 55 | { 56 | cout << s.top() << " "; 57 | s.pop(); 58 | } 59 | } 60 | int main() 61 | { 62 | cin >> n; 63 | visited = new bool[n]; 64 | createGraph(); 65 | topoSort(); 66 | display(); 67 | } 68 | 69 | /* 70 | Test Case: 71 | 72 | Input 1 : 73 | 6 74 | 5 2 75 | 5 0 76 | 4 0 77 | 4 1 78 | 2 3 79 | 3 1 80 | 81 | Output 1 : 82 | 5 4 2 3 1 0 83 | 84 | Input 2 : 85 | 6 86 | 4 2 87 | 5 1 88 | 4 0 89 | 3 1 90 | 1 3 91 | 3 2 92 | 93 | Output 2 : 94 | 5 4 1 3 2 0 95 | 96 | Time Complexity: O(V + E) – where V is the number of vertices and E is the number of edges. 97 | 98 | Space Complexity: O(V) 99 | */ -------------------------------------------------------------------------------- /Code/Java/triautomorphic_number.java: -------------------------------------------------------------------------------- 1 | /* 2 | * A number n is called triautomorphic if 3n^2 ends in n. 3 | * Example: 4 | * n=667 5 | * 3n^2 = 1334667 6 | * which ends with 667 7 | * This code checks whehter the input number is triautomorphic or not. 8 | */ 9 | import java.util.*; 10 | public class triautomorphic_number 11 | { 12 | void main() 13 | { 14 | //driver function 15 | 16 | Scanner scanner = new Scanner(System.in); 17 | 18 | System.out.println("Enter number: "); 19 | int number = scanner.nextInt(); 20 | scanner.nextLine(); 21 | 22 | if(is_triautomorphic(number) == true) 23 | { 24 | System.out.println(number+" is a Triautomorphic number!"); 25 | } 26 | else 27 | { 28 | System.out.println(number+" is not a Triautomorphic number!"); 29 | } 30 | } 31 | 32 | boolean is_triautomorphic(int number) 33 | { 34 | //this function checks whether number is triautomorphic or not 35 | 36 | int triauto = 3*number*number; 37 | 38 | if((triauto % Math.pow(10,no_of_digits(number))) == number) 39 | { 40 | return true; 41 | } 42 | else 43 | { 44 | return false; 45 | } 46 | } 47 | 48 | int no_of_digits(int number) 49 | { 50 | //this function counts the number of digits 51 | 52 | int count = 0; 53 | 54 | while(number!=0) 55 | { 56 | count++; 57 | number/=10; 58 | } 59 | 60 | return count; 61 | } 62 | } 63 | 64 | /* 65 | * Test Cases- 66 | * 1. 67 | * Enter number: 68 | * 5 69 | * 5 is a Triautomorphic number! 70 | * 71 | * 2. 72 | * Enter number: 73 | * 8 74 | * 8 is not a Triautomorphic number! 75 | * 76 | * Time Complexity: O(n) 77 | * Space Complexity: O(n) 78 | * where n is the number of digits in the number 79 | */ -------------------------------------------------------------------------------- /Code/C++/unique_permutaions_of_string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A string is given we have to generate all its possible permutations. 3 | A permutation of the string is defined as a word that contains all the characters of the original string, 4 | but in any order. The output should contain only unique words in lexicographically sorted order. 5 | 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | //function to generate all premutations 14 | void permute(char *inp, int cur_Index, set &ans) { 15 | //base case (end of string i.e. all palces filled) 16 | if (inp[cur_Index] == '\0') { 17 | ans.insert(string(inp)); 18 | return; 19 | } 20 | 21 | //recursive case 22 | for (int j = cur_Index; inp[j] != '\0'; ++j) 23 | { 24 | //we will place every available charater at current_Index 25 | swap(inp[cur_Index], inp[j]); 26 | 27 | //solving sub problem 28 | permute(inp, cur_Index + 1, ans); 29 | 30 | //undo the changes made 31 | swap(inp[cur_Index], inp[j]); 32 | } 33 | } 34 | 35 | 36 | int main() 37 | { 38 | 39 | //all the words will be stored in set 40 | //because set keeps only unique elements and stores elements in sorted order 41 | //hence iterating on set will give all unique words in lexicographically sorted order 42 | set ans; 43 | 44 | //input the string 45 | cout << "Enter the String : "; 46 | char inp[10000]; 47 | cin >> inp; 48 | 49 | //function to generate all premutations 50 | permute(inp, 0, ans); 51 | 52 | //Iterating over set 53 | cout << "\nAll Unique permutations of given string are : \n"; 54 | for (auto cur : ans) { 55 | cout << cur << endl; 56 | } 57 | 58 | return 0; 59 | } 60 | 61 | /* 62 | Test Case : 63 | 1. 64 | Input : abc 65 | Output :abc 66 | acb 67 | bac 68 | bca 69 | cab 70 | cba 71 | 72 | 2. 73 | Input : aba 74 | Output :aab 75 | aba 76 | baa 77 | 78 | Time Complexity: O(n*n!) , where n is length of string 79 | Space Complexity: O(n*n!) , where n is length of string 80 | 81 | */ -------------------------------------------------------------------------------- /Code/C++/prime_number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A number is said to be a prime number if it has only two factors which are 1 and the number itself. 4 | For examle, 2 is a prime number as it has 2 factors which are 2 and 1. Similarly 3 is also a prime number as it has only two factors which are 3 and 1. 5 | 6 | The first number in the set of prime numbers is 2. 7 | 1 is not a prime number. 8 | 9 | The following program checks if a number is a prime number or not using Trial Division Algorithm. 10 | As per the algorithm a number is a prime number if there exists no factor of N between 2 and square root of N. 11 | 12 | */ 13 | 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | int main() 19 | { 20 | int N; 21 | cin>>N; // Taking input the number from the user 22 | 23 | if(N>=2 ) //Checking if the inputted no is greater than equal to 2 24 | { 25 | int factor=0; // Variable to store number of factors of the inputted number between 2 and square root of N 26 | 27 | int K=ceil(sqrt(N)); // Variable to store the ceil value of square root of N 28 | 29 | for(int i=K;i>=2;i--) 30 | { 31 | if(N%i==0) 32 | factor++ ; //Counting number of factors of the inputted number 33 | 34 | } 35 | 36 | if(factor==0) 37 | cout< 7 | #include 8 | using namespace std; 9 | 10 | 11 | class Queue{ 12 | 13 | public: 14 | 15 | //main data structure 16 | stack s1; 17 | //helper 18 | stack s2; 19 | 20 | void push(int x){ 21 | s1.push(x); 22 | } 23 | 24 | void pop(){ 25 | 26 | //copy s1 to s2 27 | 28 | while(!s1.empty()){ 29 | s2.push(s1.top()); 30 | s1.pop(); 31 | } 32 | 33 | s2.pop(); 34 | 35 | //copy s2 to s1 36 | 37 | while(!s2.empty()){ 38 | s1.push(s2.top()); 39 | s2.pop(); 40 | } 41 | 42 | } 43 | 44 | int front(){ 45 | //copy s1 to s2 46 | 47 | while(!s1.empty()){ 48 | s2.push(s1.top()); 49 | s1.pop(); 50 | } 51 | 52 | int x = s2.top(); 53 | 54 | //copy s2 to s1 55 | 56 | while(!s2.empty()){ 57 | s1.push(s2.top()); 58 | s2.pop(); 59 | } 60 | 61 | return x; 62 | 63 | } 64 | 65 | int size(){ 66 | return s1.size(); 67 | } 68 | 69 | bool empty(){ 70 | return s1.empty(); 71 | } 72 | 73 | 74 | }; 75 | 76 | 77 | 78 | 79 | int main() 80 | { 81 | Queue q; 82 | 83 | int n; 84 | cin >> n; 85 | 86 | for(int i=1;i<=n;i++){ 87 | q.push(i); 88 | } 89 | 90 | 91 | cout< 7 | using namespace std; 8 | int main(){ 9 | int N; 10 | cin>> N; 11 | int arr[N+1]; 12 | for(int i=1; i<= N;i++){ 13 | // initially assume all number are prime so make all index 1 14 | arr[i]=1; 15 | } 16 | 17 | for(int i= 2 ; i<=sqrt(N) ; i++){ 18 | if(arr[i]==0) continue; 19 | for(int j = i*i ; j <=N ;j=j+i){ 20 | // here we make 0 at all index which are not prime numbers 21 | arr[j]=0; 22 | } 23 | } 24 | // now we print all prime numbers 25 | for(int i= 2 ;i<= N ; i++){ 26 | if(arr[i]==1) cout< ans = new Vector<>(); 25 | int n = notes.length; 26 | // Traverse through all notesmination of Notes / Currency 27 | for (int i = n - 1; i >= 0; i--) 28 | { 29 | while (V >= notes[i]) 30 | { 31 | V -= notes[i]; 32 | ans.add(notes[i]); 33 | } 34 | } 35 | // Printing which Notes will make use of Minimum Coins / Notes 36 | for (int i = 0; i < ans.size(); i++) 37 | { 38 | System.out.print(ans.elementAt(i)+" "); 39 | } 40 | System.out.println(); 41 | System.out.println("Min No of Coins / Notes is "+ ans.size()); 42 | } 43 | } 44 | /* 45 | Test Cases: 46 | Input : 94 47 | Output: 50 20 20 2 2 48 | Min No of Coins / Notes is 5 49 | 50 | Input : 72 51 | Output: 50 20 2 52 | Min No of Coins / Notes is 3 53 | 54 | Time Complexity: O(n) where n is No. of Different Denomination of Notes Available 55 | Space Complexity: O(1) 56 | */ 57 | -------------------------------------------------------------------------------- /Code/Python/Anagram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: Python program to check given two strings are Anagram of each other or not . 3 | 4 | An anagram of a string is an another string that contains the same characters but the order of characters can be different. 5 | For example ,listen and silent are anagrams of each oter because all the characters in the string "listen" are present in string "silent". 6 | So, listen and silent are anagrams of each other. 7 | At First convert both strings to list of characters and sort them using sort() methid and check if both two list strings are equal print 8 | strings are anagrams of each other ,else print strings are not anagrams of eachother. 9 | """ 10 | def anagram(string1,string2): 11 | list_string1=list(string1) 12 | list_string1.sort() 13 | list_string2=list(string2) 14 | list_string2.sort() 15 | if(list_string1==list_string2): 16 | print("Given strings are anagrams of eachother") 17 | else: 18 | print("Given strings are not anagrams of eachother") 19 | string1=input("enter string1:") 20 | string2=input("enter string2:") 21 | anagram(string1,string2) 22 | 23 | """ 24 | Test cases: 25 | Input: 26 | Enter string1: silent 27 | Enter string2: listen 28 | Output: Given strings are anagrams of eachother 29 | Because here after sorting string1 and string2 ,list_string1=['e','i','l','n','s','t'] and list_string2=['e','i','l','n','s','t']. As list_string1 = list_string2 the given 30 | strings are anagrams of each other. 31 | 32 | Input: 33 | enter string1: hello 34 | enter string2: world 35 | Output: Given strings are not anagrams of eachother. 36 | Because here after sorting string1 and string2 ,list_string1=['e','h','l','l','o'] and list_string2=['d','l','o','r','w']. As list_string1 is not equal to list_string2 the given 37 | strings are not anagrams of each other. 38 | 39 | Time Complexity: O(nlogn) .Because time complexity for sort() function is O(nlogn) where n is the size of input that is the length of string. 40 | Space complexity: O(length(string1+string2)) 41 | 42 | """ 43 | -------------------------------------------------------------------------------- /Code/Python/StockSpan.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | Problem: User would be given with the prices of stock.User needs to output the span of each stock price for n day,where 4 | span refers to as maximum number of consecutive days for which the price of the stock on the current day is less than or equal to the price on the given day. 5 | 6 | Solution: 7 | The problem could be done in O(n) time complexity using stack.The span of stock at day 1 would always be 1 as there are no previous day before it. 8 | Index of the first day is pushed inside the stack,if price at the current day is less than the price of stack that is stored at stack top 9 | then span of the current day would be currentday-stack_top,after which we would push current day index in the stack. 10 | If price at current day is greater than price at the index stored by stack top then we would simply pop from the stack, 11 | untill stack become empty or price at stack_top is greater than cureent day price. 12 | If stack become empty then span at that day would be current_day+1 13 | 14 | ''' 15 | stock = [] 16 | n = int(input("Enter total number of days : ")) 17 | for i in range(0, n): 18 | t = int(input()) 19 | 20 | stock.append(t) 21 | answer=[] 22 | for i in range(0,n): 23 | answer.append(0) 24 | 25 | answer[0]=1 26 | stackhelp=[] 27 | stackhelp.append(0) 28 | for i in range(1,n): 29 | if(len(stackhelp)>0 and stock[i]0 and stock[i]>=stock[stackhelp[-1]]): 33 | stackhelp.pop() 34 | if(len(stackhelp)<=0): 35 | answer[i]=i+1; 36 | else: 37 | answer[i]=i-stackhelp[-1] 38 | stackhelp.append(i) 39 | print("Resultant span of each stock is : ") 40 | for i in range(0, n): 41 | print (answer[i], end =" ") 42 | 43 | ''' 44 | Time Complexity : O(N) 45 | Space Complexity: O(N) 46 | 47 | Test Cases: 48 | 49 | Input 1: 50 | 5 51 | 30 35 40 38 35 52 | 53 | Output 1: 54 | 1 2 3 1 1 55 | 56 | 57 | Input 2: 58 | 7 59 | 1 2 3 8 5 6 7 60 | 61 | Output 2: 62 | 1 2 3 4 1 2 3 63 | 64 | ''' -------------------------------------------------------------------------------- /Code/C++/couting_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | - Counting sort is a stable sorting technique 4 | - It is used to sort objects according to the keys that are small numbers 5 | - It counts the number of keys whose key values are same 6 | - This sorting technique is effective when the difference between different keys are not so big, otherwise, it can increase the space complexity. 7 | 8 | */ 9 | 10 | #include 11 | 12 | using namespace std; 13 | 14 | int maxValue(int A[], int n) 15 | { 16 | int m = A[0]; 17 | int i; 18 | for (i = 1; i < n; i++) 19 | { 20 | if (A[i] > m) 21 | m = A[i]; 22 | } 23 | return m; 24 | } 25 | 26 | void CountSort(int A[], int n) 27 | { 28 | int i, *C, j; 29 | 30 | // Obtaining thr max value from the array 31 | int max = maxValue(A, n); 32 | 33 | C = (int *)malloc((max + 1) * sizeof(int)); 34 | 35 | // Initialize empty array 36 | for (i = 0; i < max + 1; i++) 37 | C[i] = 0; 38 | 39 | // // Insert elements in their rescpetive position (array index) 40 | for (i = 0; i < n; i++) 41 | C[A[i]]++; 42 | 43 | // Get the sorted elements 44 | i = 0, j = 0; 45 | while (i < max + 1) 46 | { 47 | if (C[i] > 0) 48 | { 49 | A[j++] = i; 50 | C[i]--; 51 | } 52 | else 53 | i++; 54 | } 55 | } 56 | 57 | int main() 58 | { 59 | int n; 60 | cin >> n; 61 | int A[n]; 62 | for (int i = 0; i < n; i++) 63 | cin >> A[i]; 64 | CountSort(A, n); 65 | for (int i = 0; i < n; i++) 66 | cout << A[i] << " "; 67 | return 0; 68 | } 69 | 70 | /* 71 | 72 | Test Case: 73 | 74 | Input: 6 75 | 34 22 65 38 99 48 76 | 77 | Output: 22 34 38 48 65 99 78 | 79 | 80 | Input: 10 81 | 10 72 82 30 67 28 75 1 55 34 82 | 83 | Output: 1 10 28 30 34 55 67 72 75 82 84 | 85 | 86 | 87 | Time Complexity: 88 | Worst Time Complexity: O(n+r) 89 | Average Time Complexity: O(n+r) 90 | 91 | Space Complexity: O(n+r) 92 | 93 | */ 94 | -------------------------------------------------------------------------------- /Code/Java/peakvalueinarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | An array element is a peak if it is NOT smaller than 3 | its neighbours. For corner elements, we need to 4 | consider only one neighbour. 5 | Here we will Assume Peak element in Array is -11 i.e if peak elemwnt dosent exists then will retuen -1, 6 | then by Liner Search, we will compare (i) with (i+1) & (i-1), if found greater than both the Neighbouring Elemnts 7 | then it will retuen that Element. 8 | */ 9 | 10 | package peakval; 11 | import java.util.Scanner; 12 | 13 | public class peakvalueinarray { 14 | public static void main(String[] args) { 15 | Scanner scan = new Scanner(System.in); 16 | System.out.println("Enter Size of Array"); 17 | int n = scan.nextInt(); 18 | if (n>0) { 19 | System.out.println("Enter " + n + " Elements of array"); 20 | int[] arr = new int[n]; 21 | for (int i = 0; i < n; i++) { 22 | arr[i] = scan.nextInt(); 23 | } 24 | int ans = peakval(arr); 25 | System.out.println(); 26 | System.out.println("Peak Value in Array is : " + ans); 27 | }else { 28 | System.out.println("Enter Valid Length of Array"); 29 | } 30 | } 31 | public static int peakval(int[] arr){ 32 | if (arr.length >=2){ 33 | if(arr[0]>arr[1]){ 34 | return arr[0]; 35 | } 36 | } 37 | int peak = -1; 38 | for (int i = 1;iarr[i+1] && arr[i]>arr[i-1]){ 40 | peak = arr[i]; 41 | return peak; 42 | } 43 | } 44 | if (arr.length >=2){ 45 | if(arr[arr.length-1]>arr[arr.length-2]){ 46 | return arr[arr.length-1]; 47 | } 48 | } 49 | return peak; 50 | } 51 | } 52 | /* 53 | Test Cases: 54 | Input : 5 55 | 8 9 5 2 4 56 | Output: 9 57 | 58 | Input : 3 59 | 0 1 0 60 | Output: 1 61 | 62 | Time Complexity: O(n) 63 | Space Complexity: O(1) 64 | */ 65 | -------------------------------------------------------------------------------- /Code/C++/Climbing_Stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Description : 3 | You are climbing a staircase. It takes n steps to reach the top. 4 | 5 | Each time you can either climb 1 or 2 steps. 6 | In how many distinct ways can you climb to the top? 7 | Algorithm : 8 | Solving Using Dynamic Programming Approach. 9 | Sub-problem Formula of each trail : steps[i] = steps[i - 1] + steps[i - 2] 10 | Extra Storage Size : No extra storage Required. 11 | */ 12 | 13 | 14 | #include 15 | using namespace std; 16 | 17 | long long ClimbStairs(int N) 18 | { 19 | // Base Case : at the first stair (steps[0]) the number of ways to get there is 1 20 | // Base Case : at the second stair (steps[1]) the number of ways to get there is 2 21 | if(N == 1) 22 | return 1; 23 | 24 | long long s1 = 1; 25 | long long s2 = 2; 26 | 27 | // Calculate the steps at the (i - 1)th stair according to this formula : 28 | // steps[i] = steps[i - 1] + steps[i - 2] 29 | 30 | // starting from the third stair, calculate the number of ways to reach stair i according to the previous formula 31 | for(int i = 2; i < N; i++) 32 | { 33 | // calculate s2 and update s1 to be equal the previous s2 34 | long long tmp = s2; 35 | s2 = s1 + s2; 36 | s1 = tmp; 37 | } 38 | 39 | //Return the steps at the final stair. 40 | return s2; 41 | } 42 | 43 | int main() 44 | { 45 | int n; 46 | cout << "Enter the number of stairs to calculate the number of ways to get to it's top :\t"; 47 | cin >> n; 48 | 49 | if(n > 0) 50 | cout << "The number of distinct ways can you climb to the top :\t" << ClimbStairs(n) << endl; 51 | else 52 | cout << "The number of stairs must be greater than 0." < 9 | #include 10 | 11 | using namespace std; 12 | 13 | 14 | int main() { 15 | int val; 16 | int carry = 0; //Input the number whose factorial is to be calculated 17 | cin >> val; 18 | vector arr(10000, 0); //The size of the vector should be more than the digits present 19 | arr[0] = 1; //in the factorial of the number. 20 | int k = 0; 21 | 22 | for(int i = 1; i <= val; i++) { 23 | for(int j = 0;j <= k; j++) { 24 | arr[j] = arr[j] * i + carry; 25 | carry = arr[j] / 10; 26 | arr[j] = arr[j] % 10; 27 | } 28 | while(carry) { //The carries are forwarded in order to get the final result 29 | k++; 30 | arr[k] = carry % 10; 31 | carry /= 10; 32 | } 33 | } 34 | for(int i = k; i >= 0; i--) { //Each digit of the final answer is stored in a single index 35 | cout << arr[i]; //of the vector 36 | } 37 | cout << "\n"; 38 | return 0; 39 | } 40 | 41 | /* 42 | Test Cases : 43 | 44 | 1)Input : 10 45 | Output : 3628800 46 | 47 | 2)Input : 20 48 | Output : 2432902008176640000 49 | 50 | 3)Input : 30 51 | Output : 265252859812191058636308480000000 52 | 53 | Time Complexity: O ( N ) (where N is the number which is the input) 54 | Space Complexity: O ( N ) (where N is the number of digits present in the final answer) 55 | 56 | 57 | */ 58 | -------------------------------------------------------------------------------- /Code/C++/Largest_Rectangle.cpp: -------------------------------------------------------------------------------- 1 | /*Here, we consider each bar has a unit width. We will use a notion of a Rectangle for each bar and two indices j and k. For each bar, we can find the rectangle with the height of it and also containing it. 2 | To do this for a bar, let's say i bar, we go to left from i and stop at the first bar which is smaller than the i bar. Say we have stopped at j position. 3 | 4 | Time Complexity: For each bar we are considering a linear search. Thus it is O(n^2) in total. 5 | 6 | Here, we use Divide and Conquer Approach.*/ 7 | 8 | #include 9 | using namespace std; 10 | 11 | typedef long long lli; 12 | 13 | #define pb push_back 14 | 15 | 16 | vector < lli > height; 17 | vector < int > s; 18 | lli Histogram(vector &height) 19 | { 20 | s.clear(); 21 | height.push_back(0); 22 | 23 | lli sum = 0; 24 | int i = 0; 25 | while(i < height.size()) 26 | { 27 | if(s.empty() || height[i] > height[s.back()]) 28 | { 29 | s.push_back(i); 30 | i++; 31 | } 32 | else 33 | { 34 | int t = s.back(); 35 | s.pop_back(); 36 | 37 | sum = max(sum, height[t] * (s.empty() ? i : i - s.back() - 1)); 38 | } 39 | } 40 | 41 | return sum; 42 | } 43 | 44 | int main(void) 45 | { 46 | int i,j,k,kase=0; 47 | 48 | int n; 49 | while( scanf("%d",&n)==1 ) 50 | { 51 | height.assign(n, 0); 52 | for(i=0; i 8 | #include 9 | 10 | using namespace std; 11 | 12 | // Function to find max value 13 | int maxValue(int A[], int n) 14 | { 15 | int m = A[0]; 16 | int i; 17 | for (i = 1; i < n; i++) 18 | { 19 | if (A[i] > m) 20 | m = A[i]; 21 | } 22 | return m; 23 | } 24 | 25 | // Function for Bucket Sort 26 | void BucketSort(int A[], int n) 27 | { 28 | // Calling function get maximum value among all the elements 29 | int maximum = maxValue(A, n); 30 | 31 | // Create empty bins 32 | vector Bins[maximum + 1]; 33 | 34 | // Insert elements in their rescpetive bin 35 | for (int i = 0; i < n; i++) 36 | Bins[A[i]].push_back(A[i]); 37 | 38 | // Get the sorted elements 39 | int i = 0, k = 0; 40 | while (i < maximum + 1) 41 | { 42 | for (int j = Bins[i].size() - 1; j >= 0; j--) 43 | A[k++] = Bins[i][j]; 44 | i++; 45 | } 46 | } 47 | 48 | int main() 49 | { 50 | int n; 51 | // Number of elements 52 | cin >> n; 53 | int A[n]; 54 | 55 | // Taking input of the elements 56 | for (int i = 0; i < n; i++) 57 | cin >> A[i]; 58 | 59 | // Calling function to sort the elements using Bucket Sort 60 | BucketSort(A, n); 61 | 62 | // Displaying Sorted Elements 63 | for (int i = 0; i < n; i++) 64 | cout << A[i] << " "; 65 | return 0; 66 | } 67 | 68 | /* 69 | 70 | Test Case: 71 | Input: 7 72 | 4 63 1 53 87 44 36 73 | Output: 1 4 36 44 53 63 87 74 | 75 | Input: 6 76 | 5 3 12 7 21 4 77 | Output: 3 4 5 7 12 21 78 | 79 | Time Complexity: 80 | Worst Time Complexity: O(n^2) 81 | Average Time Complexity: O(n+k) 82 | Best Time Complexity: O(n+k) 83 | 84 | Space Complexity: O(n+k) 85 | 86 | where O(n) is the complexity for making the buckets and 87 | O(k) is the complexity for sorting the elements of the bucket 88 | */ 89 | -------------------------------------------------------------------------------- /Code/C++/Brian_Kernighan.cpp: -------------------------------------------------------------------------------- 1 | /* Brian Kernighan's Algorithm 2 | 3 | It is an algorithm developed to count the number of set bits in a number 4 | in a efficient way. 5 | 6 | IDEA/INTUITION behind the efficient algorithm- 7 | 1) Consider any number n. Then if we consider (n-1), it is observed 8 | that in (n-1), "All the bits from the last set bit to the rightmost 9 | bit gets changed to it's opposite bit". 10 | 11 | Example- 12 | let n=40, binary representation -> 000....101000 (32 bit) 13 | now (n-1)=39, binary representation -> 000...100111 14 | We can clearly verify the above statement from the example. 15 | 16 | 2) The next step is to take the bitwise And(&) of n and (n-1). 17 | What this step does, is that it turns off the last set bit. 18 | 19 | Example- 20 | n=40 -> 000...101000 21 | n=39 -> 000...100111 22 | ----------------------- 23 | n&(n-1) -> 000...100000 24 | 25 | We clearly see the only change tha happens after the 2 steps, 26 | is that the left most set bit gets turned off. 27 | 28 | 3) We repeat this step until n becomes 0. 29 | 30 | Above function at line 36, that takes an integer as argument and 31 | returns the number of set bits. 32 | */ 33 | #include 34 | using namespace std; 35 | 36 | int count_set(int n){ 37 | // 'ans' variable keeps the track of the number of set bits 38 | int ans = 0; 39 | while(n > 0){ 40 | n = (n & (n-1)); 41 | ans++; 42 | } 43 | return ans; 44 | } 45 | 46 | //main function 47 | int main(){ 48 | int n; 49 | // Taking input from the user 50 | cin >> n; 51 | int ans = count_set(n); 52 | cout << ans << "\n"; 53 | } 54 | 55 | /* Test case : 56 | 1) input : 32 57 | output : 1 58 | 2) input : 39 59 | output : 4 60 | 61 | Time Complexity -> O(n) where n is number of set bits in input. 62 | 63 | Space Complexity -> O(1) 64 | 65 | */ 66 | 67 | -------------------------------------------------------------------------------- /Code/Python/peak_element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Peak Element using Binary Search 3 | Problem Statement: Given an array of size n, find the peak element. 4 | Peak element is the element which is greater than its neighbours. 5 | There may exist more than one peak element, so print any one. 6 | ''' 7 | 8 | def binary_search(in_arr, start, end): 9 | 10 | # find the middle element useing "start + (end - start) / 2" 11 | mid = start + (end - start) // 2 12 | 13 | # check if the middle element is greater than its neighbors 14 | # by applying the condition for binary search 15 | if ((mid == 0 or in_arr[mid - 1] <= in_arr[mid]) and 16 | (mid == len(in_arr) - 1 or in_arr[mid + 1] <= in_arr[mid])): 17 | # if true then return the index of that element 18 | return mid 19 | 20 | # If the left neighbor of "mid" is greater than the middle element, 21 | # find the peak in the left sublist using recursion 22 | if mid - 1 >= 0 and in_arr[mid - 1] > in_arr[mid]: 23 | return binary_search(in_arr, start, mid - 1) 24 | 25 | # If the right neighbor of "mid" is greater than the middle element, 26 | # find the peak in the right sublist using recursion 27 | 28 | return binary_search(in_arr, mid + 1, end) 29 | 30 | 31 | if __name__ == '__main__': 32 | # input the size of array 33 | n = int(input()) 34 | arr = [] 35 | # enter the elements of the array 36 | for i in range(0, n): 37 | arr.append(int(input())) 38 | # calling the function to find the index of peak element 39 | pos = binary_search(arr, 0, n - 1) 40 | # printing the element 41 | print("The peak element is", arr[pos]) 42 | 43 | 44 | ''' 45 | Test Case 1: 46 | Input - 47 | 5 48 | 1 49 | 3 50 | 2 51 | 5 52 | 1 53 | Output - 54 | The peak element is 3 55 | 56 | Test Case 2: 57 | Input - 58 | 7 59 | 1 60 | 2 61 | 3 62 | 4 63 | 3 64 | 2 65 | 1 66 | Output - 67 | The peak element is 4 68 | 69 | Time Complexity: O(logn), since we used binary search 70 | Space Complexity: O(1), no extra space is used 71 | ''' 72 | -------------------------------------------------------------------------------- /Code/C++/splitarraylargestsum.cpp: -------------------------------------------------------------------------------- 1 | // Given an array nums which consists of non-negative integers and an integer m, 2 | // you can split the array into m non-empty continuous subarrays. 3 | // Input: nums = [7,2,5,10,8], m = 2 4 | // Output: 18 5 | // Explanation: 6 | // There are four ways to split nums into two subarrays. 7 | // The best way is to split it into [7,2,5] and [10,8], 8 | // where the largest sum among the two subarrays is only 18. 9 | 10 | #include 11 | using namespace std; 12 | 13 | int splitArray(vector& nums, int m) { 14 | int n = nums.size(); 15 | vector> dp(n + 1, vector(m + 1, INT_MAX)); 16 | vector sub(n + 1, 0); 17 | for (int i = 0; i < n; i++) { 18 | sub[i + 1] = sub[i] + nums[i]; 19 | } 20 | // f[i][j] to be the minimum largest subarray sum for splitting nums[0..i] into j parts 21 | dp[0][0] = 0; 22 | for (int i = 1; i <= n; i++) { 23 | for (int j = 1; j <= m; j++) { 24 | for (int k = 0; k < i; k++) { 25 | dp[i][j] = min(dp[i][j], max(dp[k][j - 1], sub[i] - sub[k])); 26 | } 27 | } 28 | } 29 | return dp[n][m]; 30 | } 31 | 32 | int main(){ 33 | // Number of element in the array 34 | int n; 35 | cin >> n; 36 | vector nums(n); 37 | // Input element of an array 38 | for(int i = 0; i < n; i++){ 39 | cin >> nums[i]; 40 | } 41 | 42 | int number_of_split; 43 | cin >> number_of_split; 44 | // calling splitArray function to find number of ways to split nums into number_of_split subarray 45 | // with minimum largest sum. 46 | cout << splitArray(nums, number_of_split) << endl; 47 | 48 | return 0; 49 | } 50 | 51 | // Input 1: nums = [7,2,5,10,8], number_of_split = 2 52 | // Output 1: 18 53 | 54 | // Input 2: nums = [1,2,3,4,5], number_of_split = 2 55 | // Output 2: 9 56 | 57 | // Input: nums = [1,4,4], number_of_split = 3 58 | // Output: 4 59 | 60 | // Time Complexity : O(n * n + number_of_split) 61 | // Space Complexity : O(n * number_of_split) 62 | // where n is the size of array nums. 63 | -------------------------------------------------------------------------------- /Code/Python/Three_Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PROBLEM STATEMENT: 3 | Given an integer array, arr of size n, Find out all the possible distinct triplets that sum up to 0, i.e., 4 | if a triplet consists of a, b, c which belongs to arr and if a + b + c = 0, then print a, b, c. 5 | ''' 6 | 7 | 8 | # A function to find triplets whose sum is equal to 0 9 | def ThreeSum(arr, n): 10 | arr.sort() #Sorting array 11 | for i in range(n-2): 12 | if i != 0 and arr[i-1] == arr[i] : 13 | continue 14 | # Initializing the two pointers, left and right 15 | left = i + 1 16 | right = n - 1 17 | while left < right : 18 | lis = [arr[i], arr[left], arr[right]] #Creating a list of three elements 19 | sumval = sum(lis) #sumval is initialized with the sum of the elements of list 20 | if sumval == 0 : 21 | print(lis) #Printing the list of triplets whose sum = 0 22 | while left < n-1 and arr[left] == arr[left+1] : 23 | left += 1 24 | while right > 0 and arr[right-1] == arr[right] : 25 | right -= 1 26 | left += 1 27 | right -= 1 28 | elif sumval > 0 : #if sumval > 0, decrementing right by 1 29 | right -= 1 30 | else : #if sumval < 0, incrementing left by 1 31 | left += 1 32 | 33 | 34 | # Driver Code 35 | 36 | # User inputs the the size of array 37 | n = int(input("Enter the size of an array: ")) 38 | arr = [] 39 | print("Enter ", n ," elements:") 40 | 41 | # User inputs array elemnents 42 | for i in range(n): 43 | arr.append(int(input())) 44 | 45 | # A function call to Three Sum 46 | print("The triplets which sum upto 0 are:") 47 | ThreeSum(arr, n) 48 | 49 | 50 | ''' 51 | TEST CASES: 52 | 1. 53 | Input: 54 | 6 55 | [-1, 0, 1, 2, -1, -4] 56 | Output: 57 | [-1, -1, 2] 58 | [-1, 0, 1] 59 | 60 | 2. 61 | Input: 62 | 8 63 | [4, 0, 1, 3, -1, -3, -4, 2] 64 | Output: 65 | [-4, 0, 4] 66 | [-4, 1, 3] 67 | [-3, -1, 4] 68 | [-3, 0, 3] 69 | [-3, 1, 2] 70 | [-1, 0, 1] 71 | 72 | TIME COMPLEXITY: O(n^2), Due to two nested loops 73 | SPACE COMPLEXITY: O(n), Because an additional list is created to store the triplets 74 | where 'n' denotes the size of the array which user inputs 75 | ''' 76 | -------------------------------------------------------------------------------- /Algorithm/Searching_Sorting/dnf_sort.cpp: -------------------------------------------------------------------------------- 1 | /*Dutch National Flag Algorithm 2 | At first, the full array is unknown. There are three indices - low, mid and high. Initially, the value of low = mid = 1 and high = N. 3 | If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range. 4 | Similarly, if the element is 1 then keep it as it is but shrink the unknown range. 5 | If the element is 2 then swap it with an element in high range. 6 | Algorithm: 7 | 1.Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2). 8 | 2.Traverse the array from start to end and mid is less than high. (Loop counter is i) 9 | 3.If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1 10 | 4.If the element is 1 then update mid = mid + 1 11 | 5.If the element is 2 then swap the element with the element at index high and update high = high - 1 and update i = i - 1. As the swapped element is not processed 12 | 6.Print the output array. 13 | */ 14 | 15 | #include 16 | using namespace std; 17 | 18 | void swap(int arr[],int i,int j){ 19 | int temp=arr[i]; 20 | arr[i]=arr[j]; 21 | arr[j]=temp; 22 | } 23 | 24 | void dnfSort(int arr[],int n){ 25 | int low=0; 26 | int mid=0; 27 | int high=n-1; 28 | 29 | while(mid<=high){ 30 | if(arr[mid]==0){ 31 | swap(arr,low,mid); 32 | low++; 33 | mid++; 34 | } 35 | else if(arr[mid]==1){ 36 | mid++; 37 | } 38 | else{ 39 | swap(arr,mid,high); 40 | high--; 41 | } 42 | } 43 | } 44 | 45 | int main(){ 46 | int n; 47 | cin >> n; 48 | int arr[n]; 49 | for(int i=0;i> arr[i]; 51 | } 52 | dnfSort(arr,n); 53 | 54 | for(int i=0;i 19 | 20 | using namespace std; 21 | 22 | int main() 23 | { char str[256]; 24 | 25 | //creating an array namely count to keep track of individual count of characters. 26 | //here used 256 as we have total 256 ASCII characters. 27 | int count[256]={0}; 28 | 29 | // 'output' will store the maximum occuring character in the string. 30 | int output; 31 | int getmax=0; 32 | 33 | cout<<"Enter the String:-\n"; 34 | cin>>str; 35 | 36 | //this 'strlen' will calculate the length of the string 37 | int length=strlen(str); 38 | 39 | //it will give the maximum occured character 40 | for(int i=0;i 11 | using namespace std; 12 | 13 | void merge(int arr1[],int arr2[],int n,int m) 14 | { 15 | //iterating the first array from last and second array from first element 16 | for(int i=n-1,j=0;i>=0 && jarr2[j];i--,j++) //--------O(n+m) 17 | { 18 | //swap those elements of second array from first array which are less than the element of first array 19 | int temp=arr1[i]; 20 | arr1[i]=arr2[j]; 21 | arr2[j]=temp; 22 | } 23 | // sort the respective arrays and combined array will be our result 24 | sort(arr1,arr1+n); //---------O(nlogn) 25 | sort(arr2,arr2+m); //---------O(mlogm) 26 | } 27 | 28 | int main() 29 | { 30 | int n,m; 31 | cin>>n>>m; 32 | int arr1[n],arr2[m]; 33 | //taking input for first array 34 | for(int i=0;i>arr1[i]; 36 | //taking input for first array 37 | for(int i=0;i>arr2[i]; 39 | //call merge operation 40 | merge(arr1,arr2,n,m); 41 | 42 | //printing sorted array 43 | for(int i=0;i 9 | #include 10 | #include 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | template 16 | 17 | class Graph{ 18 | 19 | map > m; 20 | public: 21 | void AddEdge(T src, T dest, bool nondirectional = true){ 22 | 23 | m[src].push_back(dest); 24 | // bi-directional 25 | if(nondirectional){ 26 | m[dest].push_back(src); 27 | } 28 | } 29 | 30 | void print(){ 31 | for(auto i : m){ 32 | cout << i.first<<" -> "; 33 | for(auto j: i.second){ 34 | cout< "; 35 | } 36 | cout<<"\n"; 37 | } 38 | } 39 | void DFS_helper(T src, map &visited){ 40 | 41 | cout << src <<" "; 42 | 43 | visited[src] = true; 44 | for(auto i : m[src]){ 45 | if(!visited[i]){ 46 | DFS_helper(i, visited); 47 | } 48 | } 49 | } 50 | 51 | void DFS(T src){ 52 | map visited; 53 | 54 | DFS_helper(src, visited); 55 | 56 | } 57 | 58 | }; 59 | 60 | int main(){ 61 | Graph g; 62 | 63 | //no. of edges 64 | int n; 65 | 66 | cin >> n; 67 | 68 | int u, v; 69 | 70 | for(int i=0; i> u >> v; 72 | g.AddEdge(u,v); 73 | } 74 | 75 | 76 | g.DFS(0); 77 | 78 | 79 | return 0; 80 | } 81 | 82 | /* 83 | 84 | Test Case : 85 | 86 | Input : 7 87 | 0 1 88 | 0 4 89 | 1 2 90 | 2 3 91 | 2 4 92 | 3 4 93 | 3 5 94 | 95 | output - 0 1 2 3 4 5 96 | 97 | Input : 6 98 | 0 1 99 | 0 2 100 | 1 2 101 | 2 0 102 | 2 3 103 | 3 3 104 | 105 | Output : 0 1 2 3 106 | 107 | Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph. 108 | Space Complexity: O(V) 109 | 110 | */ -------------------------------------------------------------------------------- /Code/C++/Union_of_two_unsorted_array.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to find the Union of two unsorted arrays. 2 | 3 | /* Procedure 4 | ================== 5 | First of all here we'll initialize an empty set 's'. 6 | then we'll iterate through the first array and put every element of the first array in the set s. 7 | Repeat the process for the second array. 8 | Finally we'll print the set s. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | void Union(int a1[], int a2[], int n1, int n2) 14 | { 15 | set s; 16 | for (int i = 0; i < n1; i++) 17 | s.insert(a1[i]); 18 | for (int i = 0; i < n2; i++) 19 | s.insert(a2[i]); 20 | for (auto it = s.begin(); it != s.end(); it++) 21 | cout << *it << " "; 22 | cout << endl; 23 | } 24 | int main() 25 | { 26 | int a1[100005], a2[1000005], n1, n2, i; 27 | cout << "Enter the size of both the arrays: "; 28 | cin >> n1 >> n2; 29 | cout << "\nEnter the elements of 1st array:"; 30 | for (i = 0; i < n1; i++) 31 | { 32 | cin >> a1[i]; 33 | } 34 | cout << "\nEnter the elements of 2nd array:"; 35 | for (i = 0; i < n2; i++) 36 | { 37 | cin >> a2[i]; 38 | } 39 | cout << "\nUnion of both the arrays:\n"; 40 | Union(a1, a2, n1, n2); 41 | return 0; 42 | } 43 | 44 | /* 45 | Time Complexity: O((n+m) log(n+m)) 46 | where m,n are the sizes of both arrays. 47 | Sample Input output set 48 | ========================== 49 | Sample Input 1 50 | ---------------- 51 | 5 52 | 6 53 | 2 6 9 7 1 54 | 1 2 3 4 5 6 55 | Sample Output 56 | -------------- 57 | Enter the size of both the arrays: 58 | Enter the elements of 1st array: 59 | Enter the elements of 2nd array: 60 | Union of both the arrays: 61 | 1 2 3 4 5 6 7 9 62 | 63 | Sample Input 2 64 | --------------- 65 | 6 66 | 6 67 | 1 2 3 4 5 6 68 | 1 2 3 4 5 6 69 | Sample Output 70 | Enter the size of both the arrays: 71 | Enter the elements of 1st array: 72 | Enter the elements of 2nd array: 73 | Union of both the arrays: 74 | 1 2 3 4 5 6 75 | 76 | Sample Input 77 | 1 78 | 4 79 | 7 80 | 1 2 3 4 81 | Sample Output 82 | Enter the size of both the arrays: 83 | Enter the elements of 1st array: 84 | Enter the elements of 2nd array: 85 | Union of both the arrays: 86 | 1 2 3 4 7 87 | */ 88 | -------------------------------------------------------------------------------- /Code/C++/shell_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | - Shell sort is an algorithm that first sorts the elements far apart from each other and successively reduces the interval between the elements to be sorted. 4 | - It is a generalized version of insertion sort. 5 | 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | void ShellSort(int A[], int n) 13 | { 14 | int gap, i, j, temp; 15 | 16 | // Start with a big gap, then reduce the gap 17 | for (gap = n / 2; gap >= 1; gap /= 2) 18 | { 19 | // Do a gapped insertion sort for this gap size. 20 | // The first gap elements a[0..gap-1] are already in gapped order 21 | // keep adding one more element until the entire array is gap sorted 22 | for (i = gap; i < n; i++) 23 | { 24 | // add a[i] to the elements that have been gap sorted 25 | // save a[i] in temp and make a hole at position i 26 | temp = A[i]; 27 | j = i - gap; 28 | 29 | // shift earlier gap-sorted elements up until the correct 30 | // location for a[i] is found 31 | while (j >= 0 && A[j] > temp) 32 | { 33 | A[j + gap] = A[j]; 34 | j = j - gap; 35 | } 36 | 37 | // put temp (the original a[i]) in its correct location 38 | A[j + gap] = temp; 39 | } 40 | } 41 | } 42 | 43 | int main() 44 | { 45 | int n; 46 | cin >> n; 47 | 48 | int A[n]; 49 | 50 | for (int i = 0; i < n; i++) 51 | { 52 | cin >> A[i]; 53 | } 54 | 55 | ShellSort(A, n); 56 | 57 | for (int i = 0; i < n; i++) 58 | { 59 | cout << A[i] << " "; 60 | } 61 | 62 | return 0; 63 | } 64 | 65 | /* 66 | 67 | Test Case: 68 | 69 | Input: 7 70 | 64 923 84 738 12 873 2 71 | 72 | 73 | Output: 2 12 64 84 738 873 923 74 | 75 | 76 | Input: 6 77 | 64 -83 19 -22 73 100 78 | 79 | 80 | Output: -83 -22 19 64 73 100 81 | 82 | 83 | 84 | Time Complexity: 85 | Worst Time Complexity: O(n^2) 86 | Average Time Complexity: O(n*log(n)^2) O(n^(3/2)) 87 | Best Time Complexity: O(n+r) 88 | 89 | Space Complexity: O(1) 90 | 91 | */ 92 | -------------------------------------------------------------------------------- /Code/C++/searching_a_word_in_trie.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A trie is a tree and each node in it contains the number of pointers equal to the number of 3 | characters of the alphabet. For example, if we assume that all the strings are formed with English 4 | alphabet characters “a” to “z” then each node of the trie contains 26 pointers. 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | class node{ 14 | public: 15 | 16 | char data; 17 | map m; 18 | bool is_terminal; 19 | 20 | node(char c){ 21 | data = c; 22 | is_terminal = false; 23 | } 24 | 25 | }; 26 | 27 | class Trie{ 28 | node* root; 29 | public: 30 | 31 | Trie(){ 32 | root = new node('\0'); 33 | } 34 | 35 | void Addword(char word[]){ 36 | node* temp = root; 37 | 38 | for(int i=0;word[i]!='\0';i++){ 39 | char ch = word[i]; 40 | 41 | //if not present 42 | if(temp->m.count(ch)==0){ 43 | // create link 44 | node* child = new node(ch); 45 | temp->m[ch] = child; 46 | temp = child; 47 | } 48 | else{ 49 | // next address 50 | temp = temp->m[ch]; 51 | 52 | } 53 | } 54 | // last node 55 | temp->is_terminal = true; 56 | } 57 | 58 | bool search(char word[]){ 59 | 60 | node* temp = root; 61 | 62 | for(int i=0;word[i]!='\0';i++){ 63 | 64 | char ch = word[i]; 65 | // if present 66 | if(temp->m.count(ch)==1){ 67 | temp = temp->m[ch]; 68 | } 69 | else{ 70 | // not present 71 | return false; 72 | } 73 | 74 | } 75 | // not always at last node 76 | return temp->is_terminal; 77 | } 78 | 79 | 80 | }; 81 | 82 | int main() 83 | { 84 | Trie T; 85 | T.Addword("adf"); 86 | T.Addword("not"); 87 | T.Addword("nott"); 88 | 89 | char word[1000]; 90 | cin >> word; 91 | 92 | 93 | 94 | cout << boolalpha< 23 | #define input(n); int n; cin>> n 24 | using namespace std; 25 | 26 | int Kth_Symbol_Grammar(int n,int k) 27 | { 28 | /* 29 | Base case is when both n and k are equal to 1. 30 | Now calculating mid and observing that (n-1)th row is exactly same to the nth row till mid. 31 | Hence, calling function twice when k is less than equal to mid or grater than mid, for n-1 and k else n-1 and k-mid. 32 | */ 33 | if(n==1 && k==1) 34 | return 0; 35 | int mid = pow(2,n-1) / 2; 36 | 37 | if(k<=mid) 38 | return Kth_Symbol_Grammar(n-1,k); 39 | else 40 | return !Kth_Symbol_Grammar(n-1,k-mid); 41 | } 42 | 43 | 44 | int main() 45 | { 46 | cout<<"Test cases: "; 47 | input(t); 48 | // enter number of test cases 49 | while(t--) 50 | { 51 | cout<<"INPUT: "; 52 | input(n); 53 | // enter n (which acts as number of rows) 54 | input(k); 55 | // enter k (which acts as number of columns) 56 | int Symbol = Kth_Symbol_Grammar(n,k); 57 | // Function calling and returning the Kth-indexed grammar 58 | cout<<"OUTPUT: "< pq = new PriorityQueue<>(); // A min Priority Queue 23 | 24 | for(int i=0;iele) 33 | { 34 | ele=arr[i]; // if current element is greater than minimum element replace 35 | } 36 | pq.add(ele); // add in Priority Queue 37 | } 38 | 39 | while(pq.size()>0) 40 | { 41 | System.out.print(pq.remove()+" "); // Print the Elements in Priority Queue 42 | } 43 | 44 | } 45 | 46 | } 47 | /* 48 | Test Case 1 : 49 | Input : 13 50 | 12 62 22 15 37 99 11 37 98 67 31 84 99 51 | 4 52 | output :84 98 99 99 53 | 54 | */ 55 | /* 56 | Test Case 2 : 57 | Input : 15 58 | 1 45 2 15 37 99 11 37 98 67 31 84 9 100 3 59 | 3 60 | output :98 99 100 61 | */ 62 | /* 63 | Time complexity : O(nlogk) // where n is size of input array and k is number of largest element needed 64 | Auxiliary Space : O(k) 65 | */ 66 | -------------------------------------------------------------------------------- /Code/Python/Transpose_of_matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PROBLEM STATEMENT: 3 | Given a matrix with m rows and n columns. Print its transpose. Transpose of a 4 | matrix is obtained by changing the rows to columns and columns to rows i.e., by 5 | changing mat[i][j] to mat[j][i]. 6 | ''' 7 | 8 | 9 | # A function to print the transpose of the given matrix 10 | def Transpose(mat, m, n): 11 | # Creating a matrix with n rows and m columns 12 | trans = [[0 for y in range(m)] for x in range(n)] 13 | for x in range(n): 14 | for y in range(m): 15 | trans[x][y] = mat[y][x] 16 | # Printing the transposed matrix 17 | print(trans) 18 | 19 | 20 | # Driver Code 21 | # User inputs the the dimension of matrix 22 | m = int(input("Enter the no. of rows: ")) 23 | n = int(input("Enter the no. of columns: ")) 24 | 25 | # Creating a matrix with m rows and n columns 26 | mat = [[0 for j in range(n)] for i in range(m)] 27 | print("Enter elements of matrix:") 28 | # User inputs matrix elemnents 29 | for i in range(m): 30 | for j in range(n): 31 | num = int(input()) 32 | mat[i][j] = num 33 | # Printing the entered matrix 34 | print("The entered matrix is:") 35 | print(mat) 36 | # A function call to transpose the matrix 37 | print("The transpose of the entered matrix is:") 38 | Transpose(mat, m, n) 39 | 40 | 41 | ''' 42 | TEST CASES: 43 | 1. 44 | Input: 45 | Enter the no. of rows: 4 46 | Enter the no. of columns: 3 47 | Enter elements of matrix: 48 | 1 49 | 2 50 | 2 51 | 2 52 | 3 53 | 3 54 | 3 55 | 4 56 | 4 57 | 4 58 | 1 59 | 1 60 | Output: 61 | The entered matrix is: 62 | [[1, 2, 2], [2, 3, 3], [3, 4, 4], [4, 1, 1]] 63 | The transpose of the entered matrix is: 64 | [[1, 2, 3, 4], [2, 3, 4, 1], [2, 3, 4, 1]] 65 | 66 | 2. 67 | Input: 68 | Enter the no. of rows: 2 69 | Enter the no. of columns: 1 70 | Enter elements of matrix: 71 | 8 72 | 10 73 | Output: 74 | The entered matrix is: 75 | [[8], [10]] 76 | The transpose of the entered matrix is: 77 | [[8, 10]] 78 | 79 | TIME COMPLEXITY: O(m*n), because we're traversing each and every elemnt of the 80 | matrix of size mXn 81 | SPACE COMPLEXITY: O(m*n), due to the transpose matrix created of size nXm 82 | where 'm' and 'n' denotes the dimension of the matrix as entered by the user. 83 | ''' 84 | -------------------------------------------------------------------------------- /Code/Java/matrixop_add.java.java: -------------------------------------------------------------------------------- 1 | /* 2 | A 2D Array is Used for Matrix, size is taken first then 2 Matrix of that Size is taken 3 | (i,j)th Element of 1st Matrix is added only to (i,j)th Element of 2nd Matrix in Matrix Addition. 4 | */ 5 | 6 | package matrixop; 7 | import java.util.Scanner; 8 | 9 | public class MatrixOP { 10 | public static void main(String[] args) { 11 | Scanner scan = new Scanner(System.in); 12 | System.out.println("Enter Size of Matrix"); 13 | int l = scan.nextInt(); 14 | int h = scan.nextInt(); 15 | int[][] twoDarr1 = new int[l][h]; 16 | 17 | System.out.println("Enter All Values of 1st Matrix"); 18 | // Taking Input of 1st Matrix 19 | for (int i = 0; i < l; i++) { 20 | for (int j = 0; j < h; j++) { 21 | twoDarr1[i][j] = scan.nextInt(); 22 | } 23 | } 24 | 25 | System.out.println("Enter All Values of 2nd Matrix :"); 26 | int[][] twoDarr2 = new int[l][h]; 27 | // Taking Input of 2nd Matrix 28 | for (int i = 0; i < l; i++) { 29 | for (int j = 0; j < h; j++) { 30 | twoDarr2[i][j] = scan.nextInt(); 31 | } 32 | } 33 | 34 | 35 | // Adding Two Matrix 36 | for (int i = 0; i < l; i++) { 37 | for (int j = 0; j < h; j++) { 38 | twoDarr1[i][j] += twoDarr2[i][j]; 39 | } 40 | } 41 | 42 | //Printing Sum of 2 Matrix 43 | System.out.println("Addition of Two Matrix is :"); 44 | for (int i = 0; i < l; i++) { 45 | for (int j = 0; j < h; j++) { 46 | System.out.print(twoDarr1[i][j] + " "); 47 | } 48 | System.out.println(); 49 | } 50 | } 51 | } 52 | /* 53 | Test Cases: 54 | Input : 2 3 55 | 4 1 8 56 | 9 4 3 57 | 1 2 3 58 | 8 6 7 59 | 60 | Output: 5 3 11 61 | 17 10 10 62 | 63 | 64 | 65 | 66 | Input : 2 2 67 | 4 2 68 | 8 5 69 | 1 6 70 | -1 3 71 | 72 | Output: 5 8 73 | 7 8 74 | 75 | Time Complexity: O(n^2) where n is the lenght of matrix 76 | Space Complexity: O(n^2) 77 | */ 78 | -------------------------------------------------------------------------------- /Code/Python/Balanced_brackets.py: -------------------------------------------------------------------------------- 1 | # In this problem we are given a string expression 2 | # with string elements as "{","}","[","]","(" and ")". 3 | # We have to tell whether the brackets are balanced or not. 4 | # For Ex: 5 | # {([])} ----> this expression has balanced brackets. 6 | # {][]) -----> this sequence does not have balanced brackets. 7 | 8 | 9 | # In this problem we are given a string expression 10 | # with string elements as "{","}","[","]","(" and ")". 11 | # We have to tell whether the brackets are balanced or not. 12 | # For Ex: 13 | # {([])} ----> this expression has balanced brackets. 14 | # {][]) -----> this sequence does not have balanced brackets. 15 | 16 | 17 | s=input("Enter the expression\n") 18 | 19 | #this stack will contain all the opening brackets 20 | stack=[] 21 | 22 | #this flag will tell if the brackets are balanced or not 23 | flag=0 24 | 25 | for i in s: 26 | if((i == "(") or (i == "[") or (i == "{")): 27 | stack.append(i) 28 | else: 29 | #if stack is empty brackets are 30 | #not balanced 31 | if not stack: 32 | flag=1 33 | break 34 | 35 | #e will contain the last opening bracket 36 | e=stack.pop() 37 | 38 | #if opening and closing brackets are not same 39 | #the brackets are not balanced 40 | if(e == '{' and i != "}"): 41 | flag=1 42 | break 43 | if(e == '(' and i != ")"): 44 | flag=1 45 | break 46 | if(e == '[' and i != "]"): 47 | flag=1 48 | break 49 | 50 | #if stack is not empty after 51 | #transversing whole loop then 52 | #brackets are not balanced 53 | if(flag==0): 54 | if stack: 55 | flag=1 56 | 57 | if(flag==1): 58 | print("Brackets are not balanced") 59 | else: 60 | print("Brackets are balanced") 61 | 62 | # TEST CASES 63 | 64 | # 1)Input: 65 | # Enter the expression 66 | # {([])} 67 | # Output: 68 | # Brackets are balanced 69 | # 70 | # 71 | # 2)Input: 72 | # Enter the expression 73 | # {([] 74 | # Output: 75 | # Brackets are not balanced 76 | 77 | # Time complexity: O(n) 78 | # Space complexity: O(n) , Here n is the length of the expression 79 | # 80 | -------------------------------------------------------------------------------- /Code/Java/root_to_leaf_path_sum.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Problem Statement- 4 | We need to find that whether there is a possible path from root node to any leaf node in given binary tree. 5 | 6 | Algorithm- 7 | In order to check this we need to traverse through all the possible paths 8 | We start traversing from the root node and we keep on subtracting the node value from the required sum. 9 | if we reach a leaf node with sum=0 ,it means there exist such path 10 | else there does not exist any such path. 11 | 12 | */ 13 | package Code.Java; 14 | import java.io.*; 15 | import java.util.*; 16 | 17 | class Node { 18 | int val; 19 | Node left, right; 20 | 21 | // constructor 22 | 23 | Node(int data) { 24 | val = data; 25 | left = null; 26 | right = null; 27 | } 28 | } 29 | 30 | public class root_to_leaf_path_sum { 31 | static Node add(Node root, int val) { 32 | if (root == null) { 33 | root = new Node(val); 34 | } else if (val <= root.val) { 35 | root.left = add(root.left, val); 36 | } else { 37 | root.right = add(root.right, val); 38 | } 39 | return root; 40 | } 41 | 42 | static boolean hasPathSum(Node root, int sum) { 43 | if (root == null) { 44 | return false; 45 | } 46 | if (root.left == null && root.right == null && sum - root.val == 0) { 47 | return true; 48 | } 49 | return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)); 50 | } 51 | 52 | public static void main(String[] args) throws IOException { 53 | Scanner sc = new Scanner(System.in); 54 | int n = sc.nextInt(); 55 | int val1 = sc.nextInt(); 56 | Node node = new Node(val1); 57 | for (int i = 1; i < n; i++) { 58 | int val = sc.nextInt(); 59 | add(node, val); 60 | } 61 | int sum = sc.nextInt(); 62 | boolean ans = hasPathSum(node, sum); 63 | System.out.println(ans); 64 | sc.close(); 65 | return; 66 | } 67 | } 68 | 69 | /* 70 | * Test Case 1: 71 | * 72 | * Input: 4 1 7 9 4 50 73 | * 74 | * Output: false 75 | * 76 | * Test Case 2: 77 | * 78 | * Input: 5 5 1 7 6 8 6 79 | * 80 | * Output: true 81 | * 82 | * Time Complexity- O(n) 83 | Space Complexity-O(height) 84 | */ 85 | -------------------------------------------------------------------------------- /Code/Java/piglatin_convertor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * In Pig Latin - 3 | * - words starting with consonant - take the consonant cluster and 4 | * move it to the end of the word, adding the suffix - 'ay'. 5 | * - words starting with vowel - add the suffix 'hey' to the word 6 | */ 7 | 8 | import java.util.*; 9 | 10 | public class piglatin_convertor 11 | { 12 | public void main() 13 | { 14 | Scanner scanner = new Scanner(System.in); 15 | 16 | System.out.println("Enter a string: "); 17 | String str = scanner.nextLine(); 18 | 19 | System.out.println("In piglatin: "); 20 | System.out.println(string_piglatin(str)); 21 | } 22 | 23 | String string_piglatin(String str) 24 | { 25 | str = str + " "; 26 | 27 | String w = "", piglatin = ""; 28 | char ch; 29 | int i; 30 | 31 | for(i = 0; i < str.length(); i++) 32 | { 33 | ch = str.charAt(i); 34 | 35 | if(ch == ' ') 36 | { 37 | piglatin += word_piglatin(w) + ' '; 38 | w = ""; 39 | } 40 | else 41 | { 42 | w += ch; 43 | } 44 | } 45 | 46 | return piglatin; 47 | } 48 | 49 | String word_piglatin(String w) 50 | { 51 | int i; 52 | char ch, ch1 = w.charAt(0); 53 | 54 | w.toLowerCase(); 55 | 56 | if(ch1 == 'a' || ch1 == 'e' || ch1 == 'i' || ch1 == 'o' || ch1 == 'u') 57 | { 58 | return w+"hay"; 59 | } 60 | 61 | for(i = 0; i < w.length(); i++) 62 | { 63 | ch = w.charAt(i); 64 | 65 | if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') 66 | break; 67 | } 68 | 69 | return ( w.substring(i) + w.substring(0,i) + "ay"); 70 | } 71 | } 72 | 73 | /* 74 | * Test Cases- 75 | * 76 | * 1. 77 | * Enter a string: 78 | * how are you 79 | * In piglatin: 80 | * owhay arehay ouyay 81 | * 82 | * 2. 83 | * Enter a string: 84 | * i am good 85 | * In piglatin: 86 | * ihay amhay oodgay 87 | * 88 | * Time Complexity: O(n) 89 | * Space Complexity: O(n) 90 | * where n is the number of characters in the string 91 | */ 92 | 93 | 94 | -------------------------------------------------------------------------------- /Queue/readme.md: -------------------------------------------------------------------------------- 1 | # Queue 2 | 3 | A queue is an ordered list in which insertions are done at one end (rear) and 4 | deletions are done at other end (front). The first element to be inserted is the first one to be 5 | deleted. Hence, it is called **First in First out (FIFO) or Last in Last out (LILO) list**. 6 | 7 | Similar to Stacks, special names are given to the two changes that can be made to a queue. When 8 | an element is inserted in a queue, the concept is called **EnQueue**, and when an element is 9 | removed from the queue, the concept is called **DeQueue**. 10 | 11 | **DeQueueing** an empty queue is called **underflow** and **EnQueuing** an element in a full queue is 12 | called **overflow**. Generally, we treat them as exceptions. As an example, consider the snapshot ofthe queue. 13 | 14 | ## Main Queue Operations 15 | 16 | * **EnQueue(int data):** Inserts an element at the end of the queue. 17 | * **DeQueue():** Removes and returns the element at the front of the queue. 18 | 19 | ## Auxiliary Queue Operations 20 | * **Front():** Returns the element at the front without removing it. 21 | * **QueueSize():** Returns the number of elements stored in the queue. 22 | * **IsEmptyQueueQ:** Indicates whether no elements are stored in the queue or not. 23 | 24 | ## Direct Applications 25 | 26 | * Operating systems schedule jobs (with equal priority) in the order of arrival (e.g., a print queue). 27 | * Simulation of real-world queues such as lines at a ticket counter or any other first- 28 | * come first-served scenario requires a queue. 29 | * Multiprogramming. 30 | * Asynchronous data transfer (file IO, pipes, sockets). 31 | * Waiting times of customers at call center. 32 | * Determining number of cashiers to have at a supermarket. 33 | 34 | ## Indirect Applications 35 | 36 | * Auxiliary data structure for algorithms 37 | * Component of other data structures 38 | 39 | ## Questions : 40 | 41 | * Circular Queue Implementation ----> [Java](/Code/Java/CircularQueue.java) | [Python](/Code/Python/circular_queue.py) 42 | * DeQueue using Array ----> [C++](/Code/C++/dequeue_using_array.cpp) 43 | * Implementation of Queue ----> [Python](/Code/Python/queue.py) 44 | * Queue using Circular Linked List ----> [C++](/Code/C++/queue_using_circular_list.cpp) 45 | * Queue using Linkedlist ----> [C++](/Code/c++/Queue_all_operations_using_linkedlist.cpp) 46 | * Queue using Stacks ----> [C++](/Code/C++/queue_using_stacks.cpp) 47 | -------------------------------------------------------------------------------- /Code/Java/matrixop_sub.java.java: -------------------------------------------------------------------------------- 1 | /* 2 | A 2D Array is Used for Matrix, size is taken first then 2 Matrix of that Size is taken 3 | (i,j)th Element of 1st Matrix is subtracted only from (i,j)th Element of 2nd Matrix in Matrix Addition. 4 | */ 5 | 6 | package matrixop; 7 | import java.util.Scanner; 8 | 9 | 10 | public class MatrixOP { 11 | public static void main(String[] args) { 12 | Scanner scan = new Scanner(System.in); 13 | System.out.println("Enter Size of Matrix"); 14 | int l = scan.nextInt(); 15 | int h = scan.nextInt(); 16 | int[][] twoDarr1 = new int[l][h]; 17 | 18 | System.out.println("Enter All Values of 1st Matrix"); 19 | // Taking Input of 1st Matrix 20 | for (int i = 0; i < l; i++) { 21 | for (int j = 0; j < h; j++) { 22 | twoDarr1[i][j] = scan.nextInt(); 23 | } 24 | } 25 | 26 | System.out.println("Enter All Values of 2nd Matrix :"); 27 | int[][] twoDarr2 = new int[l][h]; 28 | // Taking Input of 2nd Matrix 29 | for (int i = 0; i < l; i++) { 30 | for (int j = 0; j < h; j++) { 31 | twoDarr2[i][j] = scan.nextInt(); 32 | } 33 | } 34 | 35 | 36 | // Subtracting Two Matrix 37 | for (int i = 0; i < l; i++) { 38 | for (int j = 0; j < h; j++) { 39 | twoDarr1[i][j] -= twoDarr2[i][j]; 40 | } 41 | } 42 | 43 | 44 | //Printing Matrix after Subtraction 45 | System.out.println("Matrix after subtraction is :"); 46 | for (int i = 0; i < l; i++) { 47 | for (int j = 0; j < h; j++) { 48 | System.out.print(twoDarr1[i][j] + " "); 49 | } 50 | System.out.println(); 51 | } 52 | 53 | } 54 | } 55 | /* 56 | Test Cases: 57 | Input : 2 3 58 | 4 1 8 59 | 9 4 3 60 | 1 2 3 61 | 8 6 7 62 | 63 | Output: 3 -1 5 64 | 1 -2 -4 65 | 66 | 67 | 68 | 69 | Input : 2 2 70 | 4 2 71 | 8 5 72 | 1 6 73 | -1 3 74 | 75 | Output: 3 -4 76 | 9 2 77 | 78 | Time Complexity: O(n^2) where n is the length of matrix 79 | Space Complexity: O(n^2) 80 | */ 81 | -------------------------------------------------------------------------------- /Code/Java/Palindrome_number.java: -------------------------------------------------------------------------------- 1 | /* Check for Palindrome Number 2 | To check whether the number is palindrome or not , 3 | check if the number read backwards is equal to the original number if equal then, 4 | it will be considered to be a palindrome number else it is not a palindrome number. 5 | Algorithm : 6 | Step 1:Get the number to check for palindrome 7 | Step 2: Hold the number in temporary variable (temp) 8 | Step 3: Reverse the number 9 | Step 4: Compare the temporary number with reversed number 10 | Step 5: If both numbers are same, return true 11 | Step 6: Else return false */ 12 | 13 | package palin; 14 | import java.util.*; 15 | class P 16 | { 17 | boolean Palindrome (int n) 18 | { 19 | //for remainder 20 | int rem=0; 21 | int sum=0; 22 | int temp=0; 23 | //assign n to temp 24 | temp=n; 25 | //loop until n is greater than 0 26 | while(n>0){ 27 | //extract the remainder to get the last digit 28 | rem= n % 10; 29 | sum = (sum*10)+rem; 30 | //divide the number by 10 31 | n = n/10; 32 | } 33 | //original number is equal to reversed number 34 | if(sum==temp) { 35 | //true if number is a palindrome 36 | return true; 37 | } 38 | else 39 | { 40 | //false if number is not a palindrome 41 | return false; 42 | } 43 | } 44 | } 45 | public class Palindrome_number { 46 | 47 | public static void main(String[] args) { 48 | Scanner sc = new Scanner(System.in); 49 | boolean result; 50 | int n1=0; 51 | //create object of class P 52 | P pa = new P(); 53 | System.out.println("-------To check whether a number is palindrome or not-------"); 54 | System.out.println("Enter a number: "); 55 | n1 = sc.nextInt(); 56 | System.out.println("Input: "+n1); 57 | result= pa.Palindrome(n1); 58 | System.out.println("Output: "+result); 59 | } 60 | } 61 | /*Test case 1: 62 | -------To check whether a number is palindrome or not------- 63 | Enter a number: 64 | 124 65 | Input: 124 66 | Output: false 67 | 68 | Test case 2: 69 | -------To check whether a number is palindrome or not------- 70 | Enter a number: 71 | 656 72 | Input: 656 73 | Output: true 74 | 75 | Time Complexity: O(log10​(n)) where n is the input number 76 | Because we are dividing the number by 10 in every iteration. 77 | So the time complexity can be said is equal to the number of digits in a number. 78 | Space complexity : O(1) //As Only the number is required to be stored. 79 | */ 80 | 81 | -------------------------------------------------------------------------------- /Code/C++/circle_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement Circle Sort 2 | 3 | #include 4 | using namespace std; 5 | 6 | /* 7 | Performs recursive circular swaps and returns true if atleast one swap occurs 8 | */ 9 | bool rec_sort(int arr[], int beg, int end) 10 | { 11 | bool isSwap = false; 12 | 13 | // If concerned array is empty, Return 14 | if (beg == end) 15 | return false; 16 | 17 | // Storing the values of beg, end to later use in the recursive call 18 | int begA, endA; 19 | for(begA = beg, endA = end; begA < endA; begA++, endA--) 20 | { 21 | //Compares the first and last elements 22 | if (arr[begA] > arr[endA]) 23 | { 24 | swap(arr[begA], arr[endA]); 25 | isSwap = true; 26 | } 27 | 28 | } 29 | 30 | // If the array has odd number of elements 31 | if (begA == endA) 32 | if (arr[begA] > arr[endA + 1]) 33 | { 34 | swap(arr[beg], arr[endA+1]); 35 | isSwap = true; 36 | } 37 | 38 | int mid = (end - beg) / 2; 39 | bool isSwapA = rec_sort(arr, beg, beg+mid); 40 | bool isSwapB = rec_sort(arr, beg+mid+1, end); 41 | 42 | return (isSwap || isSwapA || isSwapB); 43 | } 44 | 45 | void circle_sort(int arr[], int n) 46 | { 47 | while (rec_sort(arr, 0, n-1)) 48 | { 49 | 50 | } 51 | } 52 | 53 | 54 | int main() 55 | { 56 | int n; 57 | cout<<"\nHow many numbers do you want to sort? "; 58 | cin>>n; 59 | int arr[n]; 60 | 61 | if (n <= 0) 62 | { 63 | cout<<"The array is Empty!!!"; 64 | return 0; 65 | } 66 | // Input the numbers to sort 67 | cout<<"Enter the numbers: "; 68 | for (int i = 0; i < n; i++) 69 | cin>>arr[i]; 70 | 71 | //Call the sort function 72 | circle_sort(arr,n); 73 | 74 | cout<<"The numbers in sorted order is: "; 75 | // Print the sorted array 76 | for (int i = 0; i < n; i++) 77 | cout<