├── .all-contributorsrc ├── .vscode ├── launch.json └── tasks.json ├── Algorithms ├── Armstrong number.cpp ├── ArmstrongNumber.py ├── BFS.cpp ├── Bellman Ford.cpp ├── CheckStringPallindrome.cs ├── Dijkstra Algorithm in c# │ ├── DijkstraAllPairsShortestPaths.cs │ └── DijkstraShortestPaths.cs ├── DijkstrasAlgorithm.cpp ├── DijkstrasUsingSetInSTL.cpp ├── Generate_AllPremutations_Backtracking.cpp ├── Kruskal'sAlgorithm.cpp ├── Kruskal-Algo.cpp ├── Numeric │ ├── CatalanNumbers.cs │ ├── GreatestCommonDivisor.cs │ └── reverse-number.rkt ├── Pascal │ ├── PascalTriangle.cpp │ ├── PascalTriangle.java │ ├── PascalTriangle.php │ ├── PascalTriangle_in_C.c │ ├── PascalTriangle_in_JS.js │ ├── PascalTriangleinC#.cs │ ├── PascalsTr.go │ ├── pascal.java │ ├── pascalTriangle.cpp │ ├── pascal_triangle.py │ └── pascals.lua ├── Prim.java ├── SuffixArray.cpp ├── Two Pointer Algorithm ├── armstrong-Number.rkt ├── decimal to binary.cpp ├── dijkstra_algo.cpp ├── dijkstra_algo.py ├── dikshtra.java ├── fenwick_tree.py ├── kadane │ ├── Kadane's Algorithm.cpp │ ├── Kadane.java │ ├── KadaneAlgorithm.cpp │ └── KadanesAlgorithm.py ├── karatsuba_algorithm.py ├── knapsack_zero_one.cpp ├── mo.cpp ├── palindrome_checker.cpp ├── remove_duplicates.py ├── reverse_number.py ├── tower_of_hanoi.c └── tower_of_hanoi.py ├── Arrays ├── 15. Rotate 2D array.cpp ├── 18. Store string in 2D array.cpp ├── maxHourGlass.py └── suffix_array_strings.py ├── Bellman Ford Algo.cpp ├── Best approach for some algorithms ├── fibonacci_number.cpp ├── get_all_factor.cpp ├── power_of_two_no.cpp ├── readme.md └── sum_of_all_subset_of_set.cpp ├── BinarySearch ├── (1)BS.cpp ├── (10)CeilEle.cpp ├── (11)NextAlphabet.cpp ├── (12)BSinfiniteArr.cpp ├── (13)PeakEle.cpp ├── (14)BinaryInfArr.cpp ├── (15)MinDiffEle.cpp ├── (16)SearchBitonicArr.cpp ├── (17)MaxEleBitonicArr.cpp ├── (18)2dSortedArr.cpp ├── (19)AllocateMinPages.cpp ├── (2)RevBS.cpp ├── (20)SqrtUsingBS.cpp ├── (3)OrderAgnostic.cpp ├── (4)1stNlastOccu.cpp ├── (5)CountOccu.cpp ├── (6)CountArrRotations.cpp ├── (7)BSRotatedArr.cpp ├── (8)BSNearlySortedArr.cpp └── (9)FloorEle.cpp ├── Bits and Binary Operations ├── binary _to_decimal.cpp ├── decimal_to_binary.cpp ├── left_shift.cpp └── right_shift.cpp ├── CONTRIBUTING.md ├── DSU ├── DSU.cpp └── DSU.py ├── Dynamic Programming ├── 0-1 Knapsack │ ├── (1)0-1Kp.cpp │ ├── (2)SubsetSum.cpp │ ├── (3)EqualSumPartition.cpp │ ├── (4)CountOfSubetSum.cpp │ ├── (5)MinSubsetSumDiff.cpp │ └── (6)CountOfSubsetDiff.cpp ├── CuttingARod.py ├── LCS │ ├── (1)LCS.cpp │ ├── (2)LCSubstring.cpp │ ├── (3)PrintLCS.cpp │ ├── (4)PrintLCSubstring.cpp │ ├── (5)PrintSCS.cpp │ └── (6)LRepeatingS.cpp ├── MCM │ ├── (1)MCM.cpp │ └── (2)PalindromePartitioning.cpp └── unbounded Knapsack │ ├── (1)UnbKp.cpp │ ├── (2)CoinChange1.cpp │ └── (3)CoinChange2.cpp ├── Graph Traversal Algorithms ├── BFS&DFS.java ├── BFS.cpp ├── DFS.cpp └── DFS.js ├── Heap ├── (1)KthSmallest.cpp ├── (2)KthLargest.cpp ├── (3)KSortedArray.cpp ├── (4)KClosestNo.cpp └── (5)KFrequent.cpp ├── Krusal.java ├── LICENSE ├── Mathematics ├── City Tour Problem ├── Factorial │ └── factorial.rkt ├── GCD │ ├── GCD&LCM_recursion.cpp │ ├── GCD_and_LCM.js │ ├── LcmGcd.java │ ├── Mathematics.cs │ ├── gcd.cpp │ ├── gcd.js │ ├── gcd.py │ ├── lcm_gcd.c │ ├── lcm_gcd.cpp │ └── lcm_gcd.go ├── LCM │ ├── LCM.java │ ├── lcm.js │ └── lcm.py ├── SieveOfEratosthenes.cpp ├── SieveofEratosthenes.java ├── fibonacci │ ├── Fibonacci(c language).c │ ├── Fibonacci.java │ ├── Fibonacci.ml.txt │ ├── FibonacciDynamicProgramming.py │ ├── FibonacciIterative.java │ ├── FibonacciRecursive.java │ ├── FibonacciSequence.c │ ├── Fibonacci_Series.java │ ├── Maitreyi88_fibonacci.py │ ├── fac.c │ ├── fib.rkt │ ├── fibo.c │ ├── fibo.cpp │ ├── fibo.java │ ├── fibo.py │ ├── fibonacci(Cpp).c │ ├── fibonacci(iterative).cpp │ ├── fibonacci.cpp │ ├── fibonacci.go │ ├── fibonacci.js │ ├── fibonacci.py │ ├── fibonacciSeries.java │ ├── fibonacciSeries.js │ ├── fibonacciSeries.py │ ├── fibonacci_recursive.cpp │ ├── fibonacci_recursive.cs │ ├── fibonacci_recursive.py │ └── fibonacci_series.py ├── modulo_exp.cpp └── sieve_of_eratosthenes.py ├── Other Graph Based Algorithms ├── BellmanFordShortestPaths.cs ├── CycleDetection.cpp ├── DijstraSSPS.cpp ├── Kruskal_MST.cpp ├── Prim's.cpp └── TSP.cpp ├── Prims.cpp ├── README.md ├── Recursion ├── (1)Print1_N.cpp ├── (10)PermWSpaces.cpp ├── (11)PermWCases.cpp ├── (12)LetterCasePerm.cpp ├── (13)BalancedParenthesis.cpp ├── (14)Prefix1s_0s.cpp ├── (15)JosephusProblem.cpp ├── (2)SortArray.cpp ├── (3)SortStack.cpp ├── (4)RemoveFromStack.cpp ├── (5)ReverseStack.cpp ├── (6)KthSymbolinGrammer.cpp ├── (7)TOH.cpp ├── (8)PrintSubseq.cpp └── (9)UniqueSubsets.cpp ├── Trie ├── Auto_Complete_using_TRIE.cpp ├── Implement trie (Prefix tree).cpp ├── Trie.cpp └── trie implementation in c++ insert delete search.cpp ├── fibonacci ├── damora_fibonacci.py ├── fibonacci.cs └── fibonacci_recursive.py ├── gcd ├── gcd.java └── gcd.py ├── graphs └── DepthFirstSearcher.cs ├── hashing ├── Hashing.java ├── hashing.cpp ├── hashing.js └── hashing.py ├── kruskal.cpp ├── linked-list ├── LinkedList.java ├── Single_Linked_List.c ├── Singly_Linked_List_as_Circular.c ├── circular-linked-list.c ├── circularLinkedList.js ├── doublyLL.cpp ├── doublyLinkedList.js ├── doubly_linked_list.c ├── linkedList.cpp ├── linkedList.js ├── linked_list.c └── python_linked_list.py ├── pal.py ├── problems ├── Anagram │ ├── CheckTwoStringsAsAnagrams.cpp │ ├── anagram.cpp │ ├── anagram_detection.java │ ├── anagrams.c++ │ ├── check_anagrams.cs │ ├── isAnagram.java │ ├── isAnagram.js │ ├── isAnagram.kt │ ├── isAnagram.py │ └── isAnagram?.rkt ├── FirstDuplicate.cs ├── NQueen.cpp ├── NQueen_Backtracking.cpp ├── ReverseLineWordByWord ├── ToggleStringCharacters.cpp ├── armstrongNumber.js ├── first-duplicate.js ├── firstDuplicate.cpp ├── firstDuplicate.py ├── hourglass.cpp ├── palindrome │ ├── Palindrome.cpp │ ├── PalindromeNum.c │ ├── isIntegerPalindromeWithoutString.cpp │ ├── isPalindrome?.rkt │ ├── palindrome.py │ ├── palindromeInteger.js │ ├── palindrome_checker.py │ └── palindrome_detection.java ├── prime │ ├── isPrime.c │ ├── isPrime.cpp │ ├── isPrime.java │ ├── isPrime.js │ ├── isPrime.kt │ ├── isPrime.py │ └── prime.c ├── reverseNumber │ ├── ReverseAnIntegerWithoutUsingString.cpp │ ├── reverse.py │ ├── reverseNumber.java │ ├── reverseNumber.js │ └── reversenumber.py ├── reverse_list.py └── swap_case.py ├── queue ├── Queue.java ├── Queue_Good_code.cpp ├── circularQueue_using_Array.c ├── circularQueue_using_LinkedList.c ├── dequeue_using_array.c ├── priority_queue_using_array.c ├── queue.cpp ├── queue.js ├── queue_using_array.c └── queue_using_linklist.c ├── searching ├── Binary Search.py ├── Binary_search.c ├── Linear Search.py ├── LinearSearch.java ├── Linear_Search.py ├── binarySearch.cpp ├── binarySearch.js ├── linearSearch.java ├── linear_search.cpp ├── linear_search.go ├── ternarySearch.cpp └── ternary_search.py ├── sorting-algorithms ├── BogoSort.java ├── BogoSort.py ├── BubbleSort.java ├── Counting Sort.py ├── Heap Sort.py ├── MergeSort.cs ├── Quicksort.py ├── RecursiveBubbleSort.cpp ├── RecursiveBubbleSort.java ├── SelectionSort.java ├── bogo_sort.cpp ├── bubbleSort.js ├── bubbleSort.py ├── bubble_sort.c ├── bubble_sort.cpp ├── bubble_sort.py ├── count_sort.py ├── countingsort.cpp ├── heapsort.cpp ├── insertion-sort.js ├── insertionSort.py ├── insertion_sort.cpp ├── insertion_sort_rs.rs ├── mergeSort.java ├── mergeSort.js ├── mergeSort.py ├── mergesort.cpp ├── pancakeSort.cpp ├── pancakeSort.py ├── quick-sort.cpp ├── quicksort.cpp ├── quicksort.hs ├── selection-sort.js ├── selectionSort.cpp ├── selectionSort.py ├── shell_sort.cpp └── shellsort.py ├── stack ├── (1)NGR.cpp ├── (10)MinStackO(1).cpp ├── (2)NGL.cpp ├── (3)NSR.cpp ├── (4)NSL.cpp ├── (5)StockSpan.cpp ├── (6)MAH.cpp ├── (7)MaxBM.cpp ├── (8)RainwaterTrap.cpp ├── (9)MinStackO(n).cpp ├── Stack.java ├── stack.cpp ├── stack.go ├── stack.js ├── stack.py ├── stack_using_LinkedList.c ├── stack_using_LinkedList.py └── stack_using_array.c ├── tree ├── BFS.py ├── BinarySearchTree.py ├── DFS.py ├── RecursiveBinarySearchTree.java ├── avl_tree.java ├── binaryTree.js ├── bst.c ├── fenwicktree.py ├── merge_two_binary_tree_node_sum.cpp └── suffixtree.py └── trie data structure └── trie.cpp /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "g++.exe - Build and debug active file", 9 | "type": "cppdbg", 10 | "request": "launch", 11 | "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", 12 | "args": [], 13 | "stopAtEntry": false, 14 | "cwd": "${workspaceFolder}", 15 | "environment": [], 16 | "externalConsole": false, 17 | "MIMode": "gdb", 18 | "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", 19 | "setupCommands": [ 20 | { 21 | "description": "Enable pretty-printing for gdb", 22 | "text": "-enable-pretty-printing", 23 | "ignoreFailures": true 24 | } 25 | ], 26 | "preLaunchTask": "C/C++: g++.exe build active file" 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "shell", 5 | "label": "C/C++: g++.exe build active file", 6 | "command": "C:\\MinGW\\bin\\g++.exe", 7 | "args": [ 8 | "-g", 9 | "${file}", 10 | "-o", 11 | "${fileDirname}\\${fileBasenameNoExtension}.exe" 12 | ], 13 | "options": { 14 | "cwd": "${workspaceFolder}" 15 | }, 16 | "problemMatcher": [ 17 | "$gcc" 18 | ], 19 | "group": { 20 | "kind": "build", 21 | "isDefault": true 22 | } 23 | } 24 | ], 25 | "version": "2.0.0" 26 | } -------------------------------------------------------------------------------- /Algorithms/Armstrong number.cpp: -------------------------------------------------------------------------------- 1 | //program to check if a number is armstrong number 2 | 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int n,r,sum=0,temp; 8 | cout<<"Enter the Number= "; 9 | cin>>n; 10 | temp=n; 11 | while(n>0) 12 | { 13 | r=n%10; 14 | sum=sum+(r*r*r); 15 | n=n/10; 16 | } 17 | if(temp==sum) 18 | cout<<"Armstrong Number."< 0: 5 | digit = n%10 6 | sum_of_cubes = sum_of_cubes + pow(digit, 3) 7 | n = n//10 8 | 9 | if sum_of_cubes == orig_n: 10 | return "Is an Armstrong Number" 11 | else: 12 | return "Not an Armstrong Number" 13 | 14 | number = int(input()) 15 | result = check_armstrong_num(number) 16 | print(result) 17 | -------------------------------------------------------------------------------- /Algorithms/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std ; 4 | vector vis ; 5 | vector < vector > adj ; 6 | 7 | void BFS(int s) 8 | { 9 | queue q ; 10 | q.push(s) ; 11 | vis[s] = true ; 12 | while (!q.empty()) 13 | { 14 | int f = q.front() ; 15 | q.pop() ; 16 | cout<>n>>e ; 33 | vis.assign(n ,false) ; 34 | adj.assign(n , vector ()) ; 35 | int x , y ; 36 | cout<<"Enter Edges\n" ; 37 | for (int i = 0; i < e; i++) { 38 | cin>>x>>y ; 39 | adj[x].push_back(y) ; 40 | adj[y].push_back(x) ; 41 | } 42 | cout<<"BFS path from source node 0 : " ; 43 | BFS(0) ; 44 | } -------------------------------------------------------------------------------- /Algorithms/CheckStringPallindrome.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Checks if the entered string is a pallindrome or not. 3 | */ 4 | 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | 9 | namespace DSA 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | Dictionary characterPairs = new Dictionary(); 16 | string input = Console.ReadLine(); 17 | 18 | foreach (char c in input) 19 | { 20 | if (characterPairs.ContainsKey(c)) 21 | characterPairs[c]++; 22 | else 23 | characterPairs[c] = 1; 24 | } 25 | 26 | int oddPairs = 0; 27 | foreach (KeyValuePair kvp in characterPairs) 28 | { 29 | 30 | if (characterPairs[kvp.Key] % 2 != 0) 31 | oddPairs++; 32 | } 33 | if (oddPairs > 1) 34 | Console.WriteLine("The string CANNOT be rearranged to a pallindrome"); 35 | else 36 | Console.WriteLine("The string CAN be rearranged to a pallindrome"); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Generate_AllPremutations_Backtracking.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | void solve(int n, vector& A, set& s, vector& curr, vector>& ans) 7 | { 8 | if (curr.size() == n) 9 | { 10 | //cout<<"hi\n"; 11 | ans.push_back(curr); 12 | return ; 13 | } 14 | for (int i = 0; i < n; i++) 15 | { 16 | if (s.find(i) == s.end()) 17 | { 18 | s.insert(i); 19 | curr.push_back(A[i]); 20 | solve(n, A, s, curr, ans); 21 | curr.pop_back(); 22 | s.erase(s.find(i)); 23 | } 24 | } 25 | } 26 | 27 | void permute(vector& A) 28 | { 29 | 30 | vector> ans; 31 | vector curr; 32 | set s; 33 | int n = A.size(); 34 | solve(n, A, s, curr, ans); 35 | cout << ans.size() << "size\n"; 36 | for (int i = 0; i < ans.size(); i++) 37 | { 38 | for (auto x : ans[i]) 39 | { 40 | cout << x << " "; 41 | } 42 | cout << "\n"; 43 | } 44 | } 45 | 46 | int main() 47 | { 48 | 49 | int n; 50 | cin >> n; 51 | vector A(n); 52 | for (int i = 0; i < n; i++) 53 | { 54 | 55 | cin >> A[i]; 56 | } 57 | permute(A); 58 | } 59 | -------------------------------------------------------------------------------- /Algorithms/Numeric/reverse-number.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | ;Build a function that, given a number, reverses it without using strings. 4 | ; 5 | ;input: 12345 6 | ; 7 | ;output: 54321 8 | 9 | ;; number -> number 10 | ;; reverses the given number without using strings 11 | 12 | ;; intution 13 | ;; (= 321 (+ (* 3 (expt 10 2)) (* 2 (expt 10 1)) 1 )) 14 | ;; (= 321 (+ (* (modulo 123 10) (expt 10 2)) (* (modulo 12 10) (expt 10 1)) 1 )) 15 | 16 | ;; code 17 | (define (reverse-number num) 18 | (local [(define (reverse-n n acc) ; using an decerasing accumulator 19 | (cond [(= (order-of-magnitude n) 0) n] ; basecase, used to stop recursion 20 | [else 21 | (+ 22 | (* (modulo n 10) (expt 10 acc)) ; get the right-most digit of n, multiply it with 10^x 23 | (reverse-n (quotient n 10) (sub1 acc)))]))] ; structural recursion with reduced digits, and decreased accumulator 24 | (reverse-n num (order-of-magnitude num)))) ; using inner funtion "reverse-n" to return the reversed number 25 | 26 | 27 | ; test examples 28 | ;(= (reverse-number 9) 9) ; basecase 29 | ;(= (reverse-number 12345) 54321) 30 | ;(= (reverse-number 1234500) 0054321) 31 | 32 | 33 | ;; I got help from this article 34 | ;; https://medium.com/@ManBearPigCode/how-to-reverse-a-number-mathematically-97c556626ec6 35 | -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | // including necessary header files 2 | #include 3 | using namespace std; 4 | 5 | // function to calculate binomial coefficient 6 | int BinCoef(int n, int k) 7 | { 8 | int result = 1; 9 | if (k > n - k) 10 | { 11 | k = n - k; 12 | } 13 | for (int i = 0; i < k; i++) 14 | { 15 | result *= (n - i); 16 | result /= (i + 1); 17 | } 18 | return result; 19 | } 20 | 21 | // function to generate Pascal triangle (of lines n) 22 | void pascal(int n) 23 | { 24 | for (int i = 0; i < n; i++) 25 | { 26 | for (int j = i; j <= n; j++) 27 | { 28 | cout <<" "; 29 | } 30 | for (int j = 0; j <= i; j++) 31 | { 32 | cout << BinCoef(i, j)<<" "; 33 | } 34 | cout << endl; 35 | } 36 | } 37 | 38 | // main function 39 | int main() 40 | { 41 | int rows; 42 | cin >> rows; 43 | pascal(rows); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalTriangle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class PascalTriangle { 4 | 5 | // Function to print first 6 | // n lines of Pascal's Triangle 7 | static void printPascal(int n) 8 | { 9 | 10 | // Iterate through every line 11 | // and print entries in it 12 | for (int line = 0; line < n; line++) 13 | { 14 | // Every line has number of 15 | // integers equal to line number 16 | for (int i = 0; i <= line; i++) 17 | System.out.print(binomialCoeff 18 | (line, i)+" "); 19 | 20 | System.out.println(); 21 | } 22 | } 23 | 24 | 25 | static int binomialCoeff(int n, int k) 26 | { 27 | int res = 1; 28 | 29 | if (k > n - k) 30 | k = n - k; 31 | 32 | for (int i = 0; i < k; ++i) 33 | { 34 | res *= (n - i); 35 | res /= (i + 1); 36 | } 37 | return res; 38 | } 39 | 40 | // Driver code 41 | public static void main(String args[]) 42 | { 43 | int n = 7; 44 | printPascal(n); 45 | } 46 | } 47 | 48 | //This code is contributed by Ehtesham Khursheed 49 | -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalTriangle.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalTriangle_in_C.c: -------------------------------------------------------------------------------- 1 | void printPascal(int n) 2 | { 3 | 4 | int arr[n][n]; 5 | 6 | 7 | for (int line = 0; line < n; line++) 8 | { 9 | 10 | for (int i = 0; i <= line; i++) 11 | { 12 | 13 | if (line == i || i == 0) 14 | arr[line][i] = 1; 15 | 16 | else 17 | arr[line][i] = arr[line-1][i-1] + arr[line-1][i]; 18 | printf("%d ", arr[line][i]); 19 | } 20 | printf("\n"); 21 | } 22 | } 23 | 24 | int main() 25 | { 26 | int n = 5; 27 | printPascal(n); 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalTriangle_in_JS.js: -------------------------------------------------------------------------------- 1 | function generate_new_row(curr_row){ 2 | new_row = [1] 3 | for(let i=0;i<=curr_row.length-2;i++) 4 | new_row.push(curr_row[i] + curr_row[i+1]) 5 | new_row.push(1) 6 | return new_row 7 | } 8 | 9 | function generate_pascal_triangle(num_row){ 10 | let triangle = [[1], [1, 1]] 11 | for(let i=2;i<=num_row-1;i++) 12 | triangle.push(generate_new_row(triangle[triangle.length-1])) 13 | 14 | for(let i=0;i<=num_row-1;i++) 15 | { 16 | for(let j=0;j<=num_row-triangle[i].length+1;j++) 17 | { 18 | process.stdout.write(" "); 19 | } 20 | for(let j=0;j<=triangle[i].length-1;j++) 21 | { 22 | process.stdout.write(""+triangle[i][j]+" "); 23 | } 24 | process.stdout.write("\n"); 25 | } 26 | } 27 | 28 | generate_pascal_triangle(5) -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalTriangleinC#.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | 4 | class GAURAV 5 | { 6 | public static void printPascal(int n) 7 | { 8 | 9 | int[,] arr = new int[n, n]; 10 | 11 | 12 | for (int line = 0; line < n; line++) 13 | { 14 | 15 | for (int i = 0; i <= line; i++) 16 | { 17 | 18 | if (line == i || i == 0) 19 | arr[line, i] = 1; 20 | else 21 | arr[line, i] = arr[line - 1, i - 1] + 22 | arr[line - 1, i]; 23 | Console.Write(arr[line, i]); 24 | } 25 | Console.WriteLine(""); 26 | } 27 | } 28 | 29 | 30 | public static void Main () 31 | { 32 | int n = 5; 33 | printPascal(n); 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Algorithms/Pascal/PascalsTr.go: -------------------------------------------------------------------------------- 1 | //Progra, to print the pascals triangle 2 | 3 | package main 4 | 5 | import "fmt" 6 | 7 | func main() { 8 | var rows int 9 | var temp int = 1 10 | fmt.Print("Enter the number of pascals traingle rows: ") 11 | fmt.Scan(&rows) 12 | 13 | for i := 0; i < rows; i++ { 14 | for j := 1; j <= rows-i; j++ { 15 | fmt.Print(" ") 16 | } 17 | for k := 0; k <= i; k++ { 18 | 19 | if k == 0 || i == 0 { 20 | temp = 1 21 | } else { 22 | temp = temp * (i - k + 1) / k 23 | } 24 | fmt.Printf(" %d", temp) 25 | } 26 | fmt.Println("") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/Pascal/pascal.java: -------------------------------------------------------------------------------- 1 | // Pascal's Triangle 2 | 3 | import java.util.*; 4 | 5 | class pascal { 6 | 7 | // Function to print the triangle... 8 | static void runpascal(int nm) 9 | { 10 | for (int i = 0; i < nm; i++) 11 | { 12 | for (int j = 0; j <= i; j++) 13 | { 14 | System.out.print(bincoff(i, j)+" "); 15 | } 16 | 17 | System.out.println(); 18 | } 19 | } 20 | 21 | //to obtain the factorial 22 | static int fact(int x) 23 | { 24 | int f=1; 25 | for(int i = 1; i <= x; i++) 26 | { 27 | f*=i; 28 | } 29 | return f; 30 | } 31 | 32 | //to get the binomial coefficient 33 | static int bincoff(int a, int b) 34 | { 35 | 36 | if (b > a - b) 37 | { 38 | b = a - b; 39 | } 40 | 41 | 42 | int nume = fact(a); 43 | int deno = fact(b) * fact(a-b); 44 | int r = nume / deno; 45 | return r; 46 | } 47 | 48 | //main function 49 | public static void main(String args[]) 50 | { 51 | Scanner ob = new Scanner(System.in); 52 | int n = ob.nextInt(); 53 | runpascal(n); 54 | } 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /Algorithms/Pascal/pascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | void printPascal(int n) { 7 | for (int line = 1; line <= n; line++) { 8 | // used to represent C(line, i) 9 | int C = 1; 10 | 11 | for (int i = 1; i < (n - line + 1); i++) { 12 | cout << " "; 13 | } 14 | 15 | for (int i = 1; i <= line; i++) { 16 | // The first value in a line is always 1 17 | cout << C << " "; 18 | C = C * (line - i) / i; 19 | } 20 | 21 | cout << "\n"; 22 | } 23 | } 24 | 25 | // Execution 26 | int main() { 27 | int n; 28 | 29 | cout << "Please provide the number of rows of the triangle: "; 30 | 31 | cin >> n; 32 | 33 | printPascal(n); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Pascal/pascal_triangle.py: -------------------------------------------------------------------------------- 1 | # Pascal's Triangle 2 | def printPascalTriangle(n:int): 3 | arr = [[0 for x in range(n)] for y in range(n)] 4 | 5 | for line in range (0, n): 6 | for i in range (0, line + 1): 7 | if(i is 0 or i is line): 8 | arr[line][i] = 1 9 | print(arr[line][i], end = " ") 10 | else: 11 | arr[line][i] = (arr[line - 1][i - 1] + arr[line - 1][i]) 12 | print(arr[line][i], end = " ") 13 | print("", end = "\n") 14 | 15 | # Driver code (Main function) 16 | if __name__ == '__main__': 17 | n = int (input("Enter number of rows: ")) 18 | printPascalTriangle(n) -------------------------------------------------------------------------------- /Algorithms/Pascal/pascals.lua: -------------------------------------------------------------------------------- 1 | -- Problem : To print Pascal's Triangle 2 | 3 | 4 | local n = io.read("*n") 5 | local c 6 | for l = 1,n do 7 | c=1 8 | for x = 1,l do 9 | io.write(c," ") 10 | c=(c*(l-x)/x) 11 | end 12 | io.write("\n") 13 | end 14 | 15 | -------------------------------------------------------------------------------- /Algorithms/SuffixArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct suffix{ 8 | int index; 9 | char *suff; 10 | }; 11 | 12 | int cmp(struct suffix a, struct suffix b) { 13 | return strcmp(a.suff, b.suff) < 0 ? 1: 0; 14 | } 15 | 16 | int *buildSuffixArray(char *txt, int n) { 17 | struct suffix suffixes[n]; 18 | 19 | for(int i = 0;i < n;i++) { 20 | suffixes[i].index = i; 21 | suffixes[i].suff = (txt + i); 22 | } 23 | 24 | sort(suffixes, suffixes + n, cmp); 25 | 26 | int *suffixArr = new int[n]; 27 | for(int i = 0;i < n;i++) { 28 | suffixArr[i] = suffixes[i].index; 29 | } 30 | 31 | return suffixArr; 32 | } 33 | 34 | void printArr(int arr[], int n) { 35 | for(int i = 0;i < n;i++) { 36 | cout << arr[i] << " "; 37 | } 38 | cout << endl; 39 | } 40 | 41 | int main() { 42 | char txt[] = "banana"; 43 | int n = strlen(txt); 44 | int *suffixArr = buildSuffixArray(txt, n); 45 | cout << "Following is suffix array for " << txt << endl; 46 | printArr(suffixArr, n); 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Algorithms/Two Pointer Algorithm: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class TwoPointerAlgo { 4 | 5 | public static void main(String[] args) { 6 | int arr[] = {0,-1,3,-4,5,-3,4,1}; 7 | 8 | int n = arr.length; 9 | int x=0,k=0,j=n-1; 10 | 11 | Arrays.sort(arr); //Sorting is necessary 12 | 13 | for(int i=0;i x) { 22 | j--; 23 | }else { 24 | System.out.println(arr[i] + " "+ arr[k]+" "+arr[j]); 25 | k++; 26 | j--; 27 | } 28 | } 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/decimal to binary.cpp: -------------------------------------------------------------------------------- 1 | //program for decimal to binary conversion 2 | 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int a[10], n, i; 8 | cout<<"Enter the number to convert: "; 9 | cin>>n; 10 | for(i=0; n>0; i++) 11 | { 12 | a[i]=n%2; 13 | n= n/2; 14 | } 15 | cout<<"Binary of the given number= "; 16 | for(i=i-1 ;i>=0 ;i--) 17 | { 18 | cout< 0: 20 | sum += fTree[index] 21 | index -= index & (-index) 22 | return sum 23 | 24 | 25 | def main(): 26 | n = int(input('Enter the number of elements: ')) 27 | arr = [int(x) for x in input('Enter the elements of array: '.format(n)).split()] 28 | fTree = construct_fTree(arr,len(arr)) 29 | prefix=int(input('Enter the index for which you need prefix sum')) 30 | print(getSum(prefix,fTree)) 31 | i,v=(input('Enter the index and its new value: ').split()) 32 | i=int(i) 33 | v=int(v) 34 | updateFTree(i,v,fTree,n) 35 | prefix=int(input('Enter the index for which you need prefix sum')) 36 | print(getSum(prefix,fTree)) 37 | if __name__ == '__main__': 38 | main() -------------------------------------------------------------------------------- /Algorithms/kadane/Kadane's Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxSubArraySum(int a[], int size) 6 | { 7 | int max_so_far = INT_MIN, max_ending_here = 0; 8 | 9 | for (int i = 0; i < size; i++) 10 | { 11 | max_ending_here = max_ending_here + a[i]; 12 | if (max_so_far < max_ending_here) 13 | max_so_far = max_ending_here; 14 | 15 | if (max_ending_here < 0) 16 | max_ending_here = 0; 17 | } 18 | return max_so_far; 19 | } 20 | 21 | int main() 22 | { 23 | int a[] = {1,4,7,9,0,4,5}; 24 | int n = sizeof(a)/sizeof(a[0]); 25 | int max_sum = maxSubArraySum(a, n); 26 | cout << "Subarray with maximum sum is " << max_sum; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/kadane/Kadane.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | class Kadane 6 | { 7 | public static void main (String[] args) 8 | { 9 | int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; 10 | System.out.println("Maximum contiguous sum is " + 11 | maxSubArraySum(a)); 12 | } 13 | 14 | static int maxSubArraySum(int a[]) 15 | { 16 | int size = a.length; 17 | int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; 18 | 19 | for (int i = 0; i < size; i++) 20 | { 21 | max_ending_here = max_ending_here + a[i]; 22 | if (max_so_far < max_ending_here) 23 | max_so_far = max_ending_here; 24 | if (max_ending_here < 0) 25 | max_ending_here = 0; 26 | } 27 | return max_so_far; 28 | } 29 | } 30 | //This code is contributed by Ehtesham Khursheed 31 | -------------------------------------------------------------------------------- /Algorithms/kadane/KadaneAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | class Kadane{ 7 | public: 8 | int max_sum(int p[],int n){ 9 | int max_sum=p[0],max_in=p[0]; 10 | for(int i=1;i>n; 32 | int p[n]; 33 | for (int i=0;i>p[i]; 36 | } 37 | algo.display(p,n); 38 | int a = algo.max_sum(p,n); 39 | cout<<"\n Largest sum of subarray using kadane algorithm is "< 2 | #include 3 | using namespace std; 4 | 5 | bool canBePalindrome(map m) { 6 | int oddOccurrence = 0; 7 | for (auto itr = m.begin(); itr != m.end(); itr++) { 8 | if (itr->second % 2) oddOccurrence += 1; 9 | if (oddOccurrence > 1) return false; 10 | } 11 | return true; 12 | } 13 | 14 | int main() { 15 | string input; 16 | cin >> input; 17 | map occurrenceCount; 18 | for (char c: input) { 19 | occurrenceCount[c] += 1; 20 | } 21 | cout << canBePalindrome(occurrenceCount) << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | def remove_duplicates(items): 2 | unique_items = [] 3 | for i in items: 4 | if i not in unique_items: 5 | unique_items.append(i) 6 | return unique_items 7 | 8 | 9 | if __name__ == '__main__': 10 | items = [3, 1, 1, 1, 3, 2, 2, 7, 3, 4, 5, 7, 5, 6, 7, 8, 9, 10] 11 | expected = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 12 | unique_items = sorted(remove_duplicates(items)) 13 | 14 | assert expected == unique_items 15 | -------------------------------------------------------------------------------- /Algorithms/reverse_number.py: -------------------------------------------------------------------------------- 1 | # Python program to reverse a number 2 | 3 | rev_num = 0 4 | base_pos = 1 5 | 6 | # Recursive function to reverse 7 | 8 | def reversDigits(num): 9 | global rev_num 10 | global base_pos 11 | if(num > 0): 12 | reversDigits((int)(num / 10)) 13 | rev_num += (num % 10) * base_pos 14 | base_pos *= 10 15 | return rev_num 16 | 17 | 18 | num = 2468 19 | print("Reverse of no. is ", 20 | reversDigits(num)) 21 | 22 | # This code is contributed by b.harizi 23 | -------------------------------------------------------------------------------- /Algorithms/tower_of_hanoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Function for Tower of Hanoi algorithm 5 | void hanoi(int noOfDisks,char where,char to,char extra){ 6 | if(noOfDisks == 0 ) 7 | { 8 | return; 9 | } 10 | else 11 | { 12 | hanoi(noOfDisks-1, where, extra , to); 13 | printf("Move disk : %d from %c to %c\n",noOfDisks,where,to); 14 | hanoi(noOfDisks-1,extra,to,where); 15 | } 16 | } 17 | int main(void){ 18 | int noOfDisks; 19 | 20 | //Asks the number of disks in the tower 21 | printf("Number of disks: \n"); 22 | scanf("%d", &noOfDisks); 23 | 24 | hanoi(noOfDisks,'A','B','C'); 25 | 26 | return 0; 27 | 28 | } -------------------------------------------------------------------------------- /Algorithms/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | def towerOfHanoi(n, where, to, extra): 2 | if n == 0: 3 | return 4 | else: 5 | towerOfHanoi(n-1, where, extra, to) 6 | print("Move disk :", n, "from", where, "to", to) 7 | towerOfHanoi(n-1, extra, to, where) 8 | 9 | n = int(input("number of Disks : ")) 10 | 11 | print("Process of moving all disks form A to C is -") 12 | 13 | towerOfHanoi(n, "A", "B", "C") -------------------------------------------------------------------------------- /Arrays/18. Store string in 2D array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char a[100][1000]; 7 | int n; 8 | cin>>n; 9 | 10 | cin.get(); //to get the extra enter followed after n 11 | 12 | for(int i=0;i 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | typedef long long ll ; 13 | typedef vector vi; 14 | typedef vector> vpi; 15 | typedef vector vl; 16 | typedef vector> vpl; 17 | typedef vector vs; 18 | typedef set ss; 19 | typedef set si; 20 | typedef set sl; 21 | typedef set> spi; 22 | typedef set> spl; 23 | // macros 24 | #define pan cin.tie(0);cout.tie(0);ios_base::sync_with_stdio(0); 25 | #define mod 1000000007; 26 | #define phi 1.618 27 | #define line cout<>a; 37 | cout<<"List of all factor of "< 2 | using namespace std; 3 | 4 | // search in monotonic space 5 | 6 | int binarySearch(int a[], int n, int x) { 7 | 8 | int s = 0; 9 | int e = n - 1; 10 | 11 | while (s <= e) { 12 | 13 | int mid = s + (e - s) / 2; 14 | 15 | if (a[mid] == x) return mid; 16 | else if (a[mid] > x) e = mid - 1; 17 | else if (a[mid] < x) s = mid + 1; 18 | } 19 | 20 | return -1; 21 | 22 | } 23 | 24 | int main() { 25 | 26 | #ifndef ONLINE_JUDGE 27 | freopen("input.txt", "r", stdin); 28 | freopen("output.txt", "w", stdout); 29 | #endif 30 | 31 | 32 | int n; 33 | cin >> n; 34 | int a[n]; 35 | int x; cin >> x; 36 | for (int i = 0; i < n; i++) cin >> a[i]; 37 | 38 | cout << binarySearch(a, n, x) << endl; 39 | 40 | } 41 | -------------------------------------------------------------------------------- /BinarySearch/(10)CeilEle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // find ceil of an element in a sorted array 5 | // ceil of x = smallest element greater than x 6 | 7 | int BinarySearch(int a[], int x, int s, int e) { 8 | 9 | int res = -1; 10 | while (s <= e) { 11 | 12 | int mid = s + (e - s) / 2; 13 | 14 | if (a[mid] == x) return a[mid]; 15 | 16 | if (a[mid] < x) { 17 | s = mid + 1; 18 | } 19 | 20 | else if (a[mid] > x) { 21 | res = a[mid]; 22 | e = mid - 1; 23 | } 24 | 25 | } 26 | return res; 27 | } 28 | 29 | int main() { 30 | 31 | #ifndef ONLINE_JUDGE 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | #endif 35 | 36 | 37 | int n, x; 38 | cin >> n >> x; 39 | int arr[n]; 40 | for (int i = 0; i < n; i++) cin >> arr[i]; 41 | 42 | cout << BinarySearch(arr, x, 0, n - 1) << endl; 43 | 44 | } 45 | -------------------------------------------------------------------------------- /BinarySearch/(11)NextAlphabet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Next Alphabet (kindof ceil in terms of ascii) 5 | 6 | char BinarySearch(char a[], int x, int s, int e) { 7 | 8 | char res = '#'; 9 | while (s <= e) { 10 | 11 | int mid = s + (e - s) / 2; 12 | 13 | if (a[mid] == x) return a[mid]; // or a[mid+1] for next element 14 | 15 | if (a[mid] < x) { 16 | s = mid + 1; 17 | } 18 | 19 | else if (a[mid] > x) { 20 | res = a[mid]; 21 | e = mid - 1; 22 | } 23 | 24 | } 25 | return res; 26 | } 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | 36 | int n; 37 | char x; 38 | cin >> n >> x; 39 | char arr[n]; 40 | for (int i = 0; i < n; i++) cin >> arr[i]; 41 | 42 | cout << BinarySearch(arr, x, 0, n - 1) << endl; 43 | 44 | } 45 | -------------------------------------------------------------------------------- /BinarySearch/(12)BSinfiniteArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // position of an element in an infinite sorted array 5 | 6 | int BinarySearch(int a[], int x, int s, int e) { 7 | 8 | while (s <= e) { 9 | int mid = s + (e - s) / 2; 10 | 11 | if (a[mid] == x) return mid; 12 | 13 | else if (a[mid] > x) e = mid - 1; 14 | else if (a[mid] < x) s = mid + 1; 15 | } 16 | return -1; 17 | } 18 | 19 | int main() { 20 | 21 | #ifndef ONLINE_JUDGE 22 | freopen("input.txt", "r", stdin); 23 | freopen("output.txt", "w", stdout); 24 | #endif 25 | 26 | 27 | int n; 28 | int x; 29 | cin >> n >> x; 30 | int arr[n]; 31 | for (int i = 0; i < n; i++) cin >> arr[i]; 32 | 33 | int s = 0, e = 1; 34 | while (x > arr[e]) { 35 | s = e; 36 | e = e * 2; 37 | } 38 | 39 | cout << BinarySearch(arr, x, s, e) << endl; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /BinarySearch/(13)PeakEle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Binary Search on answer [ unsorted array kind of things but monotonic] 5 | // Peak Element 6 | 7 | int BinarySearch(int a[], int n, int s, int e) { 8 | 9 | while (s <= e) { 10 | 11 | int mid = s + (e - s) / 2; 12 | int prev = (mid - 1 + n) % n; 13 | int next = (mid + 1) % n; 14 | 15 | if (mid > 0 && mid < n - 1) { 16 | 17 | if (a[mid] > a[prev] && a[mid] > a[next]) { 18 | return mid; 19 | } 20 | 21 | if (a[mid] < a[mid + 1] ) s = mid + 1; 22 | else if (a[mid] > a[mid + 1]) e = mid - 1; 23 | } 24 | 25 | else if (mid == 0) { 26 | if (a[mid] > a[mid + 1]) return 0; 27 | else return 0; 28 | } 29 | 30 | else if (mid == n - 1) { 31 | if (a[mid] > a[mid - 1]) return mid; 32 | else return mid - 1; 33 | } 34 | 35 | } 36 | } 37 | 38 | int main() { 39 | 40 | #ifndef ONLINE_JUDGE 41 | freopen("input.txt", "r", stdin); 42 | freopen("output.txt", "w", stdout); 43 | #endif 44 | 45 | 46 | int n; 47 | cin >> n; 48 | int arr[n]; 49 | for (int i = 0; i < n; i++) cin >> arr[i]; 50 | 51 | cout << BinarySearch(arr, n, 0, n - 1) << endl; // index 52 | 53 | } 54 | -------------------------------------------------------------------------------- /BinarySearch/(14)BinaryInfArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // First occurance of 1 in binary sorted array [0000...1111...] 5 | 6 | int BinarySearch(int a[], int n, int s, int e) { 7 | 8 | int res = -1; 9 | while (s <= e) { 10 | 11 | int mid = s + (e - s) / 2; 12 | 13 | if (a[mid] == 1) { 14 | res = mid; 15 | e = mid - 1; 16 | } 17 | 18 | if (a[mid] < 1 ) s = mid + 1; 19 | else if (a[mid] > 1) e = mid - 1; 20 | } 21 | return res; 22 | } 23 | 24 | int main() { 25 | 26 | #ifndef ONLINE_JUDGE 27 | freopen("input.txt", "r", stdin); 28 | freopen("output.txt", "w", stdout); 29 | #endif 30 | 31 | 32 | int n; 33 | cin >> n; 34 | int arr[n]; 35 | for (int i = 0; i < n; i++) cin >> arr[i]; 36 | 37 | int s = 0, e = 1; 38 | 39 | while (1 > arr[e]) { 40 | s = e; 41 | e = e * 2; 42 | } 43 | 44 | cout << BinarySearch(arr, n, s, e) << endl; // index 45 | 46 | } 47 | -------------------------------------------------------------------------------- /BinarySearch/(15)MinDiffEle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // if key present return key 5 | // else return minimum absolute difference element from x in a sorted array 6 | 7 | // Concept:- When element is not present , binary search ends with s,e as neighbours of key 8 | 9 | int BinarySearch(int a[], int n, int x) { 10 | 11 | int s = 0; 12 | int e = n - 1; 13 | 14 | while (s <= e) { 15 | 16 | int mid = s + (e - s) / 2; 17 | 18 | if (a[mid] == x) { 19 | return a[mid]; 20 | } 21 | 22 | if (a[mid] < x ) s = mid + 1; 23 | else if (a[mid] > x) e = mid - 1; 24 | } 25 | 26 | return (abs(a[s] - x) > abs(a[e] - x)) ? a[e] : a[s]; 27 | 28 | } 29 | 30 | int main() { 31 | 32 | #ifndef ONLINE_JUDGE 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | #endif 36 | 37 | 38 | int n, x; 39 | cin >> n >> x; 40 | int arr[n]; 41 | for (int i = 0; i < n; i++) cin >> arr[i]; 42 | 43 | cout << BinarySearch(arr, n, x) << endl; 44 | 45 | } 46 | -------------------------------------------------------------------------------- /BinarySearch/(17)MaxEleBitonicArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Max element in bitonic array [inc-peak-dec] 5 | 6 | int Peak(int a[], int n) { 7 | 8 | int s = 0; 9 | int e = n - 1; 10 | 11 | while (s <= e) { 12 | 13 | int mid = s + (e - s) / 2; 14 | int prev = (mid - 1 + n) % n; 15 | int next = (mid + 1) % n; 16 | 17 | if (a[mid] > a[prev] && a[mid] > a[next]) return mid; 18 | else if (a[mid] < a[mid + 1]) s = mid + 1; 19 | else if (a[mid] > a[mid + 1]) e = mid - 1; 20 | } 21 | } 22 | 23 | int main() { 24 | 25 | #ifndef ONLINE_JUDGE 26 | freopen("input.txt", "r", stdin); 27 | freopen("output.txt", "w", stdout); 28 | #endif 29 | 30 | 31 | int n; 32 | cin >> n; 33 | int arr[n]; 34 | for (int i = 0; i < n; i++) cin >> arr[i]; 35 | 36 | cout << arr[Peak(arr, n)]; 37 | } 38 | -------------------------------------------------------------------------------- /BinarySearch/(18)2dSortedArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Search in row-wise and col-wise sorted 2D array 5 | 6 | int main() { 7 | 8 | #ifndef ONLINE_JUDGE 9 | freopen("input.txt", "r", stdin); 10 | freopen("output.txt", "w", stdout); 11 | #endif 12 | 13 | int n, m, x; 14 | cin >> n >> m >> x; 15 | int a[n][m]; 16 | 17 | for (int i = 0; i < n; i++) { 18 | for (int j = 0; j < m; j++) { 19 | cin >> a[i][j]; 20 | } 21 | } 22 | 23 | int s = 0, e = m - 1; 24 | int flag = 0; 25 | 26 | while (s >= 0 && s < n && e >= 0 && e < n) { 27 | 28 | int mid = a[s][e]; 29 | 30 | if (mid == x) { 31 | cout << "found at " << "(" << s << "," << e << ")" << endl; 32 | flag = 1; 33 | break; 34 | } 35 | 36 | else if (mid < x) { 37 | s = s + 1; 38 | } 39 | else if (mid > x) { 40 | e = e - 1; 41 | } 42 | } 43 | 44 | if (!flag) cout << "Not found" << endl; 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /BinarySearch/(19)AllocateMinPages.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Allocate minimum number of pages 5 | 6 | bool isValid(int a[], int n, int k, int mid) { 7 | 8 | int student = 1; 9 | int sum = 0; 10 | 11 | for (int i = 0; i < n; i++) { 12 | 13 | sum += a[i]; 14 | if (sum > mid) { 15 | student ++; 16 | sum = a[i]; 17 | } 18 | } 19 | 20 | if (student > k) return false; 21 | return true; 22 | } 23 | 24 | int main() { 25 | 26 | #ifndef ONLINE_JUDGE 27 | freopen("input.txt", "r", stdin); 28 | freopen("output.txt", "w", stdout); 29 | #endif 30 | 31 | int n, k; 32 | cin >> n >> k; 33 | int a[n]; 34 | 35 | int sum = 0 ; 36 | int mx = INT_MIN; 37 | for (int i = 0; i < n; i++) { 38 | cin >> a[i]; 39 | sum += a[i]; 40 | mx = max(mx, a[i]); 41 | } 42 | 43 | int s = mx; 44 | int e = sum; 45 | int res = -1; 46 | 47 | while (s <= e) { 48 | 49 | int mid = s + (e - s) / 2; 50 | 51 | if (isValid(a, n, k, mid) == true) { 52 | res = mid; 53 | e = mid - 1; 54 | } 55 | else s = mid + 1; 56 | } 57 | 58 | cout << res << endl; 59 | 60 | } 61 | -------------------------------------------------------------------------------- /BinarySearch/(2)RevBS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int a[], int n, int x) { 5 | 6 | int s = 0; 7 | int e = n - 1; 8 | 9 | while (s <= e) { 10 | 11 | int mid = s + (e - s) / 2; 12 | 13 | if (a[mid] == x) return mid; 14 | else if (a[mid] > x) s = mid + 1; 15 | else if (a[mid] < x) e = mid - 1; 16 | } 17 | 18 | return -1; 19 | 20 | } 21 | 22 | int main() { 23 | 24 | #ifndef ONLINE_JUDGE 25 | freopen("input.txt", "r", stdin); 26 | freopen("output.txt", "w", stdout); 27 | #endif 28 | 29 | 30 | int n; 31 | cin >> n; 32 | int a[n]; 33 | int x; cin >> x; 34 | for (int i = 0; i < n; i++) cin >> a[i]; //reverse sorted array 35 | 36 | cout << binarySearch(a, n, x) << endl; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /BinarySearch/(20)SqrtUsingBS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Finding square of a number with precesion 5 | // Coding blocks 6 | 7 | float FindSqrt(int n, int p) { 8 | 9 | int int_part = 0; 10 | int s = 0, e = n; 11 | 12 | while (s <= e) { 13 | 14 | int mid = s + (e - s) / 2; 15 | 16 | if (mid * mid <= n) { 17 | int_part = mid; 18 | s = mid + 1; 19 | } 20 | else if (mid * mid > n) { 21 | e = mid - 1; 22 | } 23 | } 24 | 25 | // return int_part; 26 | 27 | float frac_part = 0; 28 | float inc = 0.1; 29 | float ans = int_part; 30 | 31 | for (int i = 0; i < p; i++) { 32 | 33 | while (ans * ans <= n) { 34 | ans += inc; 35 | } 36 | ans = ans - inc; 37 | inc = inc / 10; 38 | } 39 | 40 | return ans; 41 | } 42 | 43 | int main() { 44 | 45 | #ifndef ONLINE_JUDGE 46 | freopen("input.txt", "r", stdin); 47 | freopen("output.txt", "w", stdout); 48 | #endif 49 | 50 | int n, p; 51 | cin >> n >> p; 52 | 53 | cout << FindSqrt(n, p) << endl; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /BinarySearch/(3)OrderAgnostic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //order agnostic search 5 | // array can be asc/desc sorted 6 | 7 | int binarySearch(int a[], int n, int x, bool rev) { 8 | 9 | int s = 0; 10 | int e = n - 1; 11 | 12 | while (s <= e) { 13 | 14 | int mid = s + (e - s) / 2; 15 | 16 | if (a[mid] == x) return mid; 17 | else if (a[mid] > x && rev == true) s = mid + 1; 18 | else if (a[mid] > x && rev == false) e = mid - 1; 19 | else if (a[mid] < x && rev == true) e = mid - 1; 20 | else if (a[mid] < x && rev == false) s = mid + 1; 21 | 22 | } 23 | 24 | return -1; 25 | 26 | } 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | 36 | int n; 37 | cin >> n; 38 | int a[n]; 39 | int x; cin >> x; 40 | for (int i = 0; i < n; i++) cin >> a[i]; 41 | 42 | if (a[0] > a[1]) cout << binarySearch(a, n, x, true) << endl; 43 | else cout << binarySearch(a, n, x, false) << endl; 44 | 45 | } 46 | -------------------------------------------------------------------------------- /BinarySearch/(4)1stNlastOccu.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // first and last occurance of an element 5 | 6 | int BS_1st(int a[], int n, int x) { 7 | 8 | int s = 0; 9 | int e = n - 1; 10 | int res = -1; 11 | 12 | while (s <= e) { 13 | 14 | int mid = s + (e - s) / 2; 15 | 16 | if (a[mid] == x) { // first occurance 17 | res = mid; 18 | e = mid - 1; 19 | } 20 | else if (a[mid] > x) e = mid - 1; 21 | else if (a[mid] < x) s = mid + 1; 22 | 23 | } 24 | return res; 25 | } 26 | 27 | int BS_last(int a[], int n, int x) { 28 | 29 | int s = 0; 30 | int e = n - 1; 31 | int res = -1; 32 | 33 | while (s <= e) { 34 | 35 | int mid = s + (e - s) / 2; 36 | 37 | if (a[mid] == x) { // last occurance 38 | res = mid; 39 | s = mid + 1; 40 | } 41 | else if (a[mid] > x) e = mid - 1; 42 | else if (a[mid] < x) s = mid + 1; 43 | 44 | } 45 | return res; 46 | } 47 | 48 | 49 | int main() { 50 | 51 | #ifndef ONLINE_JUDGE 52 | freopen("input.txt", "r", stdin); 53 | freopen("output.txt", "w", stdout); 54 | #endif 55 | 56 | 57 | int n; 58 | cin >> n; 59 | int a[n]; 60 | int x; cin >> x; 61 | for (int i = 0; i < n; i++) cin >> a[i]; 62 | 63 | cout << BS_1st(a, n, x) << " " << BS_last(a, n, x) << endl; 64 | 65 | } 66 | -------------------------------------------------------------------------------- /BinarySearch/(5)CountOccu.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // count of element in sorted array = simply first occ - last occ index + 1 5 | 6 | int BS_1st(int a[], int n, int x) { 7 | 8 | int s = 0; 9 | int e = n - 1; 10 | int res = -1; 11 | 12 | while (s <= e) { 13 | 14 | int mid = s + (e - s) / 2; 15 | 16 | if (a[mid] == x) { // first occurance 17 | res = mid; 18 | e = mid - 1; 19 | } 20 | else if (a[mid] > x) e = mid - 1; 21 | else if (a[mid] < x) s = mid + 1; 22 | 23 | } 24 | return res; 25 | } 26 | 27 | int BS_last(int a[], int n, int x) { 28 | 29 | int s = 0; 30 | int e = n - 1; 31 | int res = -1; 32 | 33 | while (s <= e) { 34 | 35 | int mid = s + (e - s) / 2; 36 | 37 | if (a[mid] == x) { // last occurance 38 | res = mid; 39 | s = mid + 1; 40 | } 41 | else if (a[mid] > x) e = mid - 1; 42 | else if (a[mid] < x) s = mid + 1; 43 | 44 | } 45 | return res; 46 | } 47 | 48 | 49 | int main() { 50 | 51 | #ifndef ONLINE_JUDGE 52 | freopen("input.txt", "r", stdin); 53 | freopen("output.txt", "w", stdout); 54 | #endif 55 | 56 | 57 | int n; 58 | cin >> n; 59 | int a[n]; 60 | int x; cin >> x; 61 | for (int i = 0; i < n; i++) cin >> a[i]; 62 | 63 | if ((BS_last(a, n, x) - BS_1st(a, n, x) + 1) == 1) cout << "-1" << endl; 64 | else cout << (BS_last(a, n, x) - BS_1st(a, n, x) + 1) << endl; 65 | 66 | } 67 | -------------------------------------------------------------------------------- /BinarySearch/(6)CountArrRotations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Number of times a sorted array is rotated = index of minimum/a[0] element 5 | 6 | int CountRotations(int a[], int n) { 7 | 8 | int s = 0; 9 | int e = n - 1; 10 | 11 | while (s <= e) { 12 | 13 | int mid = s + (e - s) / 2; 14 | int next = (mid + 1) % n; 15 | int prev = (mid - 1 + n) % n; 16 | 17 | if ((a[mid] <= a[next]) && (a[mid] <= a[prev])) { 18 | return mid; 19 | } 20 | 21 | else if (a[mid] > a[mid + 1]) s = mid + 1; 22 | else if (a[mid] < a[mid + 1]) e = mid - 1; 23 | 24 | // else if (a[s] <= a[mid]) s = mid + 1; // array is sorted , search in unsorted part 25 | // else if (a[mid] <= a[e]) e = mid - 1; // array is sorted , search in unsorted part 26 | 27 | } 28 | } 29 | 30 | 31 | int main() { 32 | 33 | #ifndef ONLINE_JUDGE 34 | freopen("input.txt", "r", stdin); 35 | freopen("output.txt", "w", stdout); 36 | #endif 37 | 38 | 39 | int n; 40 | cin >> n; 41 | int a[n]; 42 | for (int i = 0; i < n; i++) cin >> a[i]; // rotated sorted array 43 | 44 | cout << CountRotations(a, n) << endl; 45 | } 46 | -------------------------------------------------------------------------------- /BinarySearch/(8)BSNearlySortedArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // find an element in nearly soretd array 5 | // Element that will be present at ith index in sorted array can be at [i-1 , i, i+1]th index 6 | 7 | int BinarySearch(int a[], int x, int s, int e) { 8 | 9 | while (s <= e) { 10 | 11 | int mid = s + (e - s) / 2; 12 | 13 | if (a[mid] == x) return mid; 14 | if (a[mid - 1] == x && (mid - 1) >= s) return mid - 1; 15 | if (a[mid + 1] == x && (mid + 1) <= e) return mid + 1; 16 | 17 | else if (a[mid] > x) e = mid - 2; 18 | else if (a[mid] < x) s = mid + 2; 19 | } 20 | return -1; 21 | } 22 | 23 | int main() { 24 | 25 | #ifndef ONLINE_JUDGE 26 | freopen("input.txt", "r", stdin); 27 | freopen("output.txt", "w", stdout); 28 | #endif 29 | 30 | 31 | int n, x; 32 | cin >> n >> x; 33 | int arr[n]; 34 | for (int i = 0; i < n; i++) cin >> arr[i]; // nearly sorted array 35 | 36 | cout << BinarySearch(arr, x, 0, n - 1) << endl; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /BinarySearch/(9)FloorEle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // find floor of an element in a sorted array 5 | // floor of x = greatest element smaller than x 6 | 7 | int BinarySearch(int a[], int x, int s, int e) { 8 | 9 | int res = -1; 10 | while (s <= e) { 11 | 12 | int mid = s + (e - s) / 2; 13 | 14 | if (a[mid] == x) return a[mid]; 15 | 16 | if (a[mid] < x) { 17 | res = a[mid]; 18 | s = mid + 1; 19 | } 20 | 21 | else if (a[mid] > x) { 22 | e = mid - 1; 23 | } 24 | 25 | } 26 | return res; 27 | } 28 | 29 | int main() { 30 | 31 | #ifndef ONLINE_JUDGE 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | #endif 35 | 36 | 37 | int n, x; 38 | cin >> n >> x; 39 | int arr[n]; 40 | for (int i = 0; i < n; i++) cin >> arr[i]; 41 | 42 | cout< 2 | #include 3 | using std::vector; 4 | using namespace std; 5 | 6 | // takes in a c++ vector of ones and zeroes and returns a decimal equivalent 7 | int binaryToDecimal(vector number) 8 | { 9 | int num = 0; 10 | reverse(number.begin(), number.end()); 11 | for (int i = 0; i < number.size(); i++) 12 | { 13 | num += number[i] * pow(2, i); 14 | } 15 | return num; 16 | } 17 | 18 | int main(void) 19 | { 20 | vector binary_number = {1, 0, 1, 0, 0, 0, 1}; 21 | int decimal_number = binaryToDecimal(binary_number); 22 | cout << decimal_number; 23 | } -------------------------------------------------------------------------------- /Bits and Binary Operations/decimal_to_binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::vector; 4 | using namespace std; 5 | 6 | //a program that takes a natural number and returns its binary equivalent in a vector 7 | vector decimalToBinary(int num) 8 | { 9 | vector number; 10 | if (num == 1) 11 | { 12 | number.push_back(num); 13 | } 14 | while (num != 1) 15 | { 16 | number.push_back(num % 2); 17 | num = num / 2; 18 | if (num == 1) 19 | { 20 | number.push_back(num); 21 | } 22 | } 23 | reverse(number.begin(), number.end()); 24 | return number; 25 | } 26 | 27 | int main(void) 28 | { 29 | int decimal_number = 81; 30 | vector binary_number = decimalToBinary(decimal_number); 31 | for (int i = 0; i < binary_number.size(); i++) 32 | { 33 | cout << binary_number[i]; 34 | } 35 | } -------------------------------------------------------------------------------- /Bits and Binary Operations/left_shift.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::vector; 4 | using namespace std; 5 | 6 | //takes a cpp vector of ones and zeroes and performs a left shift on it 7 | vector leftShift(vector number) 8 | { 9 | vector new_Number = number; 10 | for (int i = number.size() - 1; i > 0; i--) 11 | { 12 | new_Number[i - 1] = number[i]; 13 | } 14 | new_Number[number.size() - 1] = 0; 15 | return new_Number; 16 | } 17 | 18 | int main(void) 19 | { 20 | vector binary_number = {1, 0, 1, 0, 0, 0, 1}; 21 | vector left_shifted_number = leftShift(binary_number); 22 | for (int i = 0; i < left_shifted_number.size(); i++) 23 | { 24 | cout << left_shifted_number[i]; 25 | } 26 | } -------------------------------------------------------------------------------- /Bits and Binary Operations/right_shift.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::vector; 4 | using namespace std; 5 | 6 | //takes a cpp vector of ones and zeroes and performs a right shift on it 7 | 8 | vector rightShift(vector number) 9 | { 10 | vector new_Number = number; 11 | for (int i = 0; i < number.size() - 1; i++) 12 | { 13 | new_Number[i + 1] = number[i]; 14 | } 15 | new_Number[0] = 0; 16 | return new_Number; 17 | } 18 | 19 | int main(void) 20 | { 21 | vector binary_number = {1, 0, 1, 0, 0, 0, 1}; 22 | vector right_shifted_number = rightShift(binary_number); 23 | for (int i = 0; i < right_shifted_number.size(); i++) 24 | { 25 | cout << right_shifted_number[i]; 26 | } 27 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guides 2 | 3 | - Fork the project 4 | 5 | - Clone to your local machine 6 | 7 | - Find an issue to solve 8 | 9 | - Or Implement any DSA 10 | 11 | - Comment your changes and commits 12 | 13 | - Push your changes 14 | 15 | - Click the Compare & pull request button 16 | 17 | - Create new Pull Request to open new PR 18 | -------------------------------------------------------------------------------- /DSU/DSU.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Graph: 4 | 5 | def __init__(self,vertices): 6 | self.V= vertices 7 | self.graph = defaultdict(list) 8 | 9 | 10 | def addEdge(self,u,v): 11 | self.graph[u].append(v) 12 | 13 | def find_parent(self, parent,i): 14 | if parent[i] == -1: 15 | return i 16 | if parent[i]!= -1: 17 | return self.find_parent(parent,parent[i]) 18 | 19 | 20 | def union(self,parent,x,y): 21 | x_set = self.find_parent(parent, x) 22 | y_set = self.find_parent(parent, y) 23 | parent[x_set] = y_set 24 | 25 | 26 | def isCyclic(self): 27 | 28 | 29 | parent = [-1]*(self.V) 30 | 31 | 32 | for i in self.graph: 33 | for j in self.graph[i]: 34 | x = self.find_parent(parent, i) 35 | y = self.find_parent(parent, j) 36 | if x == y: 37 | return True 38 | self.union(parent,x,y) 39 | 40 | g = Graph(3) 41 | g.addEdge(0, 1) 42 | g.addEdge(1, 2) 43 | g.addEdge(2, 0) 44 | 45 | if g.isCyclic(): 46 | print "Graph contains cycle" 47 | else : 48 | print "Graph does not contain cycle " -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack/(2)SubsetSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool t[100][100]; 4 | 5 | bool SubsetSum(int *wt, int Sum, int n) { 6 | 7 | 8 | for (int i = 0; i <= Sum; i++) t[0][i] = false; 9 | for (int i = 0; i <= n; i++) t[i][0] = true; //empty set 10 | 11 | 12 | for (int i = 1; i <= n; i++) { 13 | for (int j = 1; j <= Sum; j++) { 14 | 15 | if (wt[i - 1] <= j) { 16 | t[i][j] = (t[i - 1][j - wt[i - 1]] || t[i - 1][j]); 17 | } 18 | else { 19 | t[i][j] = t[i - 1][j]; 20 | 21 | } 22 | } 23 | 24 | 25 | } 26 | return t[n][Sum]; 27 | } 28 | 29 | 30 | int main() { 31 | 32 | #ifndef ONLINE_JUDGE 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | #endif 36 | 37 | int wt[] = {1, 2, 4, 1}; 38 | int Sum = 8; 39 | cout << SubsetSum(wt, Sum, sizeof(wt) / sizeof(int)) << endl; 40 | //op - true/false 41 | } 42 | -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack/(3)EqualSumPartition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool t[100][100]; 4 | 5 | bool SubsetSum(int *wt, int Sum, int n) { 6 | 7 | 8 | for (int i = 0; i <= Sum; i++) t[0][i] = false; 9 | for (int i = 0; i <= n; i++) t[i][0] = true; //empty set 10 | 11 | 12 | for (int i = 1; i <= n; i++) { 13 | for (int j = 1; j <= Sum; j++) { 14 | 15 | if (wt[i - 1] <= j) { 16 | t[i][j] = (t[i - 1][j - wt[i - 1]] || t[i - 1][j]); 17 | } 18 | else { 19 | t[i][j] = t[i - 1][j]; 20 | 21 | } 22 | } 23 | 24 | 25 | } 26 | return t[n][Sum]; 27 | } 28 | 29 | bool EqSumPartition(int *wt, int n) { 30 | int s = 0; 31 | for (int i = 0; i < n; i++) s += wt[i]; 32 | 33 | if (s % 2 != 0) return false; 34 | else SubsetSum(wt, s / 2, n); 35 | } 36 | 37 | 38 | int main() { 39 | 40 | #ifndef ONLINE_JUDGE 41 | freopen("input.txt", "r", stdin); 42 | freopen("output.txt", "w", stdout); 43 | #endif 44 | 45 | int wt[] = {2, 6, 4, 10}; 46 | int n = sizeof(wt) / sizeof(int); 47 | cout << EqSumPartition(wt, n) << endl; 48 | } 49 | -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack/(4)CountOfSubetSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | int CountSubsetGivenSum(int *wt, int Sum, int n) { 6 | 7 | 8 | for (int i = 0; i <= Sum; i++) t[0][i] = 0; 9 | for (int i = 0; i <= n; i++) t[i][0] = 1; //empty set 10 | 11 | 12 | for (int i = 1; i <= n; i++) { 13 | for (int j = 1; j <= Sum; j++) { 14 | 15 | if (wt[i - 1] <= j) { 16 | t[i][j] = (t[i - 1][j - wt[i - 1]] + t[i - 1][j]); 17 | } 18 | else { 19 | t[i][j] = t[i - 1][j]; 20 | 21 | } 22 | } 23 | 24 | 25 | } 26 | return t[n][Sum]; 27 | } 28 | 29 | 30 | int main() { 31 | 32 | #ifndef ONLINE_JUDGE 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | #endif 36 | 37 | int wt[] = {1, 3, 4, 1}; 38 | int Sum = 5; 39 | int n = sizeof(wt) / sizeof(int); 40 | cout << CountSubsetGivenSum(wt, Sum, n) << endl; // considers all subsets so some are same 41 | } 42 | -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack/(5)MinSubsetSumDiff.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool t[100][100]; 4 | 5 | bool SubsetSum(int *wt, int Sum, int n) { 6 | 7 | 8 | for (int i = 0; i <= Sum; i++) t[0][i] = false; 9 | for (int i = 0; i <= n; i++) t[i][0] = true; //empty set 10 | 11 | 12 | for (int i = 1; i <= n; i++) { 13 | for (int j = 1; j <= Sum; j++) { 14 | 15 | if (wt[i - 1] <= j) { 16 | t[i][j] = (t[i - 1][j - wt[i - 1]] || t[i - 1][j]); 17 | } 18 | else { 19 | t[i][j] = t[i - 1][j]; 20 | 21 | } 22 | } 23 | 24 | 25 | } 26 | return t[n][Sum]; 27 | } 28 | 29 | 30 | int main() { 31 | 32 | #ifndef ONLINE_JUDGE 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | #endif 36 | 37 | int wt[] = {0, 2, 4, 3}; 38 | int n = sizeof(wt) / sizeof(int); 39 | int Range = 0; 40 | for (int i = 0; i < n; i++) Range += wt[i]; 41 | SubsetSum(wt, Range, n); // to create dp table 42 | vector v; 43 | 44 | for (int i = 0; i <= Range / 2; i++) { 45 | if (t[n][i] == true) { 46 | v.push_back(i); 47 | } 48 | } 49 | 50 | int last = INT_MIN; 51 | 52 | for (int i = 0; i < v.size(); i++) { 53 | if (last < v[i]) last = v[i]; 54 | } 55 | 56 | int ans = Range - 2 * last; 57 | cout << ans << endl; 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // LeetCode Target sum ques 6 | int CountSubsetGivenSum(int *wt, int Sum, int n) { 7 | 8 | 9 | for (int i = 0; i <= Sum; i++) t[0][i] = 0; 10 | for (int i = 0; i <= n; i++) t[i][0] = 1; //empty set 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= Sum; j++) { 15 | 16 | if (wt[i - 1] <= j) { 17 | t[i][j] = (t[i - 1][j - wt[i - 1]] + t[i - 1][j]); 18 | } 19 | else { 20 | t[i][j] = t[i - 1][j]; 21 | 22 | } 23 | } 24 | 25 | } 26 | return t[n][Sum]; 27 | } 28 | 29 | 30 | int main() { 31 | 32 | #ifndef ONLINE_JUDGE 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | #endif 36 | 37 | int wt[] = {1, 2, 4}; 38 | int diff = 3; 39 | int range = 0; 40 | int n = sizeof(wt) / sizeof(int); 41 | for (int i = 0; i < n; i++) range += wt[i]; 42 | int S1 = (diff + range) / 2; // diff+range should be even else ans=0 43 | cout << CountSubsetGivenSum(wt, S1, n) << endl; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Dynamic Programming/CuttingARod.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def max(a, b): 4 | return a if (a > b) else b 5 | 6 | def cutRod(price, n): 7 | if(n <= 0): 8 | return 0 9 | max_val = -sys.maxsize-1 10 | 11 | for i in range(0, n): 12 | max_val = max(max_val, price[i] + cutRod(price, n - i - 1)) 13 | return max_val 14 | 15 | 16 | arr = list(map(int , input().split())) 17 | size = len(arr) 18 | print("Maximum Value that can be obtained is", cutRod(arr, size)) 19 | 20 | # By Jay Dulera 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LCS/(2)LCSubstring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Longest Common Substring 6 | 7 | int LCS_topdown(string x, string y, int n, int m) { 8 | 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | for (int i = 0; i <= m; i++) t[0][i] = 0; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | 16 | if (x[i - 1] == y[j - 1]) { 17 | t[i][j] = 1 + t[i - 1][j - 1]; 18 | } 19 | else { 20 | t[i][j] = 0; 21 | } 22 | 23 | } 24 | } 25 | int ans = INT_MIN; 26 | for (int i = 0; i <= n; i++) { 27 | for (int j = 0; j <= m; j++) { 28 | ans = max(ans, t[i][j]); 29 | } 30 | } 31 | 32 | return ans; 33 | } 34 | 35 | int main() { 36 | 37 | #ifndef ONLINE_JUDGE 38 | freopen("input.txt", "r", stdin); 39 | freopen("output.txt", "w", stdout); 40 | #endif 41 | 42 | string x = "abcde"; 43 | string y = "abce"; 44 | int n = x.length(); 45 | int m = y.length(); 46 | cout << LCS_topdown(x, y, n, m) << endl; 47 | } 48 | -------------------------------------------------------------------------------- /Dynamic Programming/LCS/(3)PrintLCS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Print LCS 6 | 7 | void LCS_topdown(string x, string y, int n, int m) { 8 | 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | for (int i = 0; i <= m; i++) t[0][i] = 0; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | 16 | if (x[i - 1] == y[j - 1]) { 17 | t[i][j] = 1 + t[i - 1][j - 1]; 18 | } 19 | else { 20 | t[i][j] = max(t[i - 1][j], t[i][j - 1]); 21 | } 22 | 23 | } 24 | } 25 | 26 | } 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | string x = "acde"; 36 | string y = "agbce"; 37 | int n = x.length(); 38 | int m = y.length(); 39 | LCS_topdown(x, y, n, m); // to create dp table 40 | 41 | int i = n, j = m; 42 | string s = ""; 43 | 44 | while (i > 0 && j > 0) { 45 | if (x[i - 1] == y[j - 1]) { 46 | s += x[i - 1]; 47 | i--; 48 | j--; 49 | } 50 | 51 | else { 52 | if (t[i - 1][j] > t[i][j - 1]) i--; 53 | else j--; 54 | } 55 | } 56 | reverse(s.begin(), s.end()); 57 | cout << s << endl; 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Dynamic Programming/LCS/(4)PrintLCSubstring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Print Longest Common Substring 6 | 7 | void LCS_topdown(string x, string y, int n, int m) { 8 | 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | for (int i = 0; i <= m; i++) t[0][i] = 0; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | 16 | if (x[i - 1] == y[j - 1]) { 17 | t[i][j] = 1 + t[i - 1][j - 1]; 18 | } 19 | else { 20 | t[i][j] = 0; 21 | } 22 | } 23 | } 24 | } 25 | 26 | int main() { 27 | 28 | #ifndef ONLINE_JUDGE 29 | freopen("input.txt", "r", stdin); 30 | freopen("output.txt", "w", stdout); 31 | #endif 32 | 33 | string x = "acbde"; 34 | string y = "agbde"; 35 | int n = x.length(); 36 | int m = y.length(); 37 | LCS_topdown(x, y, n, m); // to create dp table 38 | 39 | 40 | int s = 0, e = 0; 41 | int ans = INT_MIN; 42 | 43 | for (int i = 0; i <= n; i++) { 44 | for (int j = 0; j <= m; j++) { // get the indexes with max element 45 | if (t[i][j] > ans ) { 46 | ans = t[i][j]; 47 | s = i; 48 | e = j; 49 | } 50 | } 51 | } 52 | 53 | cout << s << " " << e << endl; 54 | 55 | string str = ""; 56 | 57 | while (t[s][e] != 0) { 58 | str += x[s - 1]; 59 | s--; 60 | e--; 61 | } 62 | reverse(str.begin(), str.end()); 63 | cout << str; // there can be many LCSubstrings of max length but we are printing one 64 | 65 | } 66 | -------------------------------------------------------------------------------- /Dynamic Programming/LCS/(5)PrintSCS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Print Shortest Common Supersequence 6 | 7 | void LCS_topdown(string x, string y, int n, int m) { 8 | 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | for (int i = 0; i <= m; i++) t[0][i] = 0; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | 16 | if (x[i - 1] == y[j - 1]) { 17 | t[i][j] = 1 + t[i - 1][j - 1]; 18 | } 19 | else { 20 | t[i][j] = max(t[i - 1][j], t[i][j - 1]); 21 | } 22 | } 23 | } 24 | // return t[n][m]; 25 | return; 26 | } 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | string x = "aggtab"; 36 | string y = "gxtxayb"; 37 | 38 | int n = x.length(); 39 | int m = y.length(); 40 | LCS_topdown(x, y, n, m); // to create dp table 41 | 42 | int i = n, j = m; 43 | string s = ""; 44 | 45 | while (i > 0 && j > 0) { 46 | 47 | if (x[i - 1] == y[j - 1]) { 48 | s += x[i - 1]; 49 | i--; 50 | j--; 51 | } 52 | else { 53 | if (t[i - 1][j] > t[i][j - 1]) { 54 | s += x[i - 1]; 55 | i--; 56 | } 57 | else { 58 | s += y[j - 1]; 59 | j--; 60 | } 61 | } 62 | } 63 | 64 | while (i > 0) { 65 | s += x[i - 1]; 66 | i--; 67 | } 68 | while (j > 0) { 69 | s += y[j - 1]; 70 | j--; 71 | } 72 | 73 | reverse(s.begin(), s.end()); 74 | cout << s << endl; 75 | 76 | 77 | } 78 | -------------------------------------------------------------------------------- /Dynamic Programming/LCS/(6)LRepeatingS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Longest Repeating Subsequence 6 | 7 | int LCS_topdown(string x, string y, int n, int m) { 8 | 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | for (int i = 0; i <= m; i++) t[0][i] = 0; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | 16 | if (x[i - 1] == y[j - 1] && i != j) { 17 | t[i][j] = 1 + t[i - 1][j - 1]; 18 | } 19 | else { 20 | t[i][j] = max(t[i - 1][j], t[i][j - 1]); 21 | } 22 | } 23 | } 24 | return t[n][m]; 25 | // return; 26 | } 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | string x = "aabebcdd"; 36 | string y = x; 37 | 38 | int n = x.length(); 39 | int m = y.length(); 40 | cout << LCS_topdown(x, y, n, m); // to create dp table 41 | } 42 | -------------------------------------------------------------------------------- /Dynamic Programming/MCM/(1)MCM.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Matrix Chain Multiplication - MCM [on string / array] 6 | // Break at each k 7 | // Minimize cost to multiply matrix 8 | 9 | int solve(int a[], int i, int j) { 10 | 11 | // Ai = a[i-1]*a[i] matrix m*n 12 | int ans = INT_MAX; 13 | 14 | if (i >= j) return 0; 15 | 16 | for (int k = i; k <= j - 1; k++) { 17 | 18 | int temp_ans = solve(a, i, k) + solve(a, k + 1, j) + a[i - 1] * a[k] * a[j]; 19 | ans = min(temp_ans, ans); 20 | 21 | } 22 | 23 | return ans; 24 | } 25 | 26 | int main() { 27 | 28 | #ifndef ONLINE_JUDGE 29 | freopen("input.txt", "r", stdin); 30 | freopen("output.txt", "w", stdout); 31 | #endif 32 | 33 | int a[] = {2, 3, 4, 6}; 34 | int n = sizeof(a) / sizeof(int); 35 | 36 | cout << solve(a, 1, n - 1) << endl; 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Dynamic Programming/unbounded Knapsack/(1)UnbKp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // Rod Cutting Problem 6 | int Unbknapsack(int *wt, int *val, int W, int n) { 7 | 8 | for (int i = 0; i <= W; i++) t[0][i] = 0; 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | 11 | 12 | for (int i = 1; i <= n; i++) { 13 | for (int j = 1; j <= W; j++) { 14 | 15 | if (wt[i - 1] <= j) { 16 | t[i][j] = max(val[i - 1] + t[i][j - wt[i - 1]] , t[i - 1][j]); 17 | } 18 | else { 19 | t[i][j] = t[i - 1][j]; 20 | 21 | } 22 | } 23 | 24 | } 25 | return t[n][W]; 26 | } 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | int wt[] = {4, 9, 2, 2}; 36 | int val[] = {1, 2, 5, 4}; 37 | int W = 10; 38 | int n = sizeof(val) / sizeof(int); 39 | cout << Unbknapsack(wt, val, W, n) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /Dynamic Programming/unbounded Knapsack/(2)CoinChange1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // maximum number of ways 6 | 7 | int Unbknapsack(int *wt, int W, int n) { 8 | 9 | for (int i = 0; i <= W; i++) t[0][i] = 0; 10 | for (int i = 0; i <= n; i++) t[i][0] = 1; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= W; j++) { 15 | 16 | if (wt[i - 1] <= j) { 17 | t[i][j] = t[i][j - wt[i - 1]] + t[i - 1][j]; 18 | } 19 | else { 20 | t[i][j] = t[i - 1][j]; 21 | 22 | } 23 | } 24 | 25 | } 26 | return t[n][W]; 27 | } 28 | 29 | int main() { 30 | 31 | #ifndef ONLINE_JUDGE 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | #endif 35 | 36 | int coins[] = {1, 2, 3}; 37 | int W = 5; 38 | int n = sizeof(coins) / sizeof(int); 39 | cout << Unbknapsack(coins, W, n) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /Dynamic Programming/unbounded Knapsack/(3)CoinChange2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int t[100][100]; 4 | 5 | // minimum number of coins to make sum 6 | 7 | int Unbknapsack(int *wt, int W, int n) { 8 | 9 | for (int i = 0; i <= n; i++) t[i][0] = 0; 10 | for (int i = 0; i <= W; i++) t[0][i] = INT_MAX - 1; 11 | for (int i = 1; i <= W; i++) { 12 | if (i % wt[0] == 0) t[1][i] = i / wt[0]; 13 | else t[1][i] = INT_MAX - 1; 14 | } 15 | 16 | for (int i = 2; i <= n; i++) { 17 | for (int j = 1; j <= W; j++) { 18 | 19 | if (wt[i - 1] <= j) { 20 | t[i][j] = min( 1 + t[i][j - wt[i - 1]] , t[i - 1][j]); 21 | } 22 | else { 23 | t[i][j] = t[i - 1][j]; 24 | } 25 | } 26 | 27 | } 28 | return t[n][W]; 29 | 30 | } 31 | 32 | int main() { 33 | 34 | #ifndef ONLINE_JUDGE 35 | freopen("input.txt", "r", stdin); 36 | freopen("output.txt", "w", stdout); 37 | #endif 38 | 39 | int coins[] = {1, 2, 3}; 40 | int W = 5; 41 | int n = sizeof(coins) / sizeof(int); 42 | cout << Unbknapsack(coins, W, n) << endl; 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Heap/(1)KthSmallest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Kth smallest element 5 | priority_queue heap; //max heap 6 | 7 | int Solve(int a[], int n, int k) { 8 | 9 | for (int i = 0; i < n; i++) { 10 | 11 | heap.push(a[i]); 12 | if (heap.size() > k) heap.pop(); 13 | 14 | } 15 | 16 | return heap.top(); 17 | } 18 | 19 | 20 | int main() { 21 | 22 | #ifndef ONLINE_JUDGE 23 | freopen("input.txt", "r", stdin); 24 | freopen("output.txt", "w", stdout); 25 | #endif 26 | 27 | int n, k; 28 | cin >> n >> k; 29 | int a[n]; 30 | for (int i = 0; i < n; i++) cin >> a[i]; 31 | 32 | cout << Solve(a, n, k) << endl; 33 | } 34 | -------------------------------------------------------------------------------- /Heap/(2)KthLargest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Kth largest elements 5 | priority_queue, greater> heap; //min heap 6 | 7 | void Solve(int a[], int n, int k) { 8 | 9 | for (int i = 0; i < n; i++) { 10 | 11 | heap.push(a[i]); 12 | if (heap.size() > k) heap.pop(); 13 | 14 | } 15 | 16 | while (heap.size() > 0) { 17 | cout << heap.top() << " "; 18 | heap.pop(); 19 | } 20 | } 21 | 22 | 23 | int main() { 24 | 25 | #ifndef ONLINE_JUDGE 26 | freopen("input.txt", "r", stdin); 27 | freopen("output.txt", "w", stdout); 28 | #endif 29 | 30 | int n, k; 31 | cin >> n >> k; 32 | int a[n]; 33 | for (int i = 0; i < n; i++) cin >> a[i]; 34 | 35 | Solve(a, n, k); 36 | } 37 | -------------------------------------------------------------------------------- /Heap/(3)KSortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Sort a k-sorted array or nearly sorted array 5 | // Element that should be present in sorted array is within the [i-k,i+k] range 6 | 7 | priority_queue, greater> heap; //min heap 8 | 9 | void Solve(int a[], int n, int k) { 10 | 11 | for (int i = 0; i < n; i++) { 12 | 13 | heap.push(a[i]); 14 | if (heap.size() > k) { 15 | cout << heap.top() << " "; 16 | heap.pop(); 17 | } 18 | 19 | } 20 | 21 | while (heap.size() > 0) { 22 | cout << heap.top() << " "; 23 | heap.pop(); 24 | } 25 | } 26 | 27 | 28 | int main() { 29 | 30 | #ifndef ONLINE_JUDGE 31 | freopen("input.txt", "r", stdin); 32 | freopen("output.txt", "w", stdout); 33 | #endif 34 | 35 | int n, k; 36 | cin >> n >> k; 37 | int a[n]; 38 | for (int i = 0; i < n; i++) cin >> a[i]; 39 | 40 | Solve(a, n, k); 41 | } 42 | -------------------------------------------------------------------------------- /Heap/(4)KClosestNo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // K closest numbers to x 5 | 6 | priority_queue> heap; //max heap 7 | 8 | int main() { 9 | 10 | #ifndef ONLINE_JUDGE 11 | freopen("input.txt", "r", stdin); 12 | freopen("output.txt", "w", stdout); 13 | #endif 14 | 15 | int n, k; 16 | cin >> n >> k; 17 | int x; 18 | cin >> x; 19 | int a[n]; 20 | for (int i = 0; i < n; i++) cin >> a[i]; 21 | 22 | for (int i = 0; i < n; i++) { 23 | heap.push({abs(a[i] - x), a[i]}); 24 | if (heap.size() > k) { 25 | heap.pop(); 26 | } 27 | } 28 | 29 | while (heap.size() > 0) { 30 | cout << heap.top().second << " "; 31 | heap.pop(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Heap/(5)KFrequent.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Top k frequent numbers 5 | 6 | priority_queue, vector>, greater>> heap; // min heap 7 | 8 | int main() { 9 | 10 | #ifndef ONLINE_JUDGE 11 | freopen("input.txt", "r", stdin); 12 | freopen("output.txt", "w", stdout); 13 | #endif 14 | 15 | int n, k; 16 | cin >> n >> k; 17 | int a[n]; 18 | unordered_map m; 19 | 20 | for (int i = 0; i < n; i++) { cin >> a[i]; m[a[i]]++; } 21 | 22 | for (auto i : m) { 23 | heap.push({i.second, i.first}); 24 | 25 | if (heap.size() > k) { 26 | heap.pop(); 27 | } 28 | 29 | } 30 | 31 | while (heap.size() > 0) { 32 | cout << heap.top().second << " "; 33 | heap.pop(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Mathematics/Factorial/factorial.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | 4 | ;; returns factorial of the given number 5 | ;; Number -> Number 6 | ;; code 7 | ;(define (fact n) 1) ; stub 8 | 9 | (define (fact n) 10 | (cond 11 | [(zero? n) 1] ;; basecase 12 | [else 13 | (* ;; 14 | n 15 | (fact (sub1 n)))])) ;; structural recursion and reduction of n 16 | 17 | 18 | 19 | 20 | ;; test examples 21 | ;(equal? (fact 0) 1) ;basecase 22 | ;(equal? (fact 1) 1) 23 | ;(equal? (fact 3) (* 3 (* 2 1))) -------------------------------------------------------------------------------- /Mathematics/GCD/GCD&LCM_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* This c++ program uses Basic Euclidean algorithm to find greatest common factor(GCD) and lowest common multiple(LCM) of two numbers a and b entered by user 2 | LCM(a,b) = a*b/GCD(a,b) 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | long long greatest_common_factor(long long a,long long b) 9 | { 10 | if(a == 0){ 11 | return b; 12 | } 13 | greatest_common_factor(b%a,a); 14 | } 15 | long long lowest_common_multiple(long long a,long long b) 16 | { 17 | return ( (a*b)/greatest_common_factor(a,b) ); 18 | } 19 | int main() 20 | { 21 | long long a,b; 22 | cin >> a >> b; 23 | long long gcd = greatest_common_factor(a,b); 24 | long long lcm = lowest_common_multiple(a,b); 25 | cout<<"GCD of " << a << " and " << b <<" is " << gcd <<" and LCM is " << lcm <<"\n"; 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Mathematics/GCD/GCD_and_LCM.js: -------------------------------------------------------------------------------- 1 | let gcd = (num1, num2) => { 2 | //if num2 is 0 return num1; 3 | if(num2 === 0){ 4 | return num1; 5 | } 6 | 7 | //call the same function recursively 8 | return gcd(num2, num1 % num2); 9 | 10 | // Note: 11 | // Time complexity: O(n) or O(log(a) + log(b)). 12 | // Space complexity: O(m + n). 13 | } 14 | 15 | let lcm = (n1, n2) => { 16 | //Find the gcd first 17 | let gcd = gcd(n1, n2); 18 | 19 | //then calculate the lcm 20 | return (n1 * n2) / gcd; 21 | 22 | //Note: 23 | // Time complexity: O(log(a) + log(b)). 24 | // Space complexity: O(1). 25 | } 26 | 27 | console.log(gcd(60, 15)); 28 | console.log(lcm(15, 20)); 29 | -------------------------------------------------------------------------------- /Mathematics/GCD/LcmGcd.java: -------------------------------------------------------------------------------- 1 | public class LcmGcd { 2 | 3 | // recursive function to return gcd of a and b 4 | private static int gcd(int a, int b) { 5 | /*please see: https://en.wikipedia.org/wiki/Euclidean_algorithm*/ 6 | if (b == 0) return a; 7 | return gcd(b, a % b); 8 | } 9 | 10 | // function to return LCM of two numbers 11 | private static int lcm(int a, int b) { 12 | /* 13 | a * b = lcm(a, b) * gcd (a, b) 14 | lcm(a, b) = (a * b) / gcd(a, b) 15 | */ 16 | return (a / gcd(a, b)) * b; 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println("lcm of 10, 35 is: " + lcm(10, 35)); 21 | System.out.println("gcd of 10, 35 is: " + gcd(10, 35)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Mathematics/GCD/Mathematics.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TestMath 4 | { 5 | public static class Mathematics 6 | { 7 | /// 8 | /// Calcualtes Greatest Common Divisor of given 2 integers 9 | /// 10 | /// 11 | /// 12 | /// 13 | public static int GCD(int a,int b) 14 | { 15 | if (a % b == 0) 16 | { 17 | return b; 18 | } 19 | 20 | return GCD(b, a % b); 21 | } 22 | 23 | /// 24 | /// Calcualtes Least Common Multiple of given 2 integers 25 | /// 26 | /// 27 | /// 28 | /// 29 | public static int LCM(int a, int b) 30 | { 31 | return Math.Min(a, b) * GCD(a, b); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Mathematics/GCD/gcd.cpp: -------------------------------------------------------------------------------- 1 | //Euclid's GCD/HCF Algorithm 2 | //O(log N) 3 | //1)GCD(a,b)=GCD(b,a%b) 4 | //2)GCD(a,0)=a 5 | //Compute HCF & LCM 6 | //gcd*LCM = a*b 7 | #include 8 | using namespace std; 9 | 10 | int gcd(int a, int b) { 11 | return b == 0 ? a : gcd(b, a % b); 12 | } 13 | 14 | int main() { 15 | int n1, n2; 16 | cin >> n1 >> n2; 17 | 18 | int GCD= gcd(n1, n2);` 19 | int LCM = (n1 * n2) / GCD; 20 | cout << GCD << " " << LCM; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Mathematics/GCD/gcd.js: -------------------------------------------------------------------------------- 1 | function gcd(a, b = null) { 2 | if (b != null) { 3 | if (a % b == 0) return b; 4 | } else { 5 | for (var i = 1; i < a.length; i++) a[0] = gcd(a[0], a[i]); 6 | return a[0]; 7 | } 8 | 9 | return gcd(b, a % b); 10 | } 11 | 12 | console.log(gcd(9, 18)); 13 | 14 | console.log(gcd([6, 12, 18])); 15 | -------------------------------------------------------------------------------- /Mathematics/GCD/gcd.py: -------------------------------------------------------------------------------- 1 | def gcd(a,b = None): 2 | if b != None: 3 | if a % b == 0: 4 | return b 5 | else: 6 | return gcd( b, a % b) 7 | else: 8 | for i in range(len(a)): 9 | a[0] = gcd(a[0],a[i]) 10 | return a[0] 11 | 12 | 13 | 14 | print(gcd([18,12, 6])) 15 | 16 | print(gcd(9, 12)) -------------------------------------------------------------------------------- /Mathematics/GCD/lcm_gcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // recursive function to return gcd of a and b 4 | int gcd(int a, int b) { 5 | /*please see: https://en.wikipedia.org/wiki/Euclidean_algorithm*/ 6 | if (b == 0) return a; 7 | return gcd(b, a % b); 8 | } 9 | 10 | // function to return LCM of two numbers 11 | int lcm(int a, int b) { 12 | /* 13 | a * b = lcm(a, b) * gcd (a, b) 14 | lcm(a, b) = (a * b) / gcd(a, b) 15 | */ 16 | return (a / gcd(a, b)) * b; 17 | } 18 | 19 | int main() { 20 | printf("lcm of 10, 35 is: %d\n", lcm(10, 35)); 21 | printf("lcm of 10, 35 is: %d\n", gcd(10, 35)); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Mathematics/GCD/lcm_gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // recursive function to return gcd of a and b 6 | int gcd(int a, int b) { 7 | /*please see: https://en.wikipedia.org/wiki/Euclidean_algorithm*/ 8 | if (b == 0) return a; 9 | return gcd(b, a % b); 10 | } 11 | 12 | // function to return LCM of two numbers 13 | int lcm(int a, int b) { 14 | /* 15 | a * b = lcm(a, b) * gcd (a, b) 16 | lcm(a, b) = (a * b) / gcd(a, b) 17 | */ 18 | return (a / gcd(a, b)) * b; 19 | } 20 | 21 | int main() { 22 | cout << "lcm of 10, 35 is: " << lcm(10, 35) << "\n"; 23 | cout << "gcd of 10, 35 is: " << gcd(10, 35) << "\n"; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Mathematics/GCD/lcm_gcd.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // recursive function to return gcd of a and b 6 | func gcd(a int, b int) int { 7 | /*please see: https://en.wikipedia.org/wiki/Euclidean_algorithm*/ 8 | if b == 0 { 9 | return a 10 | } 11 | return gcd(b, a%b) 12 | } 13 | 14 | // function to return LCM of two numbers 15 | func lcm(a int, b int) int { 16 | /* 17 | a * b = lcm(a, b) * gcd (a, b) 18 | lcm(a, b) = (a * b) / gcd(a, b) 19 | */ 20 | return (a / gcd(a, b)) * b 21 | } 22 | 23 | func main() { 24 | fmt.Println("lcm of 10, 35 is: ", lcm(10, 35)) 25 | fmt.Println("lcm of 10, 35 is: ", gcd(10, 35)) 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Mathematics/LCM/LCM.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | 4 | int n1 = 72, n2 = 120, lcm; 5 | 6 | // maximum number between n1 and n2 is stored in lcm 7 | lcm = (n1 > n2) ? n1 : n2; 8 | 9 | // Always true 10 | while(true) { 11 | if( lcm % n1 == 0 && lcm % n2 == 0 ) { 12 | System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm); 13 | break; 14 | } 15 | ++lcm; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Mathematics/LCM/lcm.js: -------------------------------------------------------------------------------- 1 | function gcd(a, b) { 2 | if (a % b == 0) return b; 3 | return gcd(b, a % b); 4 | } 5 | function lcm(a, b) { 6 | return Math.min(a, b) * gcd(a, b); 7 | } 8 | 9 | console.log(lcm(6, 9)) -------------------------------------------------------------------------------- /Mathematics/LCM/lcm.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | 3 | if a % b == 0: 4 | return b 5 | return gcd(b, a % b) 6 | 7 | 8 | def lcm(a, b): 9 | return min(a, b)*gcd(a, b) 10 | 11 | 12 | print(lcm(6, 9)) 13 | -------------------------------------------------------------------------------- /Mathematics/SieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int MAX = 1e5 + 5; 6 | bool sieve[MAX]; 7 | void sieveOfEratosthenes() { 8 | memset(sieve, true, sizeof(sieve)); 9 | sieve[0] = sieve[1] = false; 10 | for(int i = 2;i < MAX;i++) { 11 | if(sieve[i] == true) { 12 | for(int j = 2 * i;j < MAX;j += i) { 13 | sieve[j] = false; 14 | } 15 | } 16 | } 17 | } 18 | 19 | int main() { 20 | int n; 21 | cin >> n; 22 | 23 | sieveOfEratosthenes(); 24 | 25 | if(sieve[n] == true) { 26 | cout << "Prime" << endl; 27 | } else { 28 | cout << "Not Prime" << endl; 29 | } 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Mathematics/SieveofEratosthenes.java: -------------------------------------------------------------------------------- 1 | // Java program to print all primes smaller than or equal to 2 | // n using Sieve of Eratosthenes 3 | 4 | class SieveOfEratosthenes 5 | { 6 | void sieveOfEratosthenes(int n) 7 | { 8 | // Create a boolean array "prime[0..n]" and initialize 9 | // all entries it as true. A value in prime[i] will 10 | // finally be false if i is Not a prime, else true. 11 | boolean prime[] = new boolean[n+1]; 12 | for(int i=0;i 2 | int main() { 3 | int i, n, t1 = 0, t2 = 1, nextTerm; 4 | printf("Enter the number of terms: "); 5 | scanf("%d", &n); 6 | printf("Fibonacci Series: "); 7 | 8 | for (i = 1; i <= n; ++i) { 9 | printf("%d, ", t1); 10 | nextTerm = t1 + t2; 11 | t1 = t2; 12 | t2 = nextTerm; 13 | } 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/Fibonacci.java: -------------------------------------------------------------------------------- 1 | 2 | //Java program to evaluate fibonacci series 3 | 4 | import java.util.Scanner; 5 | 6 | public class Fibonacci{ 7 | public static void main(String args[]){ 8 | Scanner inp = new Scanner(System.in); 9 | int term = inp.nextInt(); 10 | int first =1, second = 1, temp_first=1; 11 | while(first<=term){ 12 | System.out.print(first+" "); 13 | temp_first = first; 14 | first = second; 15 | second += temp_first; 16 | 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Mathematics/fibonacci/Fibonacci.ml.txt: -------------------------------------------------------------------------------- 1 | fun (n) = if (n = 0) then 0 if (n = 1) then 1 else fib(n-1) +fib(n-2); 2 | (*If n = 0 or n=1 then the program directly outputs the value which is defined for other cases fib(n) breaks into two sub problems 3 | computing fib(n-1) and fib(n-2) and this chain continues till the function reaches the base case*) 4 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/FibonacciDynamicProgramming.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | FibArray = [0, 1] 3 | 4 | while len(FibArray) < n + 1: 5 | FibArray.append(0) 6 | 7 | if n <= 1: 8 | return n 9 | else: 10 | if FibArray[n - 1] == 0: 11 | FibArray[n - 1] = fibonacci(n - 1) 12 | 13 | if FibArray[n - 2] == 0: 14 | FibArray[n - 2] = fibonacci(n - 2) 15 | 16 | FibArray[n] = FibArray[n - 2] + FibArray[n - 1] 17 | return FibArray[n] 18 | 19 | 20 | n=int(input("Please enter a number: ")) 21 | print(fibonacci(n)) 22 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/FibonacciIterative.java: -------------------------------------------------------------------------------- 1 | public class FibonacciIterative { 2 | public static void main (String[]args) { 3 | System.out.println (nfib (0)); // Output - 0 4 | System.out.println (nfib (1)); // Output - 1 5 | System.out.println (nfib (2)); // Output - 1 6 | System.out.println (nfib (3)); // Output - 2 7 | System.out.println (nfib (4)); // Output - 3 8 | System.out.println (nfib (5)); // Output - 5 9 | } 10 | 11 | static int nfib (int n) { 12 | int c = 1; 13 | int a = 0; 14 | int b = 1; 15 | 16 | if (n == 0) return 0; 17 | 18 | while (c < n) { 19 | b += a; 20 | a = b - a; 21 | c++; 22 | } 23 | return b; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/FibonacciRecursive.java: -------------------------------------------------------------------------------- 1 | public class FibonacciRecursive { 2 | public static void main (String[]args) { 3 | System.out.println (nfib (0)); // Output - 0 4 | System.out.println (nfib (1)); // Output - 1 5 | System.out.println (nfib (2)); // Output - 1 6 | System.out.println (nfib (3)); // Output - 2 7 | System.out.println (nfib (4)); // Output - 3 8 | System.out.println (nfib (5)); // Output - 5 9 | } 10 | 11 | static int nfib (int n) { 12 | 13 | if (n == 0) return 0; 14 | 15 | if (n == 1) return 1; 16 | 17 | return nfib(n - 1) + nfib(n - 2); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/FibonacciSequence.c: -------------------------------------------------------------------------------- 1 | 2 | 3 | /** 4 | * GitHub username: chinmaykumbhare 5 | * 6 | * Issue Statement: 7 | * Implement Fibonacci sequence in any language. Recursive is appreciated. 8 | */ 9 | 10 | #include 11 | 12 | void main (void) { 13 | 14 | int num = 0; 15 | 16 | //enter the number of elements you would like to display as output 17 | 18 | scanf(" %d", &num); 19 | 20 | //using 3 variables, namely, prev for previous term. current for current term and next for next term in the sequence 21 | 22 | int prev = 0, current = 1, next = 1; 23 | 24 | //loop for calculating and printing the next number in fibonacci series 25 | 26 | for(int loop = 0; loop < num; loop++) { 27 | 28 | printf("%d ", prev); 29 | 30 | next = current + prev; 31 | 32 | prev = current; 33 | 34 | current = next; 35 | 36 | } 37 | 38 | printf("\n"); 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/Fibonacci_Series.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Main 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc = new Scanner(System.in); 7 | int sum = 0, n; 8 | int a = 0; 9 | int b = 1; 10 | System.out.println("Enter the nth value: "); 11 | n = sc.nextInt(); 12 | System.out.println("Fibonacci series: "); 13 | while(sum <= n) 14 | { 15 | System.out.print(sum + " "); 16 | a = b; // swap elements 17 | b = sum; 18 | sum = a + b; // next term is the sum of the last two terms 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/Maitreyi88_fibonacci.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[30]: 5 | 6 | 7 | a= int(input("Input integer: ")) 8 | def fibo(a): 9 | a1, a2 = 0, 1 10 | a3 = 0 11 | if a == 1: 12 | print("Fibonacci sequence upto",a,":",a1) 13 | else: 14 | print("Fibonacci sequence:") 15 | while a3 <= a: 16 | print(a1,end=" ") 17 | a3 = a1 + a2 18 | a1 = a2 19 | a2 = a3 20 | fibo(a) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fac.c: -------------------------------------------------------------------------------- 1 | #include 2 | long long int factorial (long long int n){ 3 | if(n<0) 4 | return 0; 5 | if(n==0) 6 | return 1; 7 | else 8 | return n*factorial(n-1); 9 | } 10 | 11 | int main () { 12 | long long int n, total; 13 | scanf ("%lld", &n); 14 | total = factorial(n); 15 | printf ("%d\n", total); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fib.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | ;; The Fibonacci Sequence is the series of numbers: 4 | ;; 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... 5 | 6 | ;; integer -> list of integers 7 | ;; building intution for fibn - inner helper function 8 | ;; fn = fn-1 + fn-2 where fn < 2 = n 9 | ;; f0 = 0, f1 = 1 ; basecases 10 | ;; f2 = f1 + f0 = 1 + 0 = 1 11 | ;; f3 = f2 + f1 = 1 + 1 12 | ;; f8 = f7 + f6 = 13 + 8 = 21 13 | 14 | ;; code 15 | ;(define (fib n) (list 0)) ; stub 16 | 17 | (define (fib n) 18 | (local [(define (fibn n) ;; inner helper function to calculate (fib n) 19 | (cond [(= n 0) 0] 20 | [(= n 1) 1] 21 | [else 22 | (+ ;; add fn-1 to fn-2 23 | (fibn (- n 1)) 24 | (fibn (- n 2)))]))] ;; self reference for structital recursion 25 | (build-list (add1 n) fibn))) 26 | 27 | ;; test examples for fibn 28 | ;(equal? (fibn 0) 0) ;; base case for structural recursion 29 | ;(equal? (fibn 1) 1) ;; base case for structural recursion 30 | ;(equal? (fibn 8) (+ (fibn 7) (fibn 6))) ;; intution 31 | ;(equal? (fibn 8) 21) 32 | ; 33 | 34 | ;; test examples for fib 35 | ;(equal? (fib 0) (cons 0 empty)) ;; base case for structural recursion 36 | ;(equal? (fib 1) (list 0 1)) ;; base case for structural recursion 37 | ;(equal? (fib 8) (list 0 1 1 2 3 5 8 13 21)) -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibo.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | int limit, no1 = 0, no2 = 1; 5 | printf("Enter the number of terms :- "); 6 | scanf("%d", &limit); 7 | if(limit == 0) 8 | return 0; 9 | else { 10 | printf("%d\t", no1); 11 | for(int i = 0; i < limit - 1; i++) { 12 | no2 = no1 + no2; 13 | no1 = no2 - no1; 14 | printf("%d\t", no1); 15 | } 16 | } 17 | return 0; 18 | } -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int limit, no1 = 0, no2 = 1; 6 | cout<<"Enter the number of terms :- "; 7 | cin>>limit; 8 | cout<<"Fibonacci series upto "< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, t1 = 0, t2 = 1, nextTerm = 0; 7 | 8 | cout << "Enter the number of terms: "; 9 | cin >> n; 10 | 11 | cout << "Fibonacci Series: "; 12 | 13 | for (int i = 1; i <= n; ++i) 14 | { 15 | // Prints the first two terms. 16 | if(i == 1) 17 | { 18 | cout << " " << t1; 19 | continue; 20 | } 21 | if(i == 2) 22 | { 23 | cout << t2 << " "; 24 | continue; 25 | } 26 | nextTerm = t1 + t2; 27 | t1 = t2; 28 | t2 = nextTerm; 29 | 30 | cout << nextTerm << " "; 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci(iterative).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t1 = 0, t2 = 1, nextTerm = 0, n; 7 | 8 | cout << "Enter a positive number: "; 9 | cin >> n; 10 | 11 | // displays the first two terms which is always 0 and 1 12 | cout << "Fibonacci Series: " << t1 << ", " << t2 << ", "; 13 | 14 | nextTerm = t1 + t2; 15 | 16 | while(nextTerm <= n) 17 | { 18 | cout << nextTerm << ", "; 19 | t1 = t2; 20 | t2 = nextTerm; 21 | nextTerm = t1 + t2; 22 | } 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | //fibonacci series starting from 1 6 | //n>=1 7 | int n; 8 | cin>>n; 9 | int n1 = 1, n2 = 1, fib = 0; 10 | printf("1 1 "); 11 | while (fib= 1 { 9 | fmt.Printf("%d", 1) 10 | } 11 | 12 | a, b := 1, 1 13 | 14 | for b <= limit { 15 | fmt.Printf(", %d", b) 16 | a, b = b, a+b 17 | } 18 | 19 | fmt.Println() 20 | } 21 | 22 | func main() { 23 | fibonacci(8) 24 | fibonacci(123) 25 | fibonacci(1) 26 | fibonacci(50) 27 | fibonacci(100) 28 | } 29 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci.js: -------------------------------------------------------------------------------- 1 | function fibonacci_series (number_of_terms) { 2 | // when there is only 1 term left then the first terms are to be returned 3 | if (number_of_terms === 2) { 4 | return [0, 1]; 5 | } else { 6 | // recursive call to its own self to get the last term 7 | let generated_series = fibonacci_series (number_of_terms - 1); 8 | let generated_series_length = generated_series.length 9 | // current term is the sum of the previous two terms 10 | generated_series[generated_series_length] = generated_series[generated_series_length - 1] + generated_series[generated_series_length - 2] 11 | // returns the generated sequence 12 | return generated_series; 13 | } 14 | }; 15 | 16 | // call the generate the sequence with the parameter indicating the number of terms upto which the sequence is to be generated 17 | fibonacci_series(8); 18 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci.py: -------------------------------------------------------------------------------- 1 | # Python program to display the Fibonacci sequence 2 | 3 | def fibonacci(n): 4 | if n <= 1: 5 | return n 6 | else: 7 | return(fibonacci(n-1) + fibonacci(n-2)) 8 | 9 | N = input() 10 | 11 | if N <= 0: 12 | print("Plese enter a positive integer") 13 | else: 14 | print("Fibonacci sequence:") 15 | for i in range(N): 16 | print(fibonacci(i)) -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacciSeries.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Main 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc = new Scanner(System.in); 7 | int sum = 0, n; 8 | int a = 0; 9 | int b = 1; 10 | System.out.println("Enter the nth value: "); 11 | n = sc.nextInt(); 12 | System.out.println("Fibonacci series: "); 13 | while(sum <= n) 14 | { 15 | System.out.print(sum + " "); 16 | a = b; // swap elements 17 | b = sum; 18 | sum = a + b; // next term is the sum of the last two terms 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacciSeries.js: -------------------------------------------------------------------------------- 1 | function fibonacciSeries(n) { 2 | if (n >= 1) console.log(1); 3 | 4 | var a = 1, 5 | b = 1; 6 | 7 | while (b <= n) { 8 | console.log(b); 9 | b = b + a; 10 | a = b - a; 11 | } 12 | 13 | 14 | } 15 | 16 | fibonacciSeries(9) 17 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacciSeries.py: -------------------------------------------------------------------------------- 1 | def fibonacciseries(n): 2 | if(n<=1): 3 | print(1) 4 | a, b = 1, 1 5 | print(a) 6 | while(b<=n): 7 | print(b) 8 | a, b = b, a+b 9 | 10 | fibonacciseries(9) 11 | 12 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fib(int *arr, int n) 5 | { 6 | if (n == 0 || n == 1) 7 | return 1; 8 | 9 | if (arr[n] > 0) 10 | return arr[n]; 11 | 12 | int output = fib(arr, n - 1) + fib(arr, n - 2); 13 | arr[n] = output; 14 | return output; 15 | } 16 | int main() 17 | { 18 | ios_base::sync_with_stdio(false); 19 | cin.tie(NULL); 20 | cout.tie(NULL); 21 | 22 | int n; 23 | cin >> n; 24 | int *input = new int[n]; 25 | for (int i = 0; i < n; i++) 26 | input[i] = 0; 27 | 28 | cout << fib(input, n); 29 | delete[] input; 30 | } -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci_recursive.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Fibonacci_Recursive 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | Console.WriteLine("Put in n\nn = index of Fibonacci digits"); 14 | int n = Convert.ToInt32(Console.ReadLine()); 15 | int fib = Fibonacci_rec(n); 16 | 17 | Console.WriteLine($"\nThe {n}. fib-digit is {fib}"); 18 | 19 | 20 | Console.ReadLine(); 21 | } 22 | public static int Fibonacci_rec(int n) 23 | { 24 | if (n == 0) 25 | return 0; 26 | return n == 1 ? 1 : n == 2 ? 1 : Fibonacci_rec(n - 1) + Fibonacci_rec(n - 2); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci_recursive.py: -------------------------------------------------------------------------------- 1 | def fib_recursive(n): 2 | if n > 1: 3 | return fib_recursive(n-1) + fib_recursive(n-2) 4 | return n 5 | 6 | 7 | if __name__ == '__main__': 8 | nums = int(input('How many fibonacci numbers:')) 9 | if nums < 2: 10 | print('Invalid nums') 11 | else: 12 | for i in range(nums): 13 | print(fib_recursive(i)) -------------------------------------------------------------------------------- /Mathematics/fibonacci/fibonacci_series.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if n<=2: 3 | return 1 4 | else: 5 | return fibonacci(n-1) + fibonacci(n-2) 6 | 7 | n = int(input('Enter a number (greather than 2): ')) 8 | 9 | for val in range(1,n-1): 10 | print(fibonacci(val), end = ', ') 11 | -------------------------------------------------------------------------------- /Mathematics/modulo_exp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int power(int x, unsigned int y, int p) 5 | { 6 | int res = 1; 7 | 8 | x = x % p; 9 | if (x == 0) return 0; 10 | 11 | while (y > 0) 12 | { 13 | if (y & 1) 14 | res = (res*x) % p; 15 | 16 | y = y>>1; 17 | x = (x*x) % p; 18 | } 19 | return res; 20 | } 21 | 22 | int main() 23 | { int x , y , p ; 24 | cout<<"Enter x , y and p\n" ; 25 | cin>>x>>y>>p ; 26 | cout << "Power is " << power(x, y, p); 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Mathematics/sieve_of_eratosthenes.py: -------------------------------------------------------------------------------- 1 | #Python Code of Sieve Of Eratosthenes 2 | 3 | def findPrime(num) : 4 | 5 | primeNum = [True for index in range(num+1)] 6 | 7 | index = 2 8 | 9 | while index <= num : 10 | 11 | if primeNum[index] : 12 | 13 | for index1 in range(index*index, num+1, index) : 14 | primeNum[index1] = False 15 | index = index +1 16 | 17 | 18 | return primeNum 19 | 20 | def showPrime(prime, num) : 21 | 22 | for index in range(2, num+1): 23 | 24 | if prime[index] : 25 | 26 | print(index) 27 | 28 | def main(): 29 | 30 | num = int(input()) 31 | 32 | prime = findPrime(num) 33 | 34 | showPrime(prime, num) 35 | 36 | if __name__ == "__main__" : 37 | main() -------------------------------------------------------------------------------- /Recursion/(1)Print1_N.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | 8 | void Print1_N(int n) { 9 | 10 | if (n == 1) { 11 | cout << n << " "; 12 | return; 13 | } 14 | Print1_N(n - 1); 15 | cout << n << " "; 16 | } 17 | 18 | void PrintN_1(int n) { 19 | 20 | if (n == 1) { 21 | cout << n << " "; 22 | return; 23 | } 24 | cout << n << " "; 25 | PrintN_1(n - 1); 26 | } 27 | 28 | int main() 29 | { 30 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 31 | 32 | #ifndef ONLINE_JUDGE 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | #endif 36 | 37 | int n; 38 | cin >> n; 39 | Print1_N(n); 40 | cout << endl; 41 | PrintN_1(n); 42 | 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /Recursion/(10)PermWSpaces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | // Permutation with spaces 8 | void PermWithSpaces(string ip, string op) { 9 | 10 | if (ip == "") { 11 | cout << op << endl; 12 | return; 13 | } 14 | 15 | PermWithSpaces(ip.substr(1), op + ip[0]); 16 | PermWithSpaces(ip.substr(1), op + " " + ip[0]); 17 | 18 | } 19 | 20 | int main() 21 | { 22 | 23 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 24 | 25 | #ifndef ONLINE_JUDGE 26 | freopen("input.txt", "r", stdin); 27 | freopen("output.txt", "w", stdout); 28 | #endif 29 | 30 | string ip; 31 | cin >> ip; 32 | string op = ""; 33 | op = op + ip[0]; 34 | PermWithSpaces(ip.substr(1), op); 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Recursion/(11)PermWCases.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | // Permutation with case change 8 | void PermWithCases(string ip, string op) { 9 | 10 | if (ip == "") { 11 | cout << op << endl; 12 | return; 13 | } 14 | 15 | PermWithCases(ip.substr(1), op + ip[0]); 16 | char out = ip[0]; 17 | out = toupper(out); 18 | PermWithCases(ip.substr(1), op + out); 19 | 20 | } 21 | 22 | int main() 23 | { 24 | 25 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 26 | 27 | #ifndef ONLINE_JUDGE 28 | freopen("input.txt", "r", stdin); 29 | freopen("output.txt", "w", stdout); 30 | #endif 31 | 32 | string ip; // ip will be in lowercase alphabet 33 | cin >> ip; 34 | string op = ""; 35 | 36 | PermWithCases(ip, op); 37 | 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Recursion/(12)LetterCasePerm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | // Letter case permutation 8 | void LetterCasePerm(string ip, string op) { 9 | 10 | if (ip == "") { 11 | cout << op << endl; 12 | return; 13 | } 14 | 15 | if (isalpha(ip[0])) { 16 | char uc = toupper(ip[0]); 17 | char lc = tolower(ip[0]); 18 | LetterCasePerm(ip.substr(1), op + uc); 19 | LetterCasePerm(ip.substr(1), op + lc); 20 | } 21 | else { 22 | LetterCasePerm(ip.substr(1), op + ip[0]); 23 | } 24 | } 25 | 26 | int main() 27 | { 28 | 29 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 30 | 31 | #ifndef ONLINE_JUDGE 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | #endif 35 | 36 | string ip; // ip will be of A1b2 kind 37 | cin >> ip; 38 | string op = ""; 39 | 40 | LetterCasePerm(ip, op); 41 | 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Recursion/(13)BalancedParenthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long int lli; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | // Generate all balanced parenthesis 8 | void solve(string op, int open, int close, vector &v) { 9 | 10 | if (open == 0 && close == 0) { 11 | v.push_back(op); 12 | return; 13 | } 14 | 15 | if (open > 0) solve(op + '(', open - 1, close, v); 16 | if (close > open) solve(op + ')', open, close - 1, v); 17 | return; 18 | } 19 | 20 | void solve2(int n, string op, int open, int close, vector &v) { 21 | 22 | if (open == n && close == n) { 23 | v.push_back(op); 24 | return; 25 | } 26 | 27 | if (open <= n) solve2(n, op + '(', open + 1, close, v); 28 | if (close < open) solve2(n, op + ')', open, close + 1, v); 29 | return; 30 | } 31 | 32 | int main() 33 | { 34 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 35 | 36 | #ifndef ONLINE_JUDGE 37 | freopen("input.txt", "r", stdin); 38 | freopen("output.txt", "w", stdout); 39 | #endif 40 | 41 | int n; 42 | cin >> n; 43 | 44 | int close = n, open = n; 45 | string op = ""; 46 | vector v; 47 | solve(op, open, close, v); 48 | 49 | for (auto s : v) cout << s << " "; 50 | cout << endl; 51 | v.clear(); 52 | 53 | op = ""; 54 | open = 0; 55 | close = 0; 56 | solve2(n, op, open, close, v); 57 | 58 | for (auto s : v) cout << s << " "; 59 | cout << endl; 60 | 61 | } 62 | -------------------------------------------------------------------------------- /Recursion/(14)Prefix1s_0s.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long int lli; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | // Print N-bit binary numbers having more/equal 1’s than 0’s for any prefix 8 | 9 | void solve(string op, int n, int ones, int zeroes) { 10 | 11 | if (n == 0) { 12 | cout << op << " "; 13 | return; 14 | } 15 | 16 | solve(op + '1', n - 1, ones + 1, zeroes); 17 | if (ones > zeroes) { 18 | solve(op + '0', n - 1, ones, zeroes + 1); 19 | } 20 | 21 | return; 22 | } 23 | 24 | int main() 25 | { 26 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 27 | 28 | #ifndef ONLINE_JUDGE 29 | freopen("input.txt", "r", stdin); 30 | freopen("output.txt", "w", stdout); 31 | #endif 32 | 33 | int n; 34 | cin >> n; 35 | string op = ""; 36 | int ones = 0, zeroes = 0; 37 | 38 | solve(op, n, ones, zeroes); 39 | } 40 | -------------------------------------------------------------------------------- /Recursion/(15)JosephusProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long int lli; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | // IBH Recursion 8 | // Josephus Problem | Game of Death in a circle | Execution in Circle 9 | 10 | int solve(vector &v, int idx, int k) { 11 | 12 | if (v.size() == 1) return v[0]; 13 | 14 | idx = ( idx + k ) % v.size(); 15 | v.erase(v.begin() + idx); 16 | solve(v, idx, k); 17 | 18 | } 19 | 20 | int main() { 21 | 22 | #ifndef ONLINE_JUDGE 23 | freopen("input.txt", "r", stdin); 24 | freopen("output.txt", "w", stdout); 25 | freopen("error.txt", "w", stderr) ; 26 | #endif 27 | 28 | int n, k; 29 | cin >> n >> k; 30 | k--; 31 | vectorv; 32 | for (int i = 1; i <= n; i++) 33 | v.push_back(i); 34 | cout << solve(v, 0, k); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Recursion/(2)SortArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | void Insert(vector&v, int temp) { 8 | 9 | if (v.size() == 0 || v[v.size() - 1] <= temp) { 10 | v.push_back(temp); 11 | return; 12 | } 13 | 14 | int val = v[v.size() - 1]; 15 | v.pop_back(); 16 | Insert(v, temp); 17 | v.push_back(val); 18 | 19 | return; 20 | } 21 | 22 | void Sort(vector&v) { 23 | 24 | if (v.size() == 1) return; //already sorted 25 | 26 | int temp = v[v.size() - 1]; 27 | v.pop_back(); 28 | Sort(v); 29 | Insert(v, temp); 30 | } 31 | 32 | 33 | int main() 34 | { 35 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 36 | 37 | #ifndef ONLINE_JUDGE 38 | freopen("input.txt", "r", stdin); 39 | freopen("output.txt", "w", stdout); 40 | #endif 41 | 42 | vector v = {1, 0, 5, 2}; 43 | Sort(v); 44 | 45 | for (int i = 0; i < v.size(); i++) cout << v[i] << " "; 46 | cout << endl; 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /Recursion/(3)SortStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | void Insert(stack&s, int temp) { 8 | 9 | if (s.size() == 0 || s.top() <= temp) { 10 | s.push(temp); 11 | return; 12 | } 13 | 14 | int val = s.top(); 15 | s.pop(); 16 | Insert(s, temp); 17 | s.push(val); 18 | 19 | } 20 | 21 | void Sort(stack&s) { 22 | 23 | if (s.size() == 1) return; //already sorted 24 | 25 | int temp = s.top(); 26 | s.pop(); 27 | Sort(s); 28 | Insert(s, temp); 29 | 30 | } 31 | 32 | 33 | int main() 34 | { 35 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 36 | 37 | #ifndef ONLINE_JUDGE 38 | freopen("input.txt", "r", stdin); 39 | freopen("output.txt", "w", stdout); 40 | #endif 41 | 42 | stack s; 43 | s.push(1); 44 | s.push(2); 45 | s.push(0); 46 | s.push(5); 47 | s.push(-1); 48 | 49 | Sort(s); 50 | 51 | while (!s.empty()) { cout << s.top() << " "; s.pop(); } 52 | cout << endl; 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /Recursion/(4)RemoveFromStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | //Remove mid position element from stack 8 | 9 | stack Remove(stack&s, int mid) { 10 | 11 | if (mid == 1) { //nothing to remove 12 | s.pop(); 13 | return s; 14 | } 15 | int temp = s.top(); 16 | s.pop(); 17 | Remove(s, mid - 1); 18 | s.push(temp); 19 | 20 | return s; 21 | } 22 | 23 | 24 | int main() 25 | { 26 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 27 | 28 | #ifndef ONLINE_JUDGE 29 | freopen("input.txt", "r", stdin); 30 | freopen("output.txt", "w", stdout); 31 | #endif 32 | 33 | stack s; 34 | s.push(1); 35 | s.push(2); 36 | s.push(0); 37 | s.push(5); 38 | s.push(-1); 39 | s.push(10); 40 | 41 | 42 | int mid = s.size() / 2 + 1; 43 | 44 | Remove(s, mid); 45 | 46 | while (!s.empty()) { cout << s.top() << " "; s.pop(); } 47 | cout << endl; 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /Recursion/(5)ReverseStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | //Reverse stack in O(1) space 8 | //We are only using rec call stack not any stack DS 9 | 10 | void Insert(stack&s, int temp) { 11 | 12 | if (s.size() == 0) { 13 | s.push(temp); 14 | return; 15 | } 16 | int val = s.top(); 17 | s.pop(); 18 | Insert(s, temp); 19 | s.push(val); 20 | 21 | return; 22 | 23 | } 24 | 25 | void Reverse(stack&s) { 26 | 27 | if (s.size() == 1) return ; //nothing to reverse 28 | 29 | int temp = s.top(); 30 | s.pop(); 31 | Reverse(s); 32 | Insert(s, temp); 33 | 34 | } 35 | 36 | 37 | int main() 38 | { 39 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 40 | 41 | #ifndef ONLINE_JUDGE 42 | freopen("input.txt", "r", stdin); 43 | freopen("output.txt", "w", stdout); 44 | #endif 45 | 46 | stack s; 47 | s.push(1); 48 | s.push(2); 49 | s.push(0); 50 | s.push(5); 51 | s.push(-1); 52 | s.push(10); 53 | 54 | Reverse(s); 55 | 56 | while (!s.empty()) { cout << s.top() << " "; s.pop(); } 57 | cout << endl; 58 | } 59 | 60 | 61 | -------------------------------------------------------------------------------- /Recursion/(6)KthSymbolinGrammer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | //Kth symbol in grammer [observation skills] 8 | //LeetCode 9 | 10 | // Grammer -> 11 | // if n=1 & k=1 [0] 12 | // 0 -> 01 13 | // 1 -> 10 14 | 15 | // -----> k=1 to so on 16 | // n=1 0 17 | // n=2 0 1 18 | // n=3 0 1 1 0 19 | // n=4 0 1 1 0 1 0 1 0 20 | 21 | // at each level total elements becomes twice and total ele at each level are 2^(n-1) 22 | 23 | //Output 0/1 bit at n,k location 24 | 25 | int solve(int n, int k) { 26 | 27 | int mid = pow(2, n - 1) / 2; 28 | 29 | if (n == 1 && k == 1) { 30 | return 0; 31 | } 32 | 33 | if (k <= mid) return solve(n - 1, k); 34 | else return !solve(n - 1, k - mid); 35 | } 36 | 37 | int main() 38 | { 39 | 40 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 41 | 42 | #ifndef ONLINE_JUDGE 43 | freopen("input.txt", "r", stdin); 44 | freopen("output.txt", "w", stdout); 45 | #endif 46 | 47 | int n, k; 48 | cin >> n >> k; 49 | 50 | cout << solve(n, k) << endl; 51 | 52 | } 53 | 54 | -------------------------------------------------------------------------------- /Recursion/(7)TOH.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | void TOH(int n, char S, char D, char H) { 8 | 9 | if (n == 1) { 10 | cout << "Move disk " << n << " from " << S << " to " << D << endl; 11 | return; 12 | } 13 | 14 | TOH(n - 1, S, H, D); 15 | cout << "Move disk " << n << " from " << S << " to " << D << endl; 16 | TOH(n - 1, H, D, S); 17 | 18 | } 19 | 20 | 21 | int main() 22 | { 23 | 24 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 25 | 26 | #ifndef ONLINE_JUDGE 27 | freopen("input.txt", "r", stdin); 28 | freopen("output.txt", "w", stdout); 29 | #endif 30 | 31 | int n; 32 | cin >> n; 33 | 34 | TOH(n, 'S', 'D', 'H'); 35 | 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Recursion/(8)PrintSubseq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | //Print subsets / powersets / subsequences 8 | 9 | void PrintSubseq(string ip, string op) { 10 | 11 | if (ip == "") { // i.e. we are at leaf node 12 | cout << op << endl; 13 | return; 14 | } 15 | 16 | PrintSubseq(ip.substr(1), op + ip[0]); 17 | PrintSubseq(ip.substr(1), op); 18 | 19 | } 20 | 21 | int main() 22 | { 23 | 24 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 25 | 26 | #ifndef ONLINE_JUDGE 27 | freopen("input.txt", "r", stdin); 28 | freopen("output.txt", "w", stdout); 29 | #endif 30 | 31 | string ip; 32 | cin >> ip; 33 | string op = ""; 34 | 35 | PrintSubseq(ip, op); 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Recursion/(9)UniqueSubsets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | //Print unique subsets / powersets / subsequences 8 | 9 | void PrintSubseq(string ip, string op, set &ans) { 10 | 11 | if (ip == "") { // i.e. we are at leaf node 12 | ans.insert(op); 13 | // cout << op << endl; 14 | return; 15 | } 16 | 17 | PrintSubseq(ip.substr(1), op + ip[0], ans); 18 | PrintSubseq(ip.substr(1), op, ans); 19 | 20 | } 21 | 22 | int main() 23 | { 24 | 25 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 26 | 27 | #ifndef ONLINE_JUDGE 28 | freopen("input.txt", "r", stdin); 29 | freopen("output.txt", "w", stdout); 30 | #endif 31 | 32 | string ip; 33 | cin >> ip; 34 | string op = ""; 35 | set ans; 36 | PrintSubseq(ip, op, ans); 37 | 38 | for (auto str : ans) cout << str << endl; 39 | 40 | } 41 | 42 | -------------------------------------------------------------------------------- /fibonacci/damora_fibonacci.py: -------------------------------------------------------------------------------- 1 | def Fibonacci(): 2 | statement = int(input("Please enter the number of Fibonacci numbers to generate: ")) 3 | i = 1 4 | fib_list = [] 5 | 6 | if statement == 0: 7 | fib_list = [] 8 | elif statement == 1: 9 | fib_list = [1] 10 | elif statement == 2: 11 | fib_list = [1, 1] 12 | elif statement > 2: 13 | fib_list = [1,1] 14 | while i < (statement -1): 15 | fib_list.append(fib_list[i]+fib_list[i-1]) 16 | i += 1 17 | 18 | print(fib_list) 19 | 20 | Fibonacci() -------------------------------------------------------------------------------- /fibonacci/fibonacci.cs: -------------------------------------------------------------------------------- 1 | cusing System; 2 | 3 | namespace Fibonacci 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Enter limit: "); 10 | calculateFibonacci(Int32.Parse(Console.ReadLine())); 11 | } 12 | 13 | static void calculateFibonacci (int input) 14 | { 15 | int a = 0; 16 | int b = 1; 17 | 18 | while (b <= input) 19 | { 20 | int auxiliar = a; 21 | a = b; 22 | b = auxiliar + a; 23 | Console.Write(a + " "); 24 | } 25 | } 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /fibonacci/fibonacci_recursive.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if n<=2: 3 | return 1 4 | else: 5 | return fibonacci(n-1) + fibonacci(n-2) 6 | 7 | n = int(input('Enter a number (greather than 2): ')) 8 | 9 | for val in range(1,n-1): 10 | print(fibonacci(val), end = ', ') 11 | -------------------------------------------------------------------------------- /gcd/gcd.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class GCDLCMMain { 4 | 5 | 6 | public static void main(String[] args) { 7 | Scanner input = new Scanner(System.in); 8 | 9 | System.out.println("Enter the two numbers: "); 10 | 11 | int number1 = input.nextInt(); 12 | int number2 = input.nextInt(); 13 | 14 | 15 | System.out.println("The GCD of two numbers is: " + gcd(number1, number2)); 16 | System.out.println("The LCM of two numbers is: " + lcm(number1, number2)); 17 | 18 | input.close(); 19 | 20 | } 21 | 22 | // Using Eucid algorithm for calculating gcd 23 | public static int gcd(int a,int b) 24 | { 25 | if(b==0) 26 | return a; 27 | else 28 | return gcd(b,a%b); 29 | } 30 | 31 | public static int lcm(int a,int b) 32 | { 33 | return a*b/(gcd(a,b)); 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /gcd/gcd.py: -------------------------------------------------------------------------------- 1 | # Finding HCF (GCD) and LCM using Recursive Function 2 | 3 | # Defining function 4 | 5 | def hcf(a,b): 6 | if b==0: 7 | return a 8 | else: 9 | return hcf(b, a%b) # this is recursion as hcf() calls itself 10 | 11 | # Reading numbers from user 12 | first = int(input('Enter first number: ')) 13 | second = int(input('Enter second number: ')) 14 | 15 | # Function call & displaying output HCF (GCD) 16 | print('HCF or GCD of %d and %d is %d' %(first, second, hcf(first, second))) 17 | print('LCM of %d and %d is %d' %(first, second, first*second/hcf(first, second))) -------------------------------------------------------------------------------- /pal.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | r=0 3 | while n>0: 4 | d=n%10 5 | r=r*10+d 6 | n=n/10 7 | if n==r: 8 | print (True) 9 | else: 10 | print (False) 11 | -------------------------------------------------------------------------------- /problems/Anagram/CheckTwoStringsAsAnagrams.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | ios_base::sync_with_stdio(false); 7 | cin.tie(NULL); 8 | cout.tie(NULL); 9 | 10 | string s, t; 11 | cin >> s >> t; 12 | 13 | 14 | int hash1[26], hash2[26]; 15 | memset(hash1, 0, sizeof(hash1)); 16 | memset(hash2, 0, sizeof(hash2)); 17 | 18 | for(char c : s) { 19 | hash1[c - 'a']++; 20 | } 21 | 22 | for(char c : t) { 23 | hash2[c - 'a']++; 24 | } 25 | 26 | bool flag = true; 27 | for(int i = 0;i < 26;i++) { 28 | if(hash1[i] != hash2[i]) { 29 | flag = false; 30 | break; 31 | } 32 | } 33 | 34 | if(flag) { 35 | cout << "True" << endl; 36 | } else { 37 | cout << "False" << endl; 38 | } 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /problems/Anagram/anagram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool areAnagram(string str1, string str2) 5 | { 6 | 7 | int n1 = str1.length(); 8 | int n2 = str2.length(); 9 | 10 | if (n1 != n2) 11 | return false; 12 | 13 | sort(str1.begin(), str1.end()); 14 | sort(str2.begin(), str2.end()); 15 | 16 | for (int i = 0; i < n1; i++) 17 | if (str1[i] != str2[i]) 18 | return false; 19 | 20 | return true; 21 | } 22 | 23 | 24 | int main() 25 | { 26 | string str1 = "abc"; 27 | string str2 = "cab"; 28 | if (areAnagram(str1, str2)) 29 | cout << "True"; 30 | else 31 | cout << "False"; 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /problems/Anagram/anagram_detection.java: -------------------------------------------------------------------------------- 1 | // JAVA program to detect anagrams 2 | import java.io.*; 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | public class anagram_detection { 7 | 8 | /* function to check if two strings are anagrams */ 9 | static boolean areAnagram(char[] str1, char[] str2) 10 | { 11 | // Obtain the lengths 12 | int s1 = str1.length; 13 | int s2 = str2.length; 14 | 15 | // Check length 16 | if (s1 != s2) 17 | return false; 18 | 19 | // Sort the strings 20 | Arrays.sort(str1); 21 | Arrays.sort(str2); 22 | 23 | // Compare sorted strings 24 | for (int i = 0; i < s1; i++) 25 | if (str1[i] != str2[i]) 26 | return false; 27 | 28 | return true; 29 | } 30 | 31 | /* Main function*/ 32 | public static void main(String args[]) 33 | { 34 | char str1[] = { 'w', 'e', 's', 't' }; 35 | char str2[] = { 't', 't', 'e', 'w' }; 36 | if (areAnagram(str1, str2)) 37 | System.out.println("The two strings are" 38 | + " anagram"); 39 | else 40 | System.out.println("The two strings are not" 41 | + " anagram"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /problems/Anagram/anagrams.c++: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define Chars 256 5 | bool Check(char* s1, char* s2) 6 | { 7 | 8 | int count[Chars] = { 0 }; 9 | int i; 10 | 11 | for (i = 0; s1[i] && s2[i]; i++) { 12 | count[s1[i]]++; 13 | count[s2[i]]--; 14 | } 15 | 16 | if (s1[i] || s2[i]) 17 | return false; 18 | 19 | // See if there is any non-zero value in count array 20 | for (i = 0; i < Chars ; i++) 21 | if (count[i]) 22 | return false; 23 | return true; 24 | } -------------------------------------------------------------------------------- /problems/Anagram/check_anagrams.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace ConsoleApp1 5 | { 6 | class check_anagrams 7 | { 8 | static void Main(string[] args) 9 | { 10 | Console.WriteLine("Enter two strings in two different lines: "); 11 | string a = Console.ReadLine(); 12 | string b = Console.ReadLine(); 13 | int[] a_frequency = new int[256]; 14 | int[] b_frequency = new int[256]; 15 | bool isAnagram = true; 16 | foreach (char c in a) 17 | { 18 | a_frequency[(int)c]++; 19 | } 20 | foreach (char c in b) 21 | { 22 | b_frequency[(int)c]++; 23 | } 24 | for(int i = 0; i < 256; i++) 25 | { 26 | if(a_frequency[i] != b_frequency[i]) 27 | { 28 | isAnagram = false; 29 | break; 30 | } 31 | } 32 | if (isAnagram) 33 | { 34 | Console.WriteLine(a + " and " + b + " are anagrams."); 35 | } 36 | else 37 | { 38 | Console.WriteLine(a + " and " + b + " are NOT anagrams."); 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /problems/Anagram/isAnagram.java: -------------------------------------------------------------------------------- 1 | boolean isAnagramSort(String string1, String string2) { 2 | if (string1.length() != string2.length()) { 3 | return false; 4 | } 5 | char[] a1 = string1.toCharArray(); 6 | char[] a2 = string2.toCharArray(); 7 | Arrays.sort(a1); 8 | Arrays.sort(a2); 9 | return Arrays.equals(a1, a2); 10 | } 11 | -------------------------------------------------------------------------------- /problems/Anagram/isAnagram.js: -------------------------------------------------------------------------------- 1 | function isAnagram( param_str1, param_str2 ) { 2 | 3 | // Strip all whitespace characters from both strings & convert to lowercase for comparison 4 | let str1 = param_str1.replace(/\s+/g, '').toLowerCase(); 5 | let str2 = param_str2.replace(/\s+/g, '').toLowerCase(); 6 | 7 | // If str1 equals str2, it's an anagram of itself 8 | if ( str1 === str2 ) { 9 | return true; 10 | } 11 | 12 | // If the length of the strings is not equal, they're not anagrams 13 | if ( str1.length !== str2.length ) { 14 | return false; 15 | } 16 | 17 | // Do split() on each word on each character; let JS sort the characters; then join() back into a string again 18 | str1 = str1.split("").sort().join(""); 19 | str2 = str2.split("").sort().join(""); 20 | 21 | // If the strings match each other now, they are anagrams of each other 22 | if ( str1 === str2 ) { 23 | return true; 24 | } 25 | 26 | // If we got all the way here, the strings are not anagrams 27 | return false; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /problems/Anagram/isAnagram.kt: -------------------------------------------------------------------------------- 1 | fun isAnagram(a: String, b: String): Boolean { 2 | return a.toSortedSet() == b.toSortedSet() 3 | } 4 | -------------------------------------------------------------------------------- /problems/Anagram/isAnagram.py: -------------------------------------------------------------------------------- 1 | def isAnagram(str1, str2): 2 | return sorted(str1) == sorted(str2) 3 | -------------------------------------------------------------------------------- /problems/Anagram/isAnagram?.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | ;Check weather the given two strings are anagrams of each other, i.e weather they contain the same letter. 3 | ; 4 | ;Example : 5 | ;Input: abc & cab //abc is anagrams with cab, bac, cab.. 6 | ;Output: True 7 | 8 | ;; string -> boolean 9 | ;; retruns true of given strings have the same characters 10 | 11 | ;; code 12 | ;(define (isAnagram? s1 s2) true) ; stub 13 | 14 | (define (isAnagram? s1 s2) 15 | (local [(define (isAnagram? s1 s2) ; helper function 16 | (cond 17 | [(and (empty? s1) (empty? s2)) true] ; basecase for recursion 18 | [else 19 | (and ; all the characters must match 20 | (equal? (first s1) (first s2)) 21 | (isAnagram? (rest s1) (rest s2)))]))] 22 | (isAnagram? (sort (string->list s1) (lambda (a b) (> (char->integer a) (char->integer b)))) ; turning the string into a 23 | (sort (string->list s2) (lambda (a b) (> (char->integer a) (char->integer b))))))) ; sorted list 24 | 25 | 26 | 27 | 28 | 29 | ;; testing examples 30 | ;(equal? (isAnagram? "" "") true) ; basecase 31 | ;(equal? (isAnagram? "abc" "cab") true) 32 | ;(equal? (isAnagram? "cat" "dog") false) -------------------------------------------------------------------------------- /problems/ReverseLineWordByWord: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class QuickSort { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner sc = new Scanner(System.in); 8 | 9 | String str = sc.nextLine(); 10 | String ans = ""; 11 | 12 | int spaces = 0, len = str.length()-1; 13 | 14 | while(len>=0) { 15 | while(len >= 0 && str.charAt(len) == ' ') { 16 | len--; 17 | spaces++; 18 | } 19 | int j = len; 20 | 21 | if(len<0) { break;} 22 | 23 | while(len >= 0 && str.charAt(len) != ' ') { 24 | len--; 25 | } 26 | 27 | if(ans.isEmpty()) { 28 | ans = ans.concat(str.substring(len+1,j+1)); 29 | 30 | }else { 31 | while(spaces >= 0) { 32 | if(spaces == 0) { 33 | ans = ans.concat(str.substring(len+1,j+1)); 34 | break; 35 | } 36 | ans = ans.concat(" "); 37 | spaces--; 38 | } 39 | spaces = 0; 40 | } 41 | } 42 | 43 | str = ans.toString(); 44 | System.out.println(str); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /problems/ToggleStringCharacters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int i; 7 | char str[101]; 8 | cin >> str; 9 | for(i = 0; str[i] != '\0'; i++) 10 | { 11 | if(str[i] >= 'A' && str[i] <= 'Z') 12 | { 13 | str[i] = str[i] + 32; 14 | } 15 | else if(str[i] >= 'a' && str[i] <= 'z') 16 | { 17 | str[i] = str[i] - 32; 18 | } 19 | else 20 | { 21 | str[i] = str[i]; 22 | } 23 | } 24 | cout << str << endl; 25 | return 0; 26 | } -------------------------------------------------------------------------------- /problems/armstrongNumber.js: -------------------------------------------------------------------------------- 1 | function isArmstrong (valueToCheck) { 2 | let digits = [] 3 | let numberOfDigits = 0 4 | let sum = 0 5 | let valueToCheckCopy = valueToCheck 6 | 7 | // we will extract all the digits from the number to be checked 8 | while (valueToCheckCopy > 0) { 9 | digits.push(valueToCheckCopy % 10) 10 | valueToCheckCopy = parseInt(valueToCheckCopy / 10) 11 | } 12 | // then we find the number of digits in the number 13 | numberOfDigits = digits.length 14 | 15 | // we compute the sum of the digits to the power number of digits 16 | digits.forEach(digit => { 17 | sum = sum + Math.pow(digit, numberOfDigits) 18 | }) 19 | 20 | return (sum === valueToCheck) 21 | } -------------------------------------------------------------------------------- /problems/first-duplicate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Returns first duplicated element. 3 | * @param {Array.} array 4 | * @returns {number} Duplicated element or `-1`. 5 | */ 6 | function firstDuplicate(array) { 7 | let seen = []; 8 | 9 | for (n of array){ 10 | if (seen.includes(n)){ 11 | return n; 12 | } else { 13 | seen.push(n); 14 | } 15 | } 16 | 17 | return -1; 18 | } 19 | 20 | module.exports = { 21 | firstDuplicate 22 | }; 23 | -------------------------------------------------------------------------------- /problems/firstDuplicate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int findFirstDuplicate(int arr[]) 4 | { 5 | int sizeOfArray=sizeof(arr)/sizeof(arr[0]); 6 | unordered_set store; 7 | for(int i=0;i>n; 22 | int arr[n]; 23 | for(int i=0;i>arr[i]; 26 | } 27 | cout< 2 | using namespace std; 3 | const int R = 5; 4 | const int C = 5; 5 | 6 | int findMaxSum(int mat[R][C]) 7 | { 8 | if (R<3 || C<3) 9 | return -1; 10 | 11 | int max_sum = INT_MIN; 12 | for (int i=0; i>num; 8 | dup=num; 9 | while(num) 10 | { 11 | rev=(rev*10)+(num%10); 12 | num/=10; 13 | } 14 | if(rev==dup) 15 | cout<<"Yes,It Is a Palindrome Number"; 16 | else 17 | cout<<"No,It Is not a Palindrome Number"; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /problems/palindrome/PalindromeNum.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int n, reversedN = 0, remainder, originalN; 4 | printf("Enter an integer: "); 5 | scanf("%d", &n); 6 | originalN = n; 7 | 8 | // reversed integer is stored in reversedN 9 | while (n != 0) { 10 | remainder = n % 10; 11 | reversedN = reversedN * 10 + remainder; 12 | n /= 10; 13 | } 14 | 15 | // palindrome if orignalN and reversedN are equal 16 | if (originalN == reversedN) 17 | printf("%d is a palindrome.", originalN); 18 | else 19 | printf("%d is not a palindrome.", originalN); 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /problems/palindrome/isIntegerPalindromeWithoutString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool solve(long int n) 5 | { 6 | long int orig_n = n; 7 | stackst; 8 | while(n > 0) 9 | { 10 | long int tmp = n%10; 11 | st.push(tmp); 12 | n = n/10; 13 | } 14 | n = orig_n; 15 | while(n > 0) 16 | { 17 | long int tmp = n%10; 18 | if(tmp != st.top()) 19 | return false; 20 | 21 | st.pop(); 22 | n = n/10; 23 | } 24 | return true; 25 | } 26 | 27 | int main() 28 | { 29 | long int n; 30 | cin>>n; 31 | 32 | if(solve(n)) 33 | cout<<"PALINDROME"< 0) { 7 | const lastDigit = x % 10 8 | reversed = (reversed * 10) + lastDigit 9 | x = (x / 10) | 0 10 | } 11 | return num === reversed 12 | } 13 | 14 | 15 | //Test case 16 | console.log(isPalindrome(121)) 17 | console.log(isPalindrome(221)) 18 | console.log(isPalindrome(5123215)) 19 | console.log(isPalindrome(12321)) 20 | console.log(isPalindrome(29378)) -------------------------------------------------------------------------------- /problems/palindrome/palindrome_checker.py: -------------------------------------------------------------------------------- 1 | def palindrome_checker(string): 2 | counter = {} 3 | for i in range(26): 4 | counter[chr(ord('a') + i)] = 0 5 | 6 | for s in string: 7 | counter[s] += 1 8 | 9 | odd = 0 10 | for c in counter: 11 | if counter[c] % 2 != 0: 12 | if odd == 0: 13 | odd = 1 14 | else: 15 | return False 16 | return True 17 | -------------------------------------------------------------------------------- /problems/palindrome/palindrome_detection.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | 4 | /** 5 | * Palindrome 6 | */ 7 | public class Palindrome { 8 | static boolean isPalindrome(String s) { 9 | 10 | // Left and right pointers pointing to the beginning and the end of the string 11 | 12 | int left = 0, right = s.length() - 1; 13 | 14 | while (left < right) { 15 | 16 | // If there is a mismatch 17 | 18 | if (s.charAt(left) != s.charAt(right)) 19 | return false; 20 | 21 | // Increment left pointer and decrement right pointer 22 | left++; 23 | right--; 24 | } 25 | return true; 26 | } 27 | 28 | public static void main(String[] args) { 29 | 30 | Scanner sc = new Scanner(System.in); 31 | 32 | String str = sc.nextLine(); //Input a string 33 | 34 | System.out.println(isPalindrome(str)); // Print whether the input string is palindrome or not 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /problems/prime/isPrime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | int num, flag = 0; 6 | 7 | printf("Enter a natural number: "); 8 | scanf("%d", &num); 9 | 10 | double sqrtResult = sqrt((double) num); 11 | 12 | for (int i=2; i <= sqrtResult; ++i){ 13 | if (num%i == 0){ 14 | flag = 1; 15 | break; 16 | } 17 | } 18 | 19 | if (flag == 1) { 20 | printf("%d is not a prime number\n", num); 21 | } else { 22 | printf("%d is a prime number\n", num); 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /problems/prime/isPrime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | ios_base::sync_with_stdio(false); 7 | cin.tie(NULL); 8 | cout.tie(NULL); 9 | 10 | int n; 11 | cin>>n; 12 | bool divided=false; 13 | if(n%2==0){ 14 | divided=true; 15 | } 16 | else{ 17 | int d=3; 18 | while(d*d>Number: ")))) -------------------------------------------------------------------------------- /problems/prime/prime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main (void) { 6 | float wurzelHeron = 0; 7 | float x = 0; 8 | 9 | int zahl = 0; 10 | int teiler = 0; 11 | int i; 12 | 13 | bool prim; 14 | 15 | printf("\nBitte geben Sie eine Zahl ein: "); 16 | scanf("%d",&zahl); 17 | if (zahl < 2) { 18 | printf("Das ist KEINE primzahl"); 19 | return (EXIT_SUCCESS); 20 | } 21 | 22 | x = (zahl + 1)/2; 23 | 24 | for (i = 0; i < 3; i++); { 25 | wurzelHeron = 0.5*(x+zahl/x); 26 | x = wurzelHeron; 27 | } 28 | 29 | int wurzel = wurzelHeron; 30 | 31 | prim = true; 32 | for (teiler = 2; teiler <= wurzel2; teiler++) { 33 | if (zahl%teiler == 0) { 34 | prim = false; 35 | } 36 | } 37 | 38 | if (prim == true) { 39 | printf("\n++++++++ BINGO ++++++++ \n\n %d ",zahl); 40 | } 41 | }else{ 42 | printf("\n++++++++ ZONK ++++++++ \n\n %d ",zahl); 43 | } 44 | 45 | 46 | return (EXIT_SUCCESS); 47 | } -------------------------------------------------------------------------------- /problems/reverseNumber/ReverseAnIntegerWithoutUsingString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int n; 7 | cin >> n; 8 | 9 | int result = 0; 10 | 11 | while(n != 0) { 12 | result = result * 10 + (n % 10); 13 | n /= 10; 14 | } 15 | 16 | cout << result << endl; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /problems/reverseNumber/reverse.py: -------------------------------------------------------------------------------- 1 | # Input number from the user 2 | N = int(input("Enter the number to be reversed ")) 3 | 4 | # Initiate value to null. R will store the value of the reverse of user input 5 | R = 0 6 | 7 | # Check using while loop 8 | 9 | while(N>0): 10 | #Logic 11 | remainder = N % 10 12 | R = (R * 10) + remainder 13 | N = N//10 14 | 15 | # Print the output 16 | print("The reverse number is: {}".format(R)) 17 | -------------------------------------------------------------------------------- /problems/reverseNumber/reverseNumber.java: -------------------------------------------------------------------------------- 1 | public static int reverseNumber(int num) 2 | { 3 | int ans=0; 4 | while(num>0){ 5 | int remainder=num%10; 6 | ans=ans*10+remainder; 7 | num=num/10; 8 | } 9 | return ans; 10 | } 11 | -------------------------------------------------------------------------------- /problems/reverseNumber/reverseNumber.js: -------------------------------------------------------------------------------- 1 | function reverseNumber(num = 0) { 2 | var ans = 0; 3 | while (num > 0) { 4 | var remainder = num % 10; 5 | ans = ans * 10 + remainder; 6 | num = Math.floor(num / 10); 7 | } 8 | 9 | return ans; 10 | } 11 | 12 | // console.log(reverseNumber(123456)); 13 | 14 | var num = prompt("Enter a number to reverse: "); 15 | console.log(reverseNumber(num)); 16 | 17 | -------------------------------------------------------------------------------- /problems/reverseNumber/reversenumber.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephremdeme/data-structure-and-algorithms/336f3f25bf536307273ce7318877555ba4122f2c/problems/reverseNumber/reversenumber.py -------------------------------------------------------------------------------- /problems/reverse_list.py: -------------------------------------------------------------------------------- 1 | def reverse_list(items): 2 | start = 0 3 | end = len(items) - 1 4 | 5 | while start < end: 6 | items[start], items[end] = items[end], items[start] 7 | start += 1 8 | end -= 1 9 | 10 | return items 11 | 12 | 13 | if __name__ == '__main__': 14 | items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 15 | print(reverse_list(items)) 16 | -------------------------------------------------------------------------------- /problems/swap_case.py: -------------------------------------------------------------------------------- 1 | def swap_case(s): 2 | letter = "" 3 | for i in s: 4 | if i.isalpha(): 5 | if i.islower(): 6 | j = i.upper() 7 | letter += j 8 | else: 9 | j = i.lower() 10 | letter += j 11 | else: 12 | letter += i 13 | 14 | return letter 15 | 16 | 17 | s = input("Enter String: ") 18 | print(swap_case(s)) -------------------------------------------------------------------------------- /queue/Queue.java: -------------------------------------------------------------------------------- 1 | package arrraylistqueue; 2 | import java.util.ArrayList; 3 | import java.util.Scanner; 4 | class queue 5 | { 6 | int data; 7 | int size=0; 8 | Scanner sb=new Scanner(System.in); 9 | ArrayList arrli = new ArrayList(); 10 | void enque() 11 | { 12 | System.out.println("Enter data to enque:"); 13 | data=sb.nextInt(); 14 | arrli.add(data); 15 | size++; 16 | } 17 | void deque() 18 | { 19 | if(size>0) 20 | { 21 | size--; 22 | arrli.remove(0); 23 | System.out.println("New array list is:"+arrli); 24 | } 25 | else 26 | { 27 | System.out.println("queue is empty"); 28 | } 29 | } 30 | } 31 | public class arraylist { 32 | public static void main(String args[]) 33 | { 34 | queue q=new queue(); 35 | int ch; 36 | int ans; 37 | Scanner sb=new Scanner(System.in); 38 | do 39 | { 40 | System.out.println("1.enqueue\n2.deque\n\nEnter your choice"); 41 | ch=sb.nextInt(); 42 | switch(ch) 43 | { 44 | case 1: 45 | q.enque(); 46 | break; 47 | case 2: 48 | q.deque(); 49 | break; 50 | } 51 | System.out.println("Do you wanna continue?\n1 for yes rest for no\n"); 52 | ans=sb.nextInt(); 53 | }while(ans==1); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /queue/circularQueue_using_Array.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 100 3 | int queue[MAX]; 4 | int front=-1,rear=-1; 5 | void enqueue(int data){ 6 | rear = (rear+1)%MAX; 7 | if(front==rear){ 8 | printf("\nQUEUE OVERFLOW\n"); 9 | if(rear==0) rear = MAX-1; 10 | else rear = rear-1; 11 | return; 12 | } 13 | if(front==-1) front=0; 14 | queue[rear]=data; 15 | } 16 | int dequeue(){ 17 | if(front==-1){ 18 | printf("\nQUEUE UNDERFLOW! NO ITEMS IN THE QUEUE\n"); 19 | return -1; 20 | } 21 | int data = queue[front]; 22 | if(front==rear){ 23 | front=-1; 24 | rear=-1; 25 | }else{ 26 | front = (front+1)%MAX; 27 | } 28 | return data; 29 | } 30 | void printQueue(){ 31 | int temp = front; 32 | if(temp==-1){ 33 | printf("\nLMAO! NOTHING TO DISPLAY\n"); 34 | return; 35 | } 36 | if(rear>=temp){ 37 | while(temp<=rear){ 38 | printf("%d ",queue[temp]); 39 | ++temp; 40 | } 41 | }else{ 42 | if(temp>rear){ 43 | while(temp= start: 4 | mid = start + (end- start)//2 5 | # If element is present at the middle 6 | if arr[mid] == x: 7 | return mid 8 | # If element is smaller than mid 9 | elif arr[mid] > x: 10 | return binarySearchAppr(arr, start, mid-1, x) 11 | # Else the element greator than mid 12 | else: 13 | return binarySearchAppr(arr, mid+1, end, x) 14 | else: 15 | # Element is not found in the array 16 | return -1 17 | 18 | 19 | if __name__ == "__main__": 20 | arr = sorted(['t','u','t','o','r','i','a','l']) 21 | x ='r' 22 | result = binarySearchAppr(arr, 0, len(arr)-1, x) 23 | if result != -1: 24 | print ("Element is present at index "+str(result)) 25 | else: 26 | print ("Element is not present in array") -------------------------------------------------------------------------------- /searching/Binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int array[100], i, n, search, temp, j; 6 | printf("\n Enter the size of array: \n"); 7 | scanf("%d", &n); 8 | 9 | printf("\n Enter %d array elements: \n", n); 10 | for (i =0; i< n; i++) 11 | { 12 | scanf("%d", &array[i]); 13 | } 14 | 15 | printf("\n Enter the element you want to search via binary Search \n"); 16 | scanf("%d", &search); 17 | 18 | int first = 0, last = n-1, middle; 19 | middle = (first + last)/2; 20 | 21 | //sorting the array 22 | for (i = 0; i < n; i++) 23 | { 24 | for (j = i+1; j < n; j++) 25 | { 26 | temp = array[i]; 27 | array[i] = array[j]; 28 | } 29 | } 30 | 31 | while (first <= last) 32 | { 33 | if (array[middle] < search) 34 | { 35 | first = middle + 1; 36 | } 37 | else if (array[middle] == search) 38 | { 39 | printf("\n %d found at %d position", search, middle+1); 40 | break; 41 | } 42 | else 43 | { 44 | last = middle - 1; 45 | } 46 | middle = (first + last)/2; 47 | } 48 | if (first > last) 49 | { 50 | printf("\n %d is not present in the array \n", search); 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /searching/Linear Search.py: -------------------------------------------------------------------------------- 1 | def linearSearch(arr, x): 2 | 3 | for i in range(len(arr)): 4 | 5 | if arr[i] == x: 6 | return i 7 | 8 | return -1 9 | 10 | if __name__ == "__main__": 11 | arr = [0,1,2,3,4,5,6,7,8,9] 12 | x = 6 13 | print("Value is present at index number: {}".format(linearSearch(arr,x))) -------------------------------------------------------------------------------- /searching/LinearSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class linearSearch{ 4 | static int linearSearch(int[] arr, int key){ 5 | for(int i=0;i 7 | using namespace std; 8 | 9 | // A recursive binary search function. It returns 10 | // location of x in given array arr[l..r] is present, 11 | // otherwise -1 12 | int binarySearch(int arr[], int l, int r, int x) 13 | { 14 | if (r >= l) 15 | { 16 | int mid = l + (r - l) / 2; 17 | 18 | // If the element is present at the middle 19 | // itself 20 | if (arr[mid] == x) 21 | return mid; 22 | 23 | // If element is smaller than mid, then 24 | // it can only be present in left subarray 25 | if (arr[mid] > x) 26 | return binarySearch(arr, l, mid - 1, x); 27 | 28 | // Else the element can only be present 29 | // in right subarray 30 | return binarySearch(arr, mid + 1, r, x); 31 | } 32 | 33 | // We reach here when element is not 34 | // present in array 35 | return -1; 36 | } 37 | 38 | int main(void) 39 | { 40 | 41 | int arr[] = {2, 3, 4, 10, 40}; 42 | int x = 10; 43 | int n = sizeof(arr) / sizeof(arr[0]); 44 | int result = binarySearch(arr, 0, n - 1, x); 45 | (result == -1) ? cout << "Element is not present in array" 46 | : cout << "Element is present at index " << result; 47 | return 0; 48 | } -------------------------------------------------------------------------------- /searching/binarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr = [], key) { 2 | var left = 0, 3 | right = arr.length - 1; // left index and right index of the array 4 | while (left <= right) { 5 | var middle = Math.floor((right + left) / 2); 6 | if (arr[middle] == key) return middle; 7 | else if (key > arr[middle]) { 8 | left = middle + 1; 9 | } else { 10 | right = middle - 1; 11 | } 12 | } 13 | 14 | return -1; 15 | } 16 | 17 | console.log(binarySearch([1, 2, 3, 4, 5, 6, 7], 0)); 18 | -------------------------------------------------------------------------------- /searching/linearSearch.java: -------------------------------------------------------------------------------- 1 | public class LinearSearch{ 2 | public static int linearSearch(int[] arr, int key){ 3 | for(int i=0;i 6 | #include 7 | using namespace std; 8 | 9 | int search(int arr[], int n, int x) 10 | { 11 | int i; 12 | for (i = 0; i < n; i++) 13 | if (arr[i] == x) 14 | return i; 15 | return -1; 16 | } 17 | 18 | int main(void) 19 | { 20 | 21 | int searchKey; 22 | int numOfElements; 23 | cin >> numOfElements; 24 | int arr[numOfElements]; 25 | for(int i=0;i> arr[i]; 27 | } 28 | cin >> searchKey; 29 | 30 | int result = search(arr, numOfElements, searchKey); 31 | (result == -1)? cout<<"Element is not present in array" : cout<<"Element is present at index " < 2 | using namespace std; 3 | 4 | // Function to perform Ternary Search 5 | int ternarySearch(int l, int r, int key, int ar[]) 6 | { 7 | if (r >= l) { 8 | 9 | int mid1 = l + (r - l) / 3; 10 | int mid2 = r - (r - l) / 3; 11 | 12 | if (ar[mid1] == key) 13 | return mid1; 14 | 15 | if (ar[mid2] == key) 16 | return mid2; 17 | 18 | if (key < ar[mid1]) 19 | return ternarySearch(l, mid1 - 1, key, ar); 20 | else if (key > ar[mid2]) 21 | return ternarySearch(mid2 + 1, r, key, ar); 22 | else 23 | return ternarySearch(mid1 + 1, mid2 - 1, key, ar); 24 | } 25 | return -1; 26 | } 27 | int main() 28 | { 29 | int l, r, p, key; 30 | 31 | int arr[] = { 1, 2, 3, 4, 6, 10, 10, 15, 18, 19, 20 }; 32 | l = 0; 33 | r = 12; 34 | key = 5; 35 | p = ternarySearch(l, r, key, arr); 36 | cout << "Index of " << key << " is " << p << endl; 37 | key = 20; 38 | p = ternarySearch(l, r, key, arr); 39 | 40 | 41 | cout << "Index of " << key 42 | << " is " << p << endl; 43 | } 44 | -------------------------------------------------------------------------------- /searching/ternary_search.py: -------------------------------------------------------------------------------- 1 | # Python3 program to illustrate 2 | # recursive approach to ternary search 3 | import math as mt 4 | 5 | 6 | def ternarySearch(l, r, key, ar): 7 | 8 | if (r >= l): 9 | 10 | 11 | mid1 = l + (r - l) //3 12 | mid2 = r - (r - l) //3 13 | 14 | 15 | if (ar[mid1] == key): 16 | return mid1 17 | 18 | if (ar[mid2] == key): 19 | return mid2 20 | 21 | 22 | if (key < ar[mid1]): 23 | 24 | return ternarySearch(mid1 + 1, r, key, ar) 25 | 26 | elif (key > ar[mid2]): 27 | 28 | return ternarySearch(mid2 + 1, r, key, ar) 29 | 30 | else: 31 | 32 | 33 | return ternarySearch(mid1 + 1, 34 | mid2 - 1, key, ar) 35 | 36 | 37 | return -1 38 | -------------------------------------------------------------------------------- /sorting-algorithms/BogoSort.java: -------------------------------------------------------------------------------- 1 | // Java Program to implement BogoSort 2 | public class BogoSort 3 | { 4 | // Sorts array a[0..n-1] using Bogo sort 5 | void bogoSort(int[] a) 6 | { 7 | // if array is not sorted then shuffle the 8 | // array again 9 | while (isSorted(a) == false) 10 | shuffle(a); 11 | } 12 | 13 | // To generate permuatation of the array 14 | void shuffle(int[] a) 15 | { 16 | // Math.random() returns a double positive 17 | // value, greater than or equal to 0.0 and 18 | // less than 1.0. 19 | for (int i=1; i <= n; i++) 20 | swap(a, i, (int)(Math.random()*i)); 21 | } 22 | 23 | // Swapping 2 elements 24 | void swap(int[] a, int i, int j) 25 | { 26 | int temp = a[i]; 27 | a[i] = a[j]; 28 | a[j] = temp; 29 | } 30 | 31 | // To check if array is sorted or not 32 | boolean isSorted(int[] a) 33 | { 34 | for (int i=1; i num[i+1]): 9 | return False 10 | return True 11 | 12 | def bogoSort(num): 13 | n = len(num) 14 | while(isSorted(num)==False): 15 | global counter 16 | shuffle(num) 17 | counter += 1 18 | 19 | def shuffle(num): 20 | n = len(num) 21 | for i in range (0,n): 22 | r = random.randint(0,n-1) 23 | num[i],num[r] = num[r],num[i] 24 | 25 | # Shuffle Counter 26 | counter = 0 27 | 28 | # Array/list size 29 | print("Enter the size of list/array : ") 30 | size = int(input()) 31 | num = [] 32 | 33 | for i in range(0,size): 34 | print("Enter element number ", i+1) 35 | added = int(input()) 36 | num.append(added) 37 | 38 | bogoSort(num) 39 | print("Sorted number (increasing) : ") 40 | print(num) 41 | print("Number of shuffle : ", counter) 42 | 43 | -------------------------------------------------------------------------------- /sorting-algorithms/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package array; 2 | import java.util.*; 3 | public class BubbleSort { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner sc= new Scanner(System.in); 8 | int n=sc.nextInt(); 9 | int a[]= new int[n]; 10 | boolean sorted= true; 11 | for(int i=0; i<=n-1; i++) { 12 | 13 | for(int j=0; j<=n-2-i ; j++) { 14 | 15 | if(a[j+1]=pivot] 8 | return quicksort(less)+[pivot]+quicksort(higher) 9 | print(quicksort([1,2,3,3,0])) 10 | -------------------------------------------------------------------------------- /sorting-algorithms/RecursiveBubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubbleSort(int arr[], int n){ 5 | if (n == 1) 6 | return; 7 | 8 | for (int i=0; i arr[i+1]) 10 | arr[i] = arr[i] + arr[i+1]; 11 | arr[i+1] = arr[i] - arr[i+1]; 12 | arr[i] = arr[i] - arr[i+1]; 13 | bubbleSort(arr, n-1); 14 | } 15 | void main() { 16 | int arr[] = {14,1,13,7,50,1,23,20,60}; 17 | int n = sizeof(arr)/sizeof(arr[0]); 18 | bubbleSort(arr, n); 19 | cout << "Sorted Sequence is: "; 20 | for(int i = 0; i arr[i+1]){ 12 | int temp = arr[i]; 13 | arr[i] = arr[i+1]; 14 | arr[i+1] = temp; 15 | } 16 | 17 | bubbleSort(arr, n-1); 18 | } 19 | 20 | public static void main(String[] args){ 21 | 22 | int arr[] = {14,1,13,7,50,12,60}; 23 | bubbleSort(arr, arr.length); 24 | System.out.println("Sorted array is: "); 25 | System.out.println(Arrays.toString(arr)); 26 | } 27 | } -------------------------------------------------------------------------------- /sorting-algorithms/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | public class SelectionSort { 4 | 5 | public static void main(String[] args) { 6 | int a[]= {2,4,-1,15,9,6,-19,100}; 7 | int n=a.length; 8 | 9 | for(int i=0 ; i<=n-1 ; i++) { 10 | 11 | int minIndex=i; 12 | for(int j=i ; j<=n-1; j++) { 13 | 14 | if(a[j] 2 | using namespace std; 3 | 4 | /* 5 | bogosort just generates a random shuffle of the array until it finds a sorted shuffle. 6 | time complexity: O(n!) 7 | */ 8 | 9 | bool is_not_sorted(int arr[], int size) { 10 | for (int i = 0; i < size; i++) { 11 | if (i && arr[i-1] > arr[i]) { 12 | return true; 13 | } 14 | } 15 | return false; 16 | } 17 | 18 | void shuffle(int arr[], int size) { 19 | for (int i = 0; i < size; i++) { 20 | swap(arr[i], arr[rand() % size]); 21 | } 22 | for (int i = 0; i < size; i++) { 23 | cout << arr[i] << ' '; 24 | } 25 | cout << endl; 26 | } 27 | 28 | int bogo_sort(int arr[], int size) { 29 | int i = 0; 30 | while (is_not_sorted(arr, size)) { 31 | shuffle(arr, size); 32 | i += 1; 33 | } 34 | return i; 35 | } 36 | 37 | int main() { 38 | int test_size = 6; 39 | int test_arr[test_size] = {4, 5, 1, 3, 6, 2}; 40 | int shuffle_counter = bogo_sort(test_arr, test_size); 41 | cout << "Number of shuffles: " << shuffle_counter << endl; 42 | for (int i: test_arr) { 43 | cout << i << ' '; 44 | } 45 | cout << endl; 46 | return 0; 47 | } -------------------------------------------------------------------------------- /sorting-algorithms/bubbleSort.js: -------------------------------------------------------------------------------- 1 | function swap(array, index1, index2) { 2 | var temp = array[index1]; 3 | array[index1] = array[index2]; 4 | array[index2] = temp; 5 | } 6 | 7 | function bubbleSort(array){ 8 | for(let i = 0, arrayLength = array.length; iarray[j]){ 11 | swap(array,i, j); 12 | } 13 | } 14 | } 15 | return array; 16 | } 17 | 18 | console.log(bubbleSort([2,5, 6, 1, 3, 7, 9, 4])); 19 | -------------------------------------------------------------------------------- /sorting-algorithms/bubbleSort.py: -------------------------------------------------------------------------------- 1 | #Bubble Sort 2 | # The bubble sort works by comparing each item in the list with the item next to it and 3 | # swapping them if required. 4 | 5 | arr = [4, 7, 3, 5, 2,9, 6, 8, 1] 6 | 7 | for i in range(len(arr)-1): 8 | for j in range(len(arr)-i-1): 9 | if(arr[j]>arr[j+1]): 10 | arr[j], arr[j+1] = arr[j+1], arr[j] 11 | print(arr) # just to show steps during sorting 12 | 13 | print(arr) # sorted arrays 14 | 15 | -------------------------------------------------------------------------------- /sorting-algorithms/bubble_sort.c: -------------------------------------------------------------------------------- 1 | // C implementation of Bubble sort 2 | #include 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | // Bubble Sort implementation 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | for (i = 0; i < n-1; i++) 16 | 17 | for (j = 0; j < n-i-1; j++) 18 | if (arr[j] > arr[j+1]) 19 | swap(&arr[j], &arr[j+1]); 20 | } 21 | 22 | // Print an array function 23 | void printArray(int arr[], int size) 24 | { 25 | int i; 26 | for (i=0; i < size; i++) 27 | printf("%d ", arr[i]); 28 | printf("\n"); 29 | } 30 | 31 | int main() 32 | { 33 | int arr[] = {85, 14, 12, 2, 65, 90}; 34 | int n = sizeof(arr)/sizeof(arr[0]); 35 | bubbleSort(arr, n); 36 | printf("Sorted array: \n"); 37 | printArray(arr, n); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /sorting-algorithms/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Bubble sort 2 | #include 3 | using namespace std; 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | // Bubble Sort function 13 | void bubbleSort(int arr[], int n) 14 | { 15 | int i, j; 16 | for (i = 0; i < n-1; i++) 17 | 18 | for (j = 0; j < n-i-1; j++) 19 | if (arr[j] > arr[j+1]) 20 | swap(&arr[j], &arr[j+1]); 21 | } 22 | 23 | // Print array function 24 | void printArray(int arr[], int size) 25 | { 26 | int i; 27 | for (i = 0; i < size; i++) 28 | cout << arr[i] << " "; 29 | cout << endl; 30 | } 31 | 32 | int main() 33 | { 34 | int arr[] = {58, 28, 12, 34, 92, 1, 90}; 35 | int n = sizeof(arr)/sizeof(arr[0]); 36 | bubbleSort(arr, n); 37 | cout<<"Sorted array: \n"; 38 | printArray(arr, n); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /sorting-algorithms/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(array): 2 | n = len(array) 3 | swapped = True 4 | while swapped: 5 | swapped = False 6 | for j in range(n-1): 7 | if array[j] > array[j + 1]: 8 | array[j], array[j+1] = array[j+1], array[j] 9 | swapped = True 10 | 11 | return array 12 | 13 | 14 | if __name__ == '__main__': 15 | array = [2, 3, 4, 40, 100, 20, 10, 5, 130] 16 | print('Unsorted array: {}'.format(array)) 17 | print('Sorted array: {}'.format(bubble_sort(array))) -------------------------------------------------------------------------------- /sorting-algorithms/count_sort.py: -------------------------------------------------------------------------------- 1 | def countSort(arr): 2 | 3 | output = [0 for i in range(len(arr))] 4 | 5 | 6 | count = [0 for i in range(256)] 7 | 8 | ans = ["" for _ in arr] 9 | 10 | for i in arr: 11 | count[ord(i)] += 1 12 | 13 | 14 | for i in range(256): 15 | count[i] += count[i-1] 16 | 17 | for i in range(len(arr)): 18 | output[count[ord(arr[i])]-1] = arr[i] 19 | count[ord(arr[i])] -= 1 20 | 21 | for i in range(len(arr)): 22 | ans[i] = output[i] 23 | return ans 24 | 25 | arr = input() 26 | ans = countSort(arr) 27 | print("Sorted character array is % s" %("".join(ans))) 28 | 29 | # This code is contributed by Jay Dulera 30 | -------------------------------------------------------------------------------- /sorting-algorithms/countingsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void countingsort(vector &v, int n) { 6 | int largest_element_of_vector = *max_element(v.begin(), v.end()); 7 | 8 | vector hash(largest_element_of_vector + 1, 0); 9 | 10 | for(int i = 0;i < n;i++) { 11 | hash[v[i]]++; 12 | } 13 | 14 | int idx = 0; 15 | for(int i = 0;i <= largest_element_of_vector;i++) { 16 | while(hash[i] > 0) { 17 | v[idx] = i; 18 | hash[i]--; 19 | idx++; 20 | } 21 | } 22 | } 23 | 24 | int main() { 25 | int n; 26 | cin >> n; 27 | 28 | vector v(n); 29 | for(int i = 0;i < n;i++) { 30 | cin >> v[i]; 31 | } 32 | 33 | countingsort(v, n); 34 | 35 | for(int i = 0;i < n;i++) { 36 | cout << v[i] << " "; 37 | } 38 | cout << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /sorting-algorithms/heapsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | using namespace std; 5 | 6 | 7 | void heapify(int n,int p[],int i) 8 | { 9 | //intilizing root 10 | int root = i; 11 | int left = i*2+1; 12 | int right = i*2+2; 13 | 14 | 15 | //finding largest element 16 | if(p[right]>p[root]&& rightp[root]&& left=0;i--){ 37 | heapify(n,p,i); 38 | } 39 | //deleting element from heap 40 | for(int i= n-1;i>0;i--) 41 | { 42 | //swaping to the root 43 | int temp= p[0]; 44 | p[0] = p[i]; 45 | p[i] = temp; 46 | //now heapify again 47 | heapify(i,p,0); 48 | } 49 | 50 | } 51 | 52 | int main() 53 | { 54 | int n; 55 | cout <<"enter the size of array"; 56 | cin >>n; 57 | int p[n]; 58 | for(int i=0;i>p[i]; 61 | } 62 | 63 | heap_sort(p,n); 64 | 65 | for(int i=0;i= 0 && arr[j] > temp) { 19 | arr[j + 1] = arr[j]; 20 | // keep iterating till the predicessor becomes smaller than the current item 21 | j--; 22 | } 23 | 24 | // insert it at the right place 25 | arr[j + 1] = temp; 26 | } 27 | return arr; 28 | } 29 | 30 | var arr = [4, 1, 3, 2, 1]; 31 | 32 | console.log(insertionSort(arr)) 33 | 34 | // This has the time complexity of O(n^2) 35 | -------------------------------------------------------------------------------- /sorting-algorithms/insertionSort.py: -------------------------------------------------------------------------------- 1 | 2 | # The insertion sort works just like its name suggests—it inserts each item into its proper 3 | # place in the final list 4 | 5 | arr = [4, 7, 3, 5, 2,9, 6, 8, 1] 6 | for i in range(1, len(arr)): 7 | temp = arr[i] 8 | j = i 9 | while((j > 0) and (arr[j-1] > temp)): 10 | arr[j] = arr[j-1] 11 | j = j-1 12 | arr[j] = temp 13 | print(arr, i) # just to show what happens in each iterations 14 | 15 | 16 | print(arr) #[1, 2, 3, 4, 5, 6, 7, 8, 9] 17 | 18 | -------------------------------------------------------------------------------- /sorting-algorithms/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | void display(int *array, int size) 5 | { 6 | for (int i = 0; i < size; i++) 7 | cout << array[i] << " "; 8 | cout << endl; 9 | } 10 | void insertionSort(int *array, int size) 11 | { 12 | int key, j; 13 | for (int i = 1; i < size; i++) 14 | { 15 | key = array[i]; //take value 16 | j = i; 17 | while (j > 0 && array[j - 1] > key) 18 | { 19 | array[j] = array[j - 1]; 20 | j--; 21 | } 22 | array[j] = key; 23 | } 24 | } 25 | int main() 26 | { 27 | int n; 28 | cout << "Enter the number of elements: "; 29 | cin >> n; 30 | int arr[n]; //create an array with given number of elements 31 | cout << "Enter elements:" << endl; 32 | for (int i = 0; i < n; i++) 33 | { 34 | cin >> arr[i]; 35 | } 36 | cout << "Array before Sorting: "; 37 | display(arr, n); 38 | insertionSort(arr, n); 39 | cout << "Array after Sorting: "; 40 | display(arr, n); 41 | } 42 | -------------------------------------------------------------------------------- /sorting-algorithms/insertion_sort_rs.rs: -------------------------------------------------------------------------------- 1 | /// Insertion sort. 2 | 3 | pub fn insertion_sort(arr: &mut [i32]) { 4 | for i in 1..arr.len() { 5 | let mut j = i; 6 | while j > 0 && arr[j - 1] > arr[j] { 7 | arr.swap(j - 1, j); 8 | j -= 1; 9 | } 10 | } 11 | } 12 | 13 | /// Binary insertion sort. 14 | 15 | /// Binary insertion sort is a insertion sort variant that utilizes binary 16 | 17 | /// search to reduce comparisons in a normal insertion sort. 18 | 19 | pub fn binary_insertion_sort(arr: &mut [i32]) { 20 | for i in 1..arr.len() { 21 | let val = arr[i]; 22 | let mut j = i; 23 | let pos = arr[..i].binary_search(&val).unwrap_or_else(|pos| pos); 24 | // Swap all elements until specific position. 25 | while j > pos { 26 | arr.swap(j - 1, j); 27 | j -= 1; 28 | } 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | 34 | mod base { 35 | use super::*; 36 | base_cases!(insertion_sort); 37 | } 38 | 39 | #[cfg(test)] 40 | 41 | mod binary_insertion { 42 | use super::*; 43 | base_cases!(binary_insertion_sort); 44 | } -------------------------------------------------------------------------------- /sorting-algorithms/mergeSort.js: -------------------------------------------------------------------------------- 1 | function merge(leftA, rightA) { 2 | var results = [], 3 | leftIndex = 0, 4 | rightIndex = 0; 5 | 6 | while (leftIndex < leftA.length && rightIndex < rightA.length) { 7 | if (leftA[leftIndex] < rightA[rightIndex]) { 8 | results.push(leftA[leftIndex++]); 9 | } else { 10 | results.push(rightA[rightIndex++]); 11 | } 12 | } 13 | var leftRemains = leftA.slice(leftIndex), 14 | rightRemains = rightA.slice(rightIndex); 15 | // add remaining to resultant array 16 | return results.concat(leftRemains).concat(rightRemains); 17 | } 18 | 19 | function mergeSort(array) { 20 | if (array.length < 2) { 21 | return array; // Base case: array is now sorted since it's 22 | } 23 | var midpoint = Math.floor(array.length / 2), 24 | leftArray = array.slice(0, midpoint), 25 | rightArray = array.slice(midpoint); 26 | 27 | return merge(mergeSort(leftArray), mergeSort(rightArray)); 28 | } 29 | console.log( mergeSort([6, 9, 81, 23, 4, 2, 3])); // [1, 2, 3, 4, 6, 23] 30 | console.log( mergeSort([-6, -9, -81, -23, -4, 2, 3])); // [1, 2, 3, 4, 6, 23] 31 | -------------------------------------------------------------------------------- /sorting-algorithms/mergeSort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(alist, start, end): 2 | '''Sorts the list from indexes start to end - 1 inclusive.''' 3 | if end - start > 1: 4 | mid = (start + end)//2 5 | merge_sort(alist, start, mid) 6 | merge_sort(alist, mid, end) 7 | merge_list(alist, start, mid, end) 8 | 9 | def merge_list(alist, start, mid, end): 10 | left = alist[start:mid] 11 | right = alist[mid:end] 12 | k = start 13 | i = 0 14 | j = 0 15 | while (start + i < mid and mid + j < end): 16 | if (left[i] <= right[j]): 17 | alist[k] = left[i] 18 | i = i + 1 19 | else: 20 | alist[k] = right[j] 21 | j = j + 1 22 | k = k + 1 23 | if start + i < mid: 24 | while k < end: 25 | alist[k] = left[i] 26 | i = i + 1 27 | k = k + 1 28 | else: 29 | while k < end: 30 | alist[k] = right[j] 31 | j = j + 1 32 | k = k + 1 33 | 34 | 35 | alist = input('Enter the list of numbers: ').split() 36 | alist = [int(x) for x in alist] 37 | merge_sort(alist, 0, len(alist)) 38 | print('Sorted list: ', end='') 39 | print(alist) -------------------------------------------------------------------------------- /sorting-algorithms/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void mergesort(int* a,int low,int high){ 5 | if(high==low) 6 | return; 7 | int mid = low+(high-low)/2; 8 | mergesort(a,low,mid); 9 | mergesort(a,mid+1,high); 10 | int n1 = mid-low+1,n2 = high-mid; 11 | int left[n1],right[n2]; 12 | for(int i=low;i<=mid;i++){ 13 | left[i-low] = a[i]; 14 | } 15 | for(int i=mid+1;i<=high;i++){ 16 | right[i-mid-1] = a[i]; 17 | } 18 | int i=0,j=0,k=low; 19 | while(i>n; 39 | int a[n]; 40 | for(int i=0;i>a[i]; 42 | } 43 | mergesort(a,0,n-1); 44 | for(int i=0;i arr[num] : 9 | num = index 10 | 11 | return num 12 | 13 | def flipArr(arr, index): 14 | 15 | begin = 0 16 | 17 | while begin < index : 18 | temp = arr[begin] 19 | arr[begin] = arr[index] 20 | arr[index] = temp 21 | begin = begin + 1 22 | index = index - 1 23 | 24 | 25 | def pancakeSort(arr, size): 26 | 27 | for index in range(size-1, 0 ,-1): 28 | 29 | index1 = maxNum(arr, index) 30 | 31 | if index1 != index : 32 | flipArr(arr, index1) 33 | 34 | flipArr(arr, index) 35 | 36 | 37 | def main(): 38 | arr = [56, 47, 9, 46, 70, 9, 25, 36] 39 | 40 | size = len(arr) 41 | 42 | print("Unsorted Array: ", arr) 43 | 44 | pancakeSort(arr, size) 45 | 46 | print("Sorted Array: ", arr) 47 | 48 | if __name__ == "__main__": 49 | main() -------------------------------------------------------------------------------- /sorting-algorithms/quicksort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void quicksort(int* a,int low,int high){ 5 | if(low>=high) 6 | return; 7 | int i=low-1,j=low; 8 | while(j>n; 25 | int a[n]; 26 | for(int i=0;i>a[i]; 28 | } 29 | quicksort(a,0,n-1); 30 | for(int i=0;i [a] -> [a] 2 | qsort [] = [] 3 | qsort (x:xs) = qsort lesser ++ [x] ++ qsort greater 4 | where 5 | lesser = filter (< x) xs 6 | greater = filter (>= x) xs 7 | 8 | main :: IO () 9 | main = do 10 | print $ quicksort $ reverse [1..10] -------------------------------------------------------------------------------- /sorting-algorithms/selection-sort.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Selection sort is fairly simple. Assume the left part of your array is 4 | sorted and right part is unsorted. Inititally the sorted(left) part is 5 | empty. Now select the smallest element from the unsorted(right) part and 6 | swap it with the first element of the unsorted(right) part. Now this element 7 | is sorted, move to the next iteration and repeat without touch the sorted(left) 8 | part. 9 | 10 | */ 11 | function selectionSort(arr) { 12 | for (let i = 0; i < arr.length; i++) { 13 | let firstOfUnsorted = arr[i]; 14 | 15 | // find the index of the smallest element in the unsorted part 16 | let minIndex = i; 17 | for (let j = i + 1; j < arr.length; j++) { 18 | if (arr[minIndex] > arr[j]) { 19 | minIndex = j; 20 | } 21 | } 22 | 23 | // swapping the minimum with first element of unsorted part 24 | arr[i] = arr[minIndex]; 25 | arr[minIndex] = firstOfUnsorted; 26 | } 27 | return arr; 28 | } 29 | 30 | // This has the time complexity of O(n^2) 31 | -------------------------------------------------------------------------------- /sorting-algorithms/selectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /* 6 | The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) 7 | from unsorted part and putting it at the beginning. 8 | */ 9 | 10 | void swap(int *xp, int *yp) 11 | { 12 | int temp = *xp; 13 | *xp = *yp; 14 | *yp = temp; 15 | } 16 | 17 | void selectionSort(int arr[], int n) 18 | { 19 | int k; // index of min element 20 | for(int i=0; i 2 | using namespace std; 3 | 4 | int shellSort(int arr[], int n) 5 | { 6 | for (int g = n/2; g > 0; g/= 2) 7 | { 8 | 9 | for (int i = g; i < n; i += 1) 10 | { 11 | 12 | int temp = arr[i]; 13 | 14 | int j; 15 | for (j = i; j >= g && arr[j - g] > temp; j -= g) 16 | arr[j] = arr[j - g]; 17 | 18 | 19 | arr[j] = temp; 20 | } 21 | } 22 | return 0; 23 | } 24 | 25 | void printArray(int arr[], int n) 26 | { 27 | for (int i=0; i 0): 7 | for i in range(gap, n): 8 | temp = arr[i] 9 | j = i 10 | while(j >= gap and arr[j - gap] > temp): 11 | arr[j] = arr[j - gap] 12 | j -= gap 13 | 14 | arr[j] = temp 15 | gap //= 2 16 | 17 | 18 | if __name__ == "__main__": 19 | arr = [int(item) for item in input().split()] 20 | ShellSort(arr) 21 | print(arr) -------------------------------------------------------------------------------- /stack/(1)NGR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | vector v; 8 | stack s; 9 | 10 | // Nearest Greater to Right - NGR 11 | void solve(int a[], int n) { 12 | 13 | for (int i = n - 1; i >= 0; i--) { 14 | 15 | if (s.size() == 0) { 16 | v.push_back(-1); 17 | } 18 | 19 | else if (s.size() > 0 && s.top() > a[i]) { 20 | v.push_back(s.top()); 21 | } 22 | else if (s.size() > 0 && s.top() <= a[i]) { 23 | while (s.size() > 0 && s.top() <= a[i]) { 24 | s.pop(); 25 | } 26 | 27 | if (s.size() == 0) v.push_back(-1); 28 | else v.push_back(s.top()); 29 | } 30 | 31 | s.push(a[i]); 32 | 33 | } 34 | 35 | } 36 | 37 | 38 | int main() 39 | { 40 | 41 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 42 | 43 | #ifndef ONLINE_JUDGE 44 | freopen("input.txt", "r", stdin); 45 | freopen("output.txt", "w", stdout); 46 | #endif 47 | 48 | int n; 49 | cin >> n; 50 | int a[n]; 51 | 52 | for (int i = 0; i < n; i++) cin >> a[i]; 53 | solve(a, n); 54 | 55 | reverse(v.begin(), v.end()); 56 | for (int i = 0; i < n; i++) cout << v[i] << " "; 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /stack/(10)MinStackO(1).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Min stack implementation without using ss stack i.e. in O(1) space 5 | 6 | stack s; 7 | int minEle; 8 | 9 | void push(int a) { 10 | 11 | if (s.size() == 0) { s.push(a); minEle = a; } 12 | 13 | else { 14 | 15 | if (a >= minEle) { 16 | s.push(a); 17 | } 18 | else { 19 | s.push(2 * a - minEle); 20 | minEle = a; 21 | } 22 | 23 | } 24 | return; 25 | } 26 | 27 | int pop() { 28 | int ans; 29 | if (s.size() == 0) return -1; 30 | 31 | else { 32 | if (s.top() >= minEle) { 33 | ans = s.top(); 34 | s.pop(); 35 | } 36 | else { 37 | minEle = 2 * minEle - s.top(); 38 | ans = s.top(); 39 | s.pop(); 40 | } 41 | } 42 | 43 | return ans; 44 | } 45 | 46 | int top() { 47 | 48 | if (s.size() == 0) return -1; 49 | 50 | else { 51 | if (s.top() <= minEle) return minEle; 52 | else return s.top(); 53 | } 54 | } 55 | 56 | int getMIN() { 57 | 58 | return s.size() == 0 ? -1 : minEle; 59 | } 60 | 61 | 62 | int main() { 63 | 64 | #ifndef ONLINE_JUDGE 65 | freopen("input.txt", "r", stdin); 66 | freopen("output.txt", "w", stdout); 67 | #endif 68 | 69 | push(18); 70 | push(19); 71 | push(29); 72 | push(15); 73 | pop(); 74 | push(16); 75 | pop(); 76 | pop(); 77 | 78 | cout << getMIN() << endl; 79 | 80 | } 81 | -------------------------------------------------------------------------------- /stack/(2)NGL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | vector v; 8 | stack s; 9 | 10 | // Nearest Greater to left - NGL 11 | void solve(int a[], int n) { 12 | 13 | for (int i = 0; i < n; i++) { 14 | 15 | if (s.size() == 0) { 16 | v.push_back(-1); 17 | } 18 | 19 | else if (s.size() > 0 && s.top() > a[i]) { 20 | v.push_back(s.top()); 21 | } 22 | else if (s.size() > 0 && s.top() <= a[i]) { 23 | while (s.size() > 0 && s.top() <= a[i]) { 24 | s.pop(); 25 | } 26 | 27 | if (s.size() == 0) v.push_back(-1); 28 | else v.push_back(s.top()); 29 | } 30 | 31 | s.push(a[i]); 32 | 33 | } 34 | 35 | } 36 | 37 | 38 | int main() 39 | { 40 | 41 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 42 | 43 | #ifndef ONLINE_JUDGE 44 | freopen("input.txt", "r", stdin); 45 | freopen("output.txt", "w", stdout); 46 | #endif 47 | 48 | int n; 49 | cin >> n; 50 | int a[n]; 51 | 52 | for (int i = 0; i < n; i++) cin >> a[i]; 53 | solve(a, n); 54 | 55 | // reverse(v.begin(), v.end()); 56 | for (int i = 0; i < n; i++) cout << v[i] << " "; 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /stack/(3)NSR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | vector v; 8 | stack s; 9 | 10 | // Nearest Smaller to Right - NSR 11 | void solve(int a[], int n) { 12 | 13 | for (int i = n - 1; i >= 0 ; i--) { 14 | 15 | if (s.size() == 0) { 16 | v.push_back(-1); 17 | } 18 | 19 | else if (s.size() > 0 && s.top() < a[i]) { 20 | v.push_back(s.top()); 21 | } 22 | else if (s.size() > 0 && s.top() >= a[i]) { 23 | while (s.size() > 0 && s.top() >= a[i]) { 24 | s.pop(); 25 | } 26 | 27 | if (s.size() == 0) v.push_back(-1); 28 | else v.push_back(s.top()); 29 | } 30 | 31 | s.push(a[i]); 32 | 33 | } 34 | 35 | } 36 | 37 | 38 | int main() 39 | { 40 | 41 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 42 | 43 | #ifndef ONLINE_JUDGE 44 | freopen("input.txt", "r", stdin); 45 | freopen("output.txt", "w", stdout); 46 | #endif 47 | 48 | int n; 49 | cin >> n; 50 | int a[n]; 51 | 52 | for (int i = 0; i < n; i++) cin >> a[i]; 53 | solve(a, n); 54 | 55 | reverse(v.begin(), v.end()); 56 | for (int i = 0; i < n; i++) cout << v[i] << " "; 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /stack/(4)NSL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | vector v; 8 | stack s; 9 | 10 | // Nearest Smaller to Left - NSL 11 | void solve(int a[], int n) { 12 | 13 | for (int i = 0; i < n; i++) { 14 | 15 | if (s.size() == 0) { 16 | v.push_back(-1); 17 | } 18 | 19 | else if (s.size() > 0 && s.top() < a[i]) { 20 | v.push_back(s.top()); 21 | } 22 | else if (s.size() > 0 && s.top() >= a[i]) { 23 | while (s.size() > 0 && s.top() >= a[i]) { 24 | s.pop(); 25 | } 26 | 27 | if (s.size() == 0) v.push_back(-1); 28 | else v.push_back(s.top()); 29 | } 30 | 31 | s.push(a[i]); 32 | 33 | } 34 | 35 | } 36 | 37 | 38 | int main() 39 | { 40 | 41 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 42 | 43 | #ifndef ONLINE_JUDGE 44 | freopen("input.txt", "r", stdin); 45 | freopen("output.txt", "w", stdout); 46 | #endif 47 | 48 | int n; 49 | cin >> n; 50 | int a[n]; 51 | 52 | for (int i = 0; i < n; i++) cin >> a[i]; 53 | solve(a, n); 54 | 55 | // reverse(v.begin(), v.end()); 56 | for (int i = 0; i < n; i++) cout << v[i] << " "; 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /stack/(5)StockSpan.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | #define mod 1000000007 5 | #define endl "\n" 6 | 7 | //Stock Span Problem 8 | vector v; 9 | stack> s; 10 | 11 | // Nearest Greater to Left - NGL 12 | void solve(int a[], int n) { 13 | 14 | for (int i = 0; i < n; i++) { 15 | 16 | if (s.size() == 0) { 17 | v.push_back(-1); 18 | } 19 | 20 | else if (s.size() > 0 && s.top().first > a[i]) { 21 | v.push_back(s.top().second); 22 | } 23 | else if (s.size() > 0 && s.top().first <= a[i]) { 24 | while (s.size() > 0 && s.top().first <= a[i]) { 25 | s.pop(); 26 | } 27 | 28 | if (s.size() == 0) v.push_back(-1); 29 | else v.push_back(s.top().second); 30 | } 31 | 32 | s.push({a[i], i}); 33 | 34 | } 35 | 36 | } 37 | 38 | 39 | int main() 40 | { 41 | 42 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 43 | 44 | #ifndef ONLINE_JUDGE 45 | freopen("input.txt", "r", stdin); 46 | freopen("output.txt", "w", stdout); 47 | #endif 48 | 49 | int n; 50 | cin >> n; 51 | int a[n]; 52 | 53 | for (int i = 0; i < n; i++) cin >> a[i]; 54 | solve(a, n); 55 | 56 | // reverse(v.begin(), v.end()); 57 | for (int i = 0; i < n; i++) cout << i - v[i] << " "; 58 | 59 | } 60 | 61 | -------------------------------------------------------------------------------- /stack/(8)RainwaterTrap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Rainwater trapping (total trapped water) 5 | 6 | int main() { 7 | 8 | #ifndef ONLINE_JUDGE 9 | freopen("input.txt", "r", stdin); 10 | freopen("output.txt", "w", stdout); 11 | #endif 12 | 13 | int n; 14 | cin >> n; 15 | int a[n]; 16 | 17 | for (int i = 0; i < n; i++) { 18 | cin >> a[i]; 19 | } 20 | 21 | int maxL[n]; 22 | int maxR[n]; 23 | 24 | maxL[0] = a[0]; 25 | maxR[n - 1] = a[n - 1]; 26 | 27 | for (int i = 1; i < n; i++) { 28 | maxL[i] = max(maxL[i - 1], a[i]); 29 | } 30 | 31 | for (int i = n - 2; i >= 0; i--) { 32 | maxR[i] = max(maxR[i + 1], a[i]); 33 | } 34 | 35 | int ans = 0; 36 | for (int i = 0; i < n; i++) { 37 | ans = ans + min(maxL[i], maxR[i]) - a[i]; 38 | } 39 | 40 | cout << ans << endl; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /stack/(9)MinStackO(n).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Min stack implementation using ss stack 5 | 6 | stack s; 7 | stack ss; //supporting stack 8 | 9 | void push(int a) { 10 | 11 | s.push(a); 12 | if (ss.size() == 0 || a <= ss.top()) { 13 | ss.push(a); 14 | } 15 | return; 16 | } 17 | 18 | int pop() { 19 | 20 | int val = s.top(); 21 | s.pop(); 22 | 23 | if (ss.top() == val) { 24 | ss.pop(); 25 | } 26 | 27 | return val; 28 | } 29 | 30 | int getMIN() { 31 | 32 | return ss.size() == 0 ? -1 : ss.top(); 33 | } 34 | 35 | 36 | int main() { 37 | 38 | #ifndef ONLINE_JUDGE 39 | freopen("input.txt", "r", stdin); 40 | freopen("output.txt", "w", stdout); 41 | #endif 42 | 43 | push(18); 44 | push(19); 45 | push(29); 46 | push(15); 47 | pop(); 48 | push(16); 49 | pop(); 50 | pop(); 51 | 52 | cout << getMIN() << endl; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /stack/Stack.java: -------------------------------------------------------------------------------- 1 | 2 | public class Stack { 3 | private int top; 4 | private int max; 5 | private int stack[]; 6 | 7 | 8 | Stack(int max) { 9 | top = -1; 10 | this.max = max; 11 | stack = new int[this.max]; 12 | } 13 | 14 | int top() { 15 | if(!isEmpty()) 16 | return stack[top]; 17 | else { 18 | System.out.println("stack empty"); 19 | return -1; 20 | } 21 | 22 | } 23 | 24 | 25 | boolean push(int data) { 26 | if(isFull()) { 27 | System.out.println("StackOverflow"); 28 | return false; 29 | } 30 | stack[++top]=data; 31 | return true; 32 | } 33 | 34 | boolean isFull() { 35 | if(top==(max-1)) 36 | return true; 37 | return false; 38 | } 39 | 40 | boolean isEmpty() { 41 | if(top<0) 42 | return true; 43 | else 44 | return false; 45 | } 46 | 47 | int pop() { 48 | if(isEmpty()) { 49 | System.out.println("StackEmpty"); 50 | return -1; 51 | } 52 | int data = stack[top]; 53 | top--; 54 | return data; 55 | } 56 | } 57 | 58 | public class Main { 59 | 60 | public static void main(String[] args) { 61 | Stack stack = new Stack(5); 62 | stack.push(1); 63 | System.out.println(stack.top()); 64 | System.out.println(stack.pop()); 65 | stack.push(2); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /stack/stack.go: -------------------------------------------------------------------------------- 1 | // Package stack provides an array implementation 2 | // of stack data structure 3 | package stack 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | // Stack definition 10 | type Stack struct { 11 | top int 12 | data []interface{} 13 | } 14 | 15 | // Push an int onto the stack 16 | func (s *Stack) Push(x interface{}) { 17 | s.data = append(s.data, x) 18 | s.top++ 19 | } 20 | 21 | // Pop removes the top element from the stack 22 | func (s *Stack) Pop() interface{} { 23 | if s.top < 0 { 24 | fmt.Println("The stack is empty.") 25 | } 26 | 27 | s.top-- 28 | temp := s.data[s.top] 29 | s.data = s.data[:len(s.data)-1] 30 | return temp 31 | } 32 | 33 | // Size returns the length of data 34 | func (s Stack) Size() int { 35 | return len(s.data) 36 | } 37 | 38 | // Allows print the stack's content 39 | func (s Stack) String() string { 40 | var str string 41 | for i := 0; i < s.top; i++ { 42 | str = str + fmt.Sprintf("[ %d: %v ]", i, s.data[i]) 43 | } 44 | 45 | return str 46 | } 47 | -------------------------------------------------------------------------------- /stack/stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self._data = [] 4 | self.size = 0 5 | 6 | def push(self, value, *args): 7 | self._data.append(value) 8 | for item in args: 9 | self._data.append(item) 10 | self.size += 1 11 | 12 | def pop(self): 13 | self._data.pop(-1) 14 | self.size -= 1 15 | 16 | def peek(self): 17 | return self._data[-1] 18 | 19 | def printStack(self): 20 | return ('[ ' + ', '.join(map(lambda item: str(item), self._data)) + ']') 21 | 22 | myStack = Stack(); 23 | myStack.push(5) 24 | myStack.push(10) 25 | myStack.push(89) 26 | print("Peek:", myStack.peek()) 27 | myStack.pop() 28 | print("Peek:", myStack.peek()) 29 | print(myStack.printStack()) 30 | -------------------------------------------------------------------------------- /stack/stack_using_array.c: -------------------------------------------------------------------------------- 1 | /* A basic Stack implementation in C using Array, with the following functionalities implemented: 2 | -Push operation 3 | -Pop operation 4 | -Display stack 5 | 6 | 7 | This implementation is done for max 100 elements only, you can increase it for changing the value of MAX 8 | */ 9 | 10 | #include 11 | #define MAX 100 12 | 13 | //Push operation in the stack , which inserts the elements in the stack 14 | void push(int data,int *stack, int *top){ 15 | if(*top==MAX-1){ // Condition for, Stack is full 16 | printf("\nSTACK OVERFLOW\n"); 17 | return; 18 | } 19 | stack[++(*top)] = data; 20 | } 21 | 22 | //Pop operation in the stack , whitch delete the elements from the stack 23 | int pop(int *top, int *stack){ 24 | if(*top==-1){ // Condition for, Stack is empty 25 | printf("\nSTACK UNDERFLOW\n"); 26 | return -1; 27 | } 28 | return stack[(*top)--]; 29 | } 30 | 31 | //Display Stack 32 | void displayStack(int *stack,int top){ 33 | while(top>=0){ 34 | printf("%d ",*(stack+top)); 35 | --top; 36 | } 37 | printf("\n"); 38 | } 39 | int main(){ 40 | int stack[MAX]; // Array 41 | int top=-1; 42 | push(1,stack,&top); 43 | push(2,stack,&top); 44 | push(3,stack,&top); 45 | push(5,stack,&top); 46 | displayStack(stack,top); 47 | int data = pop(&top,stack); 48 | data = pop(&top,stack); 49 | displayStack(stack,top); 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /tree/BFS.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import defaultdict 3 | 4 | 5 | class Graph: 6 | 7 | def __init__(self): 8 | 9 | 10 | self.graph = defaultdict(list) 11 | 12 | 13 | def addEdge(self,u,v): 14 | self.graph[u].append(v) 15 | self.graph[v].append(u) 16 | 17 | 18 | def BFS(self, s): 19 | 20 | 21 | visited = [False] * (len(self.graph)) 22 | 23 | 24 | queue = [] 25 | 26 | 27 | queue.append(s) 28 | visited[s] = True 29 | 30 | while queue: 31 | 32 | 33 | s = queue.pop(0) 34 | print (s, end = " ") 35 | 36 | for i in self.graph[s]: 37 | if visited[i] == False: 38 | queue.append(i) 39 | visited[i] = True 40 | 41 | 42 | g = Graph() 43 | TotalVertexs = int(input("Enter Total Vertexs: \n")) 44 | TotalEdges = int(input("Enter Total Edges: \n")) 45 | 46 | for i in range(TotalEdges): 47 | x, y = input("Enter two space seperated Conected Vertex: \n").split() 48 | g.addEdge(int(x),int(y)) 49 | 50 | 51 | print ("Following is Breadth First Traversal" 52 | " (starting from vertex 0)") 53 | g.BFS(0) 54 | 55 | # This code is contributed by Amar Shankar 56 | 57 | -------------------------------------------------------------------------------- /tree/DFS.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import defaultdict 3 | 4 | 5 | class Graph: 6 | 7 | def __init__(self): 8 | 9 | 10 | self.graph = defaultdict(list) 11 | 12 | 13 | def addEdge(self,u,v): 14 | self.graph[u].append(v) 15 | self.graph[v].append(u) 16 | 17 | 18 | def BFS(self, s): 19 | 20 | 21 | visited = [False] * (len(self.graph)) 22 | 23 | 24 | queue = [] 25 | 26 | 27 | queue.append(s) 28 | visited[s] = True 29 | 30 | while queue: 31 | 32 | 33 | s = queue.pop(0) 34 | print (s, end = " ") 35 | 36 | for i in self.graph[s]: 37 | if visited[i] == False: 38 | queue.append(i) 39 | visited[i] = True 40 | 41 | 42 | g = Graph() 43 | TotalVertexs = int(input("Enter Total Vertexs: \n")) 44 | TotalEdges = int(input("Enter Total Edges: \n")) 45 | 46 | for i in range(TotalEdges): 47 | x, y = input("Enter two space seperated Conected Vertex: \n").split() 48 | g.addEdge(int(x),int(y)) 49 | 50 | 51 | print ("Following is Depth First Traversal" 52 | " (starting from vertex 0)") 53 | g.BFS(0) 54 | 55 | # This code is contributed by Amar Shankar 56 | 57 | -------------------------------------------------------------------------------- /tree/fenwicktree.py: -------------------------------------------------------------------------------- 1 | def theupdate(index, a, tree, value): 2 | # index is index to be theupdated, a is input array / list, tree is BIT array, value is value to be added to original 3 | # number at index location 4 | add = value 5 | n = len(a) 6 | while index0): 16 | ans += tree[index] 17 | index = index - (index & (-index)) 18 | return ans 19 | 20 | #Get the user input 21 | n = int(input("Number of Elements in array: ")) 22 | inputArray = list(map(int, input("Elements in array: ").split())) 23 | inputArray.insert(0,0) # insert dummy node to have 1-based indexing 24 | 25 | #Initialise Binary Indexed Tree to 0's considering that input array is all 0's 26 | BIT = [] 27 | for i in range(0, n): 28 | BIT.append(0) 29 | 30 | # Now we will construct actual BIT 31 | # The 4th parameter is always an additional value which is to be added to element at index location 32 | # since we have considered input array as 0 earlier (while initialising BIT), for updating, we will pass actual 33 | # value 34 | for i in range(1, n): 35 | theupdate(i, inputArray, BIT, inputArray[i]) -------------------------------------------------------------------------------- /tree/suffixtree.py: -------------------------------------------------------------------------------- 1 | #inputting the string 2 | s=input("enter a word\n") 3 | l=len(s) #length of word 4 | res=[s+'0',] 5 | c=1 6 | for i in range(l-1): 7 | s=s[1:]+str(c) 8 | res.append(s) 9 | c+=1 10 | sl=len(s) 11 | s=s[:sl-1] 12 | rp=[] 13 | res.sort() 14 | for j in res: 15 | rp.append(int(j[-1])) 16 | 17 | print(rp) 18 | 19 | 20 | --------------------------------------------------------------------------------