├── .DS_Store ├── Algorithms ├── BinarySearch ├── Brian Kernighan’s Algorithm.py ├── Bubble_sort.cpp ├── CreateHeap.cpp ├── Deletion_in_Array.cpp ├── Diagnolmatrix.cpp ├── Find_middle_of_a_linkedlist.cpp ├── Floyd_Warshall.cpp ├── FractionalKnapsack.cpp ├── GCDalgo.java ├── Greedyalgo_coinchange.cpp ├── HeapSort.c ├── Heapify.cpp ├── InsertHeap.cpp ├── Insertion_sort.cpp ├── KadanesAlgo.java ├── Kruskal'sMinSpanningTree.cpp ├── Linear_Search.cpp ├── LowerTriangularMatrix.cpp ├── Merge_Sort-Iterative.c ├── Merge_Sort-Recursive.c ├── Merge_Sort.js ├── Merge_Sort_Algo.java ├── Merge_Sort_using_linked_list.cpp ├── Merge_Two_Arrays.cpp ├── Mergesort.cpp ├── PrimsMinSpanningTree.cpp ├── Quick_sort.cpp ├── Quicksort.cpp ├── README.md ├── Radixsort.cpp ├── RemoveDuplicatesFromaSortedLinkedList.cpp ├── Reverse_Array.cpp ├── Tower Of Hanoi.cpp ├── Z-Function.cpp ├── binary search.cpp ├── binary_search_Recursive.cpp ├── bresenham.py ├── circular queue.c ├── duplicate_elements_1.cpp ├── duplicate_elements_using_hash.cpp ├── heap_sort.cpp ├── insertion-sort.cpp ├── job_sequencing.cpp ├── kadane_algo.cpp ├── kth largest element in array.cpp ├── linkedList.cpp ├── merge_sort_C++.cpp ├── mergesort.py ├── missingelement.cpp ├── missingusinghash.cpp ├── queue_implementation.cpp ├── remove_duplicates_in_sorted_array.cpp ├── selectionSort.cpp ├── shellsort.cpp └── stack_implementation.cpp ├── CompanywiseSolution ├── ADOBE │ └── Linked_List │ │ ├── question.md │ │ └── solution.cpp ├── Amazon │ ├── Bit Manipulation │ │ ├── 2unique_numbers.cpp │ │ ├── 3unique_numbers.cpp │ │ ├── Count set bits in a integer.cpp │ │ ├── copy_set_bits_in_range.cpp │ │ ├── count_setbits_from_1_to_n.cpp │ │ ├── divide_integer_by_2.cpp │ │ └── numbers_bits_to_be_flipped.cpp │ ├── Dynamic Programming │ │ └── Minimum sum partition │ │ │ ├── CoinChange-dp.cpp │ │ │ ├── question.md │ │ │ └── solution.cpp │ ├── Equilibrium Point │ │ ├── Equilibrium.java │ │ └── question.md │ ├── Find Duplicates in array │ │ ├── question.txt │ │ └── solution.java │ ├── Max and Second Max │ │ ├── MaxSecondMax.java │ │ └── question.md │ └── check_for_BST │ │ ├── questions.txt │ │ └── solution.cpp ├── Morgan Stanley │ ├── Maximum Contigous Sum │ │ ├── Question.txt │ │ └── Solution.java.java │ └── String to Lower Case │ │ ├── Question.java.txt │ │ └── Solution.java.java ├── README.md └── deshaw │ ├── question.txt │ └── search_in_a_sortedarray.cpp ├── Competitive programming ├── .DS_Store ├── C# │ ├── FindElementInArray.cs │ └── README.md ├── C++ │ ├── ADACRA.cpp │ ├── Arrays_Left_Rotation.cpp │ ├── BuyStockAndSell │ ├── Ceiling Sum.cpp │ ├── Codeforces_1560B.cpp │ ├── DYNAMIC PROGRAMMING │ │ ├── Min steps to 1.cpp │ │ └── Readme.md │ ├── FLOW017.cpp │ ├── Factorial_calculator.cpp │ ├── FakeGCD.cpp │ ├── HS08TEST.cpp │ ├── InfixToPostfixUsingSTLStack.cpp │ ├── Kindergarten_Adventures.cpp │ ├── LazySegmentedTree.cpp │ ├── MajorityElementInarray │ ├── Maximum Subarray Sum │ ├── Move all zeroes to end │ ├── Move the elements.cpp │ ├── Permutation Minimization by Deque.c │ ├── PostfixEvaluation.cpp │ ├── Print Subsets of Array.cpp │ ├── Print all Codes - String(C++)) │ ├── README.md │ ├── Reverse_a_number.cpp │ ├── Search an element in sorted and rotated array.cpp │ ├── Shuffling Parities │ │ └── SHUFFLIN.cpp │ ├── Subarray With 0 sum │ ├── Symmetric_Tree.cpp │ ├── Tree.cpp │ ├── Trie.cpp │ ├── Twins.cpp │ ├── Union of Two Sorted Arrays.cpp │ ├── Vanya and Lanterns.cpp │ ├── databse.cpp │ ├── decimal_to_binary.cpp │ ├── extended_balanced_parenthesis_using_STL.cpp │ ├── generate_pattern.cpp │ ├── inverted_pattern.cpp │ ├── majority_element.cpp │ ├── median_of_2_sorted_arrays.cpp │ ├── parenthesismatching.cpp │ ├── stackLinkedList.cpp │ └── triplet sum to a given value ├── C │ ├── ArmstrongNumber.c │ ├── Find Remainder.c │ ├── Matrix multiplication.c │ ├── Merge sort.c │ ├── Queus.c │ ├── README.md │ ├── Reflection.c │ ├── Searching for specific number in 1D array.c │ ├── Stacks.c │ └── matrix-addition.c ├── JAVA │ ├── 0001spiral_traversal_2d.java │ ├── Binary_Tree_to_DLL.java │ ├── Counting Sort.java │ ├── Longest_Harmonious_Subsequence.java │ ├── MergeSort.java │ ├── PriorityQueue.java │ ├── README.md │ ├── Recursive_Bubble_Sort.java │ ├── Split_Array_Largest_Sum.java │ └── longest_rep_sub_sequence.java ├── JS │ └── README.md ├── PYTHON │ ├── .DS_Store │ ├── FAKESWAP.py │ ├── Fibonacci.py │ ├── Find an Element in an array.py │ ├── Frequent_WORD.py │ ├── N_Queen.py │ ├── README.md │ ├── SUDOKU.py │ ├── Special Numbers │ │ └── Auto_Bio.py │ ├── Tic-Tac-Toe.py │ ├── knight_moves.py │ └── maxprofit.py └── README.md └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drishyadamodaran/hacktoberfest2021_CP/5154a57d7453121b903eb4f485579db6c2c909fc/.DS_Store -------------------------------------------------------------------------------- /Algorithms/BinarySearch: -------------------------------------------------------------------------------- 1 | //srishti1302 2 | #include 3 | #define COMPARE(x,y) ( (x)<(y)?-1:(x)==(y)? 0 :1 ) 4 | int binsearch(int a[20],int k,int left,int right) 5 | { 6 | 7 | if(left 2 | using namespace std; 3 | 4 | //Bubble sort : swap two elements walaa technique 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | int arr[n]; 10 | for(int i=0;i>arr[i]; 12 | } 13 | 14 | int counter = 1; 15 | while(counterarr[i+1]){ 18 | if(arr[i]>arr[i+1]){ 19 | int temp=arr[i]; 20 | arr[i]=arr[i+1]; 21 | arr[i+1]=temp; 22 | } 23 | 24 | } 25 | } 26 | counter++; 27 | } 28 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | void Insert(vector& vec, int key){ 7 | // Insert key at the end 8 | auto i = vec.size(); 9 | vec.emplace_back(key); 10 | 11 | // Rearrange elements: O(log n) 12 | while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){ 13 | vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2]; 14 | i = i % 2 == 0 ? (i/2)-1 : i/2; 15 | } 16 | vec[i] = key; 17 | } 18 | 19 | void InsertInplace(int A[], int n){ 20 | int i = n; 21 | int temp = A[n]; 22 | while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){ 23 | A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2]; 24 | i = i % 2 == 0 ? (i/2)-1 : i/2; 25 | } 26 | A[i] = temp; 27 | } 28 | 29 | void CreateHeap(vector& vec, int A[], int n){ 30 | // O(n log n) 31 | for (int i=0; i 43 | void Print(T& vec, int n, char c){ 44 | cout << c << ": [" << flush; 45 | for (int i=0; i v; 62 | CreateHeap(v, b, sizeof(b)/sizeof(b[0])); 63 | Print(v, v.size(), 'v'); 64 | 65 | cout << "Inplace Insert" << endl; 66 | createHeap(b, sizeof(b)/sizeof(b[0])); 67 | Print(b, sizeof(b)/sizeof(b[0]), 'b'); 68 | 69 | 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Algorithms/Deletion_in_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void display(int A[],int n){ 5 | for(int i=0; i>n; 21 | cout<<"Enter length of the array: "; 22 | cin>>m; 23 | int A[n]; 24 | 25 | for(int i=0; i>A[i]; 27 | } 28 | 29 | //Example function call to delete 2nd element 30 | arr_delete(A,2,m); 31 | 32 | display(A,m-1); 33 | 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Diagnolmatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Diagnol 5 | { 6 | private: 7 | int *A; 8 | int n; 9 | public: 10 | Diagnol() 11 | { 12 | n=2; 13 | A=new int[2]; 14 | } 15 | Diagnol(int n) 16 | { 17 | this->n=n; 18 | A=new int[n]; 19 | } 20 | ~Diagnol() 21 | { 22 | delete []A; 23 | } 24 | void Set(int i, int j,int x); 25 | int Get(int i, int j); 26 | void Display(); 27 | }; 28 | 29 | void Diagnol::Set(int i, int j,int x) 30 | { 31 | if(i==j) 32 | A[i-1]=x; 33 | } 34 | 35 | int Diagnol::Get(int i, int j) 36 | { 37 | if(i==j) 38 | return A[i-1]; 39 | else 40 | return 0; 41 | } 42 | 43 | void Diagnol::Display() 44 | { 45 | for (int i = 0; i < n; i++) 46 | { 47 | for (int j = 0; j < n; j++) 48 | { 49 | if(i==j) 50 | cout< 2 | using namespace std; 3 | class node{ 4 | public: 5 | int data; 6 | node *next;//yaha address store karvana tha toh aysy likha 7 | node(int data){ 8 | this->data=data; 9 | next=NULL; 10 | } 11 | }; 12 | node *middlenode(node *head){ 13 | node *slow=head; 14 | node *fast=head->next; 15 | while(fast && fast->next){ 16 | slow=slow->next; 17 | fast=fast->next->next; 18 | } 19 | if(fast!=NULL){ 20 | return slow->next; 21 | } 22 | return slow; 23 | } 24 | 25 | int main(){ 26 | node n1(81); 27 | node n2(27); 28 | node n3(56); 29 | node *head=&n1;// this head is storing the address of first link list component so that we can access the whole link list through this 30 | n1.next=&n2; 31 | n2.next=&n3;// this is storing address jaha pehle null stored tha 32 | 33 | cout<<"the middle element is "<data; 34 | 35 | 36 | return 0; 37 | 38 | 39 | } 40 | 41 | 42 | 43 | 44 | 45 | //The running time of finding the middle element this way with two pointers is O(n) because once we pass through the entire linked list of n elements, the slower pointer is at the middle node already. 46 | -------------------------------------------------------------------------------- /Algorithms/Floyd_Warshall.cpp: -------------------------------------------------------------------------------- 1 | //Problem Statement 2 | //The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. 3 | //The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. 4 | //Time Complexity: O(V^3) 5 | 6 | #include 7 | using namespace std; 8 | 9 | vector> floyd_warshall(vector> graph) { 10 | vector> dist(graph); 11 | 12 | int V = graph.size(); 13 | 14 | // Iterate over all phases 1,2,....,V 15 | for(int k=0;k dist[i][k] + dist[k][j]) { 25 | dist[i][j] = dist[i][k] + dist[k][j]; 26 | } 27 | } 28 | } 29 | } 30 | } 31 | 32 | //Check for negative edge cycle 33 | for(int i=0;i> graph = { 46 | {0,INT_MAX,-2,INT_MAX}, 47 | {4,0,3,INT_MAX}, 48 | {INT_MAX,INT_MAX,0,2}, 49 | {INT_MAX,-1,INT_MAX,0} 50 | }; 51 | 52 | auto it = floyd_warshall(graph); 53 | 54 | //The shortest path from ith node to jth node 55 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | struct Item{ 6 | int val; 7 | int w; 8 | }; 9 | 10 | bool cmp(Item i1,Item i2){ 11 | double r1= (double)i1.val/i1.w; 12 | double r2=(double)i2.val/i2.w; 13 | return r1>r2; 14 | } 15 | 16 | int fractionalKnapsack(Item items[],int n,int W){ 17 | sort(items,items+n,cmp); 18 | 19 | int rem=W; 20 | double ans=0; 21 | for(int i=0;ib) 15 | { 16 | gcd = b; 17 | } 18 | else if (b>a) 19 | { 20 | gcd = a; 21 | } 22 | 23 | while(true) 24 | { 25 | if(a% gcd ==0 && b% gcd==0) 26 | { 27 | System.out.println(gcd); 28 | break; 29 | } 30 | --gcd; 31 | } 32 | 33 | 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Greedyalgo_coinchange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author Lakshay Goel 3 | Github profile: https://github.com/MrLakshay 4 | Problem statement : Given coins worth 1 ,5 and 10 in unlimited quantity need to find 5 | minimum number of coins 'x' to make 'n' sum of money input by user. 6 | Input: n 7 | Output : x 8 | Exampple: 9 | 17 10 | 4 11 | */ 12 | #include 13 | using namespace std; 14 | int main(){ 15 | int t; 16 | cin>>t; 17 | cout< 2 | void Insert(int A[], int n) 3 | { 4 | int i = n, temp; 5 | temp = A[i]; 6 | while (i > 1 && temp > A[i / 2]) 7 | { 8 | A[i] = A[i / 2]; 9 | i = i / 2; 10 | } 11 | A[i] = temp; 12 | } 13 | int Delete(int A[], int n) 14 | { 15 | int i, j, x, temp, val; 16 | val = A[1]; 17 | x = A[n]; 18 | A[1] = A[n]; 19 | A[n] = val; 20 | i = 1; 21 | j = i * 2; 22 | while (j <= n - 1) 23 | { 24 | if (j < n - 1 && A[j + 1] > A[j]) 25 | j = j + 1; 26 | if (A[i] < A[j]) 27 | { 28 | temp = A[i]; 29 | A[i] = A[j]; 30 | A[j] = temp; 31 | i = j; 32 | j = 2 * j; 33 | } 34 | else 35 | break; 36 | } 37 | return val; 38 | } 39 | int main() 40 | { 41 | int H[] = {0, 14, 15, 5, 20, 30, 8, 40}; 42 | int i; 43 | for (i = 2; i <= 7; i++) 44 | Insert(H, i); 45 | 46 | for (i = 7; i > 1; i--) 47 | { 48 | Delete(H, i); 49 | } 50 | for (i = 1; i <= 7; i++) 51 | printf("%d ", H[i]); 52 | printf("\n"); 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Algorithms/Heapify.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void swap(int A[], int i, int j){ 6 | int temp = A[i]; 7 | A[i] = A[j]; 8 | A[j] = temp; 9 | } 10 | 11 | int Delete(int A[], int n){ 12 | int x = A[0]; // Max element 13 | A[0] = A[n-1]; 14 | 15 | int i = 0; 16 | int j = 2 * i + 1; 17 | 18 | while (j < n-1){ 19 | // Compare left and right children 20 | if (A[j] < A[j+1]){ 21 | j = j+1; 22 | } 23 | 24 | // Compare parent and largest child 25 | if (A[i] < A[j]){ 26 | swap(A, i, j); 27 | i = j; 28 | j = 2 * i + 1; 29 | } else { 30 | break; 31 | } 32 | } 33 | return x; 34 | } 35 | 36 | void Heapify(int A[], int n){ 37 | // # of leaf elements: (n+1)/2, index of last leaf element's parent = (n/2)-1 38 | for (int i=(n/2)-1; i>=0; i--){ 39 | 40 | int j = 2 * i + 1; // Left child for current i 41 | 42 | while(j < n-1){ 43 | // Compare left and right children of current i 44 | if (A[j] < A[j+1]){ 45 | j = j+1; 46 | } 47 | 48 | // Compare parent and largest child 49 | if (A[i] < A[j]){ 50 | swap(A, i, j); 51 | i = j; 52 | j = 2 * i + 1; 53 | } else { 54 | break; 55 | } 56 | } 57 | } 58 | } 59 | 60 | template 61 | void Print(T& vec, int n, string s){ 62 | cout << s << ": [" << flush; 63 | for (int i=0; i 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Lecture based 7 | void InsertA(int A[], int n){ 8 | int i = n; 9 | int temp = A[n]; 10 | while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){ 11 | A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2]; 12 | i = i % 2 == 0 ? (i/2)-1 : i/2; 13 | } 14 | A[i] = temp; 15 | } 16 | 17 | 18 | // STL vector based 19 | void Insert(vector& vec, int key){ 20 | // Insert key at the end 21 | auto i = vec.size(); 22 | vec.emplace_back(key); 23 | 24 | // Rearrange elements: Indices are not DRY :-( 25 | while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){ 26 | vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2]; 27 | i = i % 2 == 0 ? (i/2)-1 : i/2; 28 | } 29 | vec[i] = key; 30 | } 31 | 32 | template 33 | void Print(T& vec, int n){ 34 | cout << "Max Heap: [" << flush; 35 | for (int i=0; i v = {45, 35, 15, 30, 10, 12, 6, 5, 20}; 54 | Print(v, v.size()); 55 | v.reserve(15); // Reserve space for 15 elements 56 | 57 | Insert(v, 50); 58 | Print(v, v.size()); 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Algorithms/Insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | #include 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | // This is code is contributed by rathbhupendra 48 | -------------------------------------------------------------------------------- /Algorithms/KadanesAlgo.java: -------------------------------------------------------------------------------- 1 | class KadanesAlgo 2 | { 3 | // Function to find the maximum sum of a contiguous subarray 4 | // in a given integer array 5 | public static int kadane(int[] A) 6 | { 7 | // stores the maximum sum subarray found so far 8 | int maxSoFar = 0; 9 | 10 | // stores the maximum sum of subarray ending at the current position 11 | int maxEndingHere = 0; 12 | 13 | // traverse the given array 14 | for (int i: A) 15 | { 16 | // update the maximum sum of subarray "ending" at index `i` (by adding the 17 | // current element to maximum sum ending at previous index `i-1`) 18 | maxEndingHere = maxEndingHere + i; 19 | 20 | // if the maximum sum is negative, set it to 0 (which represents 21 | // an empty subarray) 22 | maxEndingHere = Integer.max(maxEndingHere, 0); 23 | 24 | // update the result if the current subarray sum is found to be greater 25 | maxSoFar = Integer.max(maxSoFar, maxEndingHere); 26 | } 27 | 28 | return maxSoFar; 29 | } 30 | 31 | public static void main(String[] args) 32 | { 33 | int[] A = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; 34 | 35 | System.out.println("The sum of contiguous subarray with the " + 36 | "largest sum is " + kadane(A)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Kruskal'sMinSpanningTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define I 32767 // Infinity 4 | #define V 7 // # of vertices in Graph 5 | #define E 9 // # of edges in Graph 6 | 7 | using namespace std; 8 | 9 | void PrintMCST(int T[][V-1], int A[][E]){ 10 | cout << "\nMinimum Cost Spanning Tree Edges\n" << endl; 11 | for (int i {0}; i 0){ 33 | x = s[x]; 34 | } 35 | 36 | while (u != x){ 37 | v = s[u]; 38 | s[u] = x; 39 | u = v; 40 | } 41 | return x; 42 | } 43 | 44 | void KruskalsMCST(int A[3][9]){ 45 | int T[2][V-1]; // Solution array 46 | int track[E] {0}; // Track edges that are included in solution 47 | int set[V+1] = {-1, -1, -1, -1, -1, -1, -1, -1}; // Array for finding cycle 48 | 49 | int i {0}; 50 | while (i < V-1){ 51 | int min = I; 52 | int u {0}; 53 | int v {0}; 54 | int k {0}; 55 | 56 | // Find a minimum cost edge 57 | for (int j {0}; j 2 | using namespace std; 3 | 4 | void display(int A[],int n){ 5 | for(int i=0; i>n; 22 | cout<<"Enter length of the array: "; 23 | cin>>m; 24 | int A[n]; 25 | 26 | for(int i=0; i>A[i]; 28 | } 29 | //Example function call for linear search 30 | cout< 2 | 3 | using namespace std; 4 | 5 | class LowerTri 6 | { 7 | private: 8 | int *A; 9 | int n; 10 | public: 11 | LowerTri() 12 | { 13 | n=2; 14 | A=new int[2*(2+1)/2]; 15 | } 16 | LowerTri(int n) 17 | { 18 | this->n=n; 19 | A=new int[n*(n+1)/2]; 20 | } 21 | ~LowerTri() 22 | { 23 | delete []A; 24 | } 25 | void Set(int i, int j,int x); 26 | int Get(int i, int j); 27 | void Display(); 28 | int GetDimension(){return n;} 29 | }; 30 | 31 | void LowerTri::Set(int i, int j,int x) 32 | { 33 | if(i>=j) 34 | // A[i*(i-1)/2+j-1]=x; 35 | A[n*(j-1)-(j-2)*(j-1)/2+i-j]=x; 36 | } 37 | 38 | int LowerTri::Get(int i, int j) 39 | { 40 | if(i>=j) 41 | // return A[i*(i-1)/2+j-1]; 42 | return A[n*(j-1)-(j-2)*(j-1)/2+i-j]; 43 | return 0; 44 | } 45 | 46 | void LowerTri::Display() 47 | { 48 | for (int i = 1; i <= n; i++) 49 | { 50 | for (int j = 1; j <= n; j++) 51 | { 52 | if(i>=j) 53 | // cout<>d; 72 | 73 | LowerTri lm(d); 74 | 75 | int x; 76 | cout<<"Enter all elements"<>x; 82 | lm.Set(i,j,x); 83 | 84 | } 85 | 86 | 87 | } 88 | 89 | lm.Display(); 90 | 91 | 92 | return 0; 93 | } -------------------------------------------------------------------------------- /Algorithms/Merge_Sort-Iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | //merging of sub-sorted array 6 | void merging(int a[] , int low , int mid , int high) 7 | { 8 | int i,j,k; 9 | i = low; 10 | j = mid+1; 11 | k = low; 12 | int b[100]; 13 | while(i <= mid && j <= high) 14 | { 15 | if(a[i] < a[j]) 16 | b[k++] = a[i++]; 17 | else 18 | b[k++] = a[j++]; 19 | } 20 | 21 | for( ; i <=mid ; i++) 22 | b[k++]=a[i]; 23 | 24 | for( ; j <= high ; j++) 25 | b[k++]=a[j]; 26 | 27 | for(i=0 ; i <= high ; i++) 28 | a[i] = b[i]; 29 | } 30 | 31 | void merge_sort(int a[] , int n) 32 | { 33 | int p,l,h,m,i; 34 | 35 | //this for loop will take account of number of passes 36 | //in each pass number of elements is increasing by previous*2; 37 | for(p=2 ; p <= n ; p=p*2) 38 | { 39 | for(i=0 ; i+p-1 < n ; i=i+p) //for choosing number of elements in each pass 40 | { 41 | l = i; 42 | h = i+p-1; 43 | m = (l+h)/2; 44 | merging(a , l , m , h); 45 | } 46 | } 47 | if(p/2 < n) //when number of elements is odd 48 | merging(a , 0 , p/2 , n-1); 49 | } 50 | 51 | 52 | int main() 53 | { 54 | int i,n; 55 | 56 | printf("\nEnter total number of elements of array : "); 57 | scanf("%d",&n); 58 | 59 | int a[n]; 60 | 61 | printf("\nEnter elements of array :\n"); 62 | for(i=0 ; i < n ; i++) 63 | scanf("%d" , &a[i]); 64 | 65 | merge_sort(a , n); 66 | 67 | printf("\n\nMerged array is : \n"); 68 | for(i=0 ; i < n ; i++) 69 | printf("%d " , a[i]); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Algorithms/Merge_Sort-Recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void merging(int a[] , int low , int mid , int high) 5 | { 6 | int i,j,k; 7 | i = low; 8 | j = mid+1; 9 | k = low; 10 | int b[100]; 11 | while(i <= mid && j <= high) 12 | { 13 | if(a[i] < a[j]) 14 | b[k++] = a[i++]; 15 | else 16 | b[k++] = a[j++]; 17 | } 18 | 19 | for( ; i <= mid ; i++) 20 | b[k++]=a[i]; 21 | 22 | for( ; j <= high ; j++) 23 | b[k++]=a[j]; 24 | 25 | for(i=0 ; i <= high ; i++) 26 | a[i] = b[i]; 27 | } 28 | 29 | void merge_sort(int a[] , int l , int h) 30 | { 31 | int mid; 32 | if(l < h) //will check if at least 2 elements are there 33 | { 34 | mid = (l+h)/2; 35 | merge_sort(a , l , mid); 36 | merge_sort(a , mid+1 , h); 37 | merging(a , l , mid , h); 38 | } 39 | } 40 | 41 | 42 | int main() 43 | { 44 | int i,n,low,high; 45 | 46 | printf("\nEnter total number of elements of array : "); 47 | scanf("%d",&n); 48 | 49 | int a[n]; 50 | 51 | low=0; 52 | high=n-1; 53 | 54 | printf("\nEnter elements of array :\n"); 55 | for(i=0 ; i < n ; i++) 56 | scanf("%d" , &a[i]); 57 | 58 | merge_sort(a , low , high); 59 | 60 | printf("\n\nMerged array is : \n"); 61 | for(i=0 ; i < n ; i++) 62 | printf("%d " , a[i]); 63 | 64 | return 0; 65 | } 66 | 67 | -------------------------------------------------------------------------------- /Algorithms/Merge_Sort.js: -------------------------------------------------------------------------------- 1 | function merge_sort(left_part,right_part) 2 | { 3 | var i = 0; 4 | var j = 0; 5 | var results = []; 6 | 7 | while (i < left_part.length || j < right_part.length) { 8 | if (i === left_part.length) { 9 | // j is the only index left_part 10 | results.push(right_part[j]); 11 | j++; 12 | } 13 | else if (j === right_part.length || left_part[i] <= right_part[j]) { 14 | results.push(left_part[i]); 15 | i++; 16 | } else { 17 | results.push(right_part[j]); 18 | j++; 19 | } 20 | } 21 | return results; 22 | } 23 | 24 | console.log(merge_sort([1,4,6], [8,2,9])); -------------------------------------------------------------------------------- /Algorithms/Merge_Sort_Algo.java: -------------------------------------------------------------------------------- 1 | //contributed by arunim singhal 2 | import java.util.Scanner; 3 | 4 | public class mergeSort { 5 | void merge(int arr[], int beg, int mid, int end) { 6 | 7 | int l = mid - beg + 1; 8 | int r = end - mid; 9 | 10 | int LeftArray[] = new int[l]; 11 | int RightArray[] = new int[r]; 12 | 13 | for (int i = 0; i < l; ++i) 14 | LeftArray[i] = arr[beg + i]; 15 | 16 | for (int j = 0; j < r; ++j) 17 | RightArray[j] = arr[mid + 1 + j]; 18 | 19 | int i = 0, j = 0; 20 | int k = beg; 21 | while (i < l && j < r) { 22 | if (LeftArray[i] <= RightArray[j]) { 23 | arr[k] = LeftArray[i]; 24 | i++; 25 | } else { 26 | arr[k] = RightArray[j]; 27 | j++; 28 | } 29 | k++; 30 | } 31 | while (i < l) { 32 | arr[k] = LeftArray[i]; 33 | i++; 34 | k++; 35 | } 36 | 37 | while (j < r) { 38 | arr[k] = RightArray[j]; 39 | j++; 40 | k++; 41 | } 42 | } 43 | 44 | void sort(int arr[], int beg, int end) { 45 | if (beg < end) { 46 | int mid = (beg + end) / 2; 47 | sort(arr, beg, mid); 48 | sort(arr, mid + 1, end); 49 | merge(arr, beg, mid, end); 50 | } 51 | } 52 | 53 | public static void main(String args[]) { 54 | int n; 55 | Scanner sc = new Scanner(System.in); 56 | n = sc.nextInt(); 57 | int[] a = new int[10]; 58 | for (int i = 0; i < n; i++) { 59 | 60 | a[i] = sc.nextInt(); 61 | } 62 | mergeSort ob = new mergeSort(); 63 | ob.sort(a, 0, a.length - 1); 64 | 65 | System.out.println("\nSorted array"); 66 | for (int i = 0; i < a.length; i++) { 67 | System.out.print(a[i] + " "); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Algorithms/Merge_Sort_using_linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | this->next = NULL; 13 | } 14 | }; 15 | 16 | Node *merge(Node *head1, Node *head2) 17 | { 18 | Node *fhead=NULL; 19 | Node *ftail=NULL; 20 | while(head1!=NULL && head2!=NULL){ 21 | if(head1->data < head2->data){ 22 | if(fhead==NULL){ 23 | fhead=head1; 24 | ftail=head1; 25 | head1=head1->next; 26 | }else{ 27 | ftail->next=head1; 28 | ftail=ftail->next; 29 | head1=head1->next; 30 | } 31 | }else{ 32 | if(fhead==NULL){ 33 | fhead=head2; 34 | ftail=head2; 35 | head2=head2->next; 36 | }else{ 37 | ftail->next=head2; 38 | ftail=ftail->next; 39 | head2=head2->next; 40 | } 41 | } 42 | } 43 | while(head1!=NULL){ 44 | if(fhead==NULL){ 45 | fhead=head1; 46 | ftail=head1; 47 | head1=head1->next; 48 | }else{ 49 | ftail->next=head1; 50 | ftail=ftail->next; 51 | head1=head1->next; 52 | } 53 | } 54 | while(head2!=NULL){ 55 | if(fhead==NULL){ 56 | fhead=head2; 57 | ftail=head2; 58 | head2=head2->next; 59 | }else{ 60 | ftail->next=head2; 61 | ftail=ftail->next; 62 | head2=head2->next; 63 | } 64 | } 65 | return fhead; 66 | } 67 | Node* mergeSort(Node *head) { 68 | if (head == NULL || head->next == NULL) 69 | return head; 70 | 71 | Node* fast = head->next; 72 | Node *slow = head; 73 | 74 | while (fast != NULL && fast->next != NULL) { 75 | slow = slow->next; 76 | fast = fast->next->next; 77 | } 78 | 79 | Node* a = head, *b = slow->next; 80 | slow->next = NULL; 81 | 82 | Node* c = mergeSort(a); 83 | Node* d = mergeSort(b); 84 | Node *e = merge(c, d); 85 | 86 | return e; 87 | } 88 | 89 | Node *takeinput() 90 | { 91 | int data; 92 | cin >> data; 93 | Node *head = NULL, *tail = NULL; 94 | while (data != -1) 95 | { 96 | Node *newnode = new Node(data); 97 | if (head == NULL) 98 | { 99 | head = newnode; 100 | tail = newnode; 101 | } 102 | else 103 | { 104 | tail->next = newnode; 105 | tail = newnode; 106 | } 107 | cin >> data; 108 | } 109 | return head; 110 | } 111 | 112 | void print(Node *head) 113 | { 114 | Node *temp = head; 115 | while (temp != NULL) 116 | { 117 | cout << temp->data << " "; 118 | temp = temp->next; 119 | } 120 | cout << endl; 121 | } 122 | 123 | int main() 124 | { 125 | int t; 126 | cin >> t; 127 | while (t--) 128 | { 129 | Node *head = takeinput(); 130 | head = mergeSort(head); 131 | print(head); 132 | } 133 | 134 | return 0; 135 | } 136 | -------------------------------------------------------------------------------- /Algorithms/Merge_Two_Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int* merge(int A[], int m, int B[], int n) { 5 | 6 | int* C = new int[m+n]; 7 | 8 | int i=0, j=0, k=0; 9 | 10 | while (i>n; 43 | 44 | cout<<"Enter length of the array2: "; 45 | cin>>m; 46 | int A[n]; 47 | int B[m]; 48 | 49 | for(int i=0; i>A[i]; 51 | } 52 | 53 | for(int i=0; i>B[i]; 55 | } 56 | 57 | int* C = merge(A,n,B,m); 58 | display(C,m+n); 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Algorithms/Mergesort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | using namespace std; 4 | 5 | // Merges two subarrays of array[]. 6 | // First subarray is arr[begin..mid] 7 | // Second subarray is arr[mid+1..end] 8 | void merge(int array[], int const left, int const mid, int const right) 9 | { 10 | auto const subArrayOne = mid - left + 1; 11 | auto const subArrayTwo = right - mid; 12 | 13 | // Create temp arrays 14 | auto *leftArray = new int[subArrayOne], 15 | *rightArray = new int[subArrayTwo]; 16 | 17 | // Copy data to temp arrays leftArray[] and rightArray[] 18 | for (auto i = 0; i < subArrayOne; i++) 19 | leftArray[i] = array[left + i]; 20 | for (auto j = 0; j < subArrayTwo; j++) 21 | rightArray[j] = array[mid + 1 + j]; 22 | 23 | auto indexOfSubArrayOne = 0, // Initial index of first sub-array 24 | indexOfSubArrayTwo = 0; // Initial index of second sub-array 25 | int indexOfMergedArray = left; // Initial index of merged array 26 | 27 | // Merge the temp arrays back into array[left..right] 28 | while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { 29 | if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { 30 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 31 | indexOfSubArrayOne++; 32 | } 33 | else { 34 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 35 | indexOfSubArrayTwo++; 36 | } 37 | indexOfMergedArray++; 38 | } 39 | // Copy the remaining elements of 40 | // left[], if there are any 41 | while (indexOfSubArrayOne < subArrayOne) { 42 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 43 | indexOfSubArrayOne++; 44 | indexOfMergedArray++; 45 | } 46 | // Copy the remaining elements of 47 | // right[], if there are any 48 | while (indexOfSubArrayTwo < subArrayTwo) { 49 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 50 | indexOfSubArrayTwo++; 51 | indexOfMergedArray++; 52 | } 53 | } 54 | 55 | // begin is for left index and end is 56 | // right index of the sub-array 57 | // of arr to be sorted */ 58 | void mergeSort(int array[], int const begin, int const end) 59 | { 60 | if (begin >= end) 61 | return; // Returns recursively 62 | 63 | auto mid = begin + (end - begin) / 2; 64 | mergeSort(array, begin, mid); 65 | mergeSort(array, mid + 1, end); 66 | merge(array, begin, mid, end); 67 | } 68 | 69 | // UTILITY FUNCTIONS 70 | // Function to print an array 71 | void printArray(int A[], int size) 72 | { 73 | for (auto i = 0; i < size; i++) 74 | cout << A[i] << " "; 75 | } 76 | 77 | // Driver code 78 | int main() 79 | { 80 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 81 | auto arr_size = sizeof(arr) / sizeof(arr[0]); 82 | 83 | cout << "Given array is \n"; 84 | printArray(arr, arr_size); 85 | 86 | mergeSort(arr, 0, arr_size - 1); 87 | 88 | cout << "\nSorted array is \n"; 89 | printArray(arr, arr_size); 90 | return 0; 91 | } 92 | 93 | // This code is contributed by Mayank Tyagi 94 | // This code was revised by Joshua Estes 95 | -------------------------------------------------------------------------------- /Algorithms/PrimsMinSpanningTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define V 8 3 | #define I 32767 4 | 5 | using namespace std; 6 | 7 | void PrintMST(int T[][V - 2], int G[V][V]) 8 | { 9 | cout << "\nMinimum Spanning Tree Edges (w/ cost)\n" 10 | << endl; 11 | int sum{0}; 12 | for (int i{0}; i < V - 2; i++) 13 | { 14 | int c = G[T[0][i]][T[1][i]]; 15 | cout << "[" << T[0][i] << "]---[" << T[1][i] << "] cost: " << c << endl; 16 | sum += c; 17 | } 18 | cout << endl; 19 | cout << "Total cost of MST: " << sum << endl; 20 | } 21 | 22 | void PrimsMST(int G[V][V], int n) 23 | { 24 | int u; 25 | int v; 26 | int min{I}; 27 | int track[V]; 28 | int T[2][V - 2]{0}; 29 | 30 | // Initial: Find min cost edge 31 | for (int i{1}; i < V; i++) 32 | { 33 | track[i] = I; // Initialize track array with INFINITY 34 | for (int j{i}; j < V; j++) 35 | { 36 | if (G[i][j] < min) 37 | { 38 | min = G[i][j]; 39 | u = i; 40 | v = j; 41 | } 42 | } 43 | } 44 | T[0][0] = u; 45 | T[1][0] = v; 46 | track[u] = track[v] = 0; 47 | 48 | // Initialize track array to track min cost edges 49 | for (int i{1}; i < V; i++) 50 | { 51 | if (track[i] != 0) 52 | { 53 | if (G[i][u] < G[i][v]) 54 | { 55 | track[i] = u; 56 | } 57 | else 58 | { 59 | track[i] = v; 60 | } 61 | } 62 | } 63 | 64 | // Repeat 65 | for (int i{1}; i < n - 1; i++) 66 | { 67 | int k; 68 | min = I; 69 | for (int j{1}; j < V; j++) 70 | { 71 | if (track[j] != 0 && G[j][track[j]] < min) 72 | { 73 | k = j; 74 | min = G[j][track[j]]; 75 | } 76 | } 77 | T[0][i] = k; 78 | T[1][i] = track[k]; 79 | track[k] = 0; 80 | 81 | // Update track array to track min cost edges 82 | for (int j{1}; j < V; j++) 83 | { 84 | if (track[j] != 0 && G[j][k] < G[j][track[j]]) 85 | { 86 | track[j] = k; 87 | } 88 | } 89 | } 90 | PrintMST(T, G); 91 | } 92 | 93 | int main() 94 | { 95 | 96 | int cost[V][V]{ 97 | {I, I, I, I, I, I, I, I}, 98 | {I, I, 25, I, I, I, 5, I}, 99 | {I, 25, I, 12, I, I, I, 10}, 100 | {I, I, 12, I, 8, I, I, I}, 101 | {I, I, I, 8, I, 16, I, 14}, 102 | {I, I, I, I, 16, I, 20, 18}, 103 | {I, 5, I, I, I, 20, I, I}, 104 | {I, I, 10, I, 14, 18, I, I}, 105 | }; 106 | 107 | int n = sizeof(cost[0]) / sizeof(cost[0][0]) - 1; 108 | 109 | PrimsMST(cost, n); 110 | 111 | return 0; 112 | } -------------------------------------------------------------------------------- /Algorithms/Quick_sort.cpp: -------------------------------------------------------------------------------- 1 | /* C implementation QuickSort */ 2 | #include 3 | 4 | // A utility function to swap two elements 5 | void swap(int* a, int* b) 6 | { 7 | int t = *a; 8 | *a = *b; 9 | *b = t; 10 | } 11 | 12 | /* This function takes last element as pivot, places 13 | the pivot element at its correct position in sorted 14 | array, and places all smaller (smaller than pivot) 15 | to left of pivot and all greater elements to right 16 | of pivot */ 17 | int partition (int arr[], int low, int high) 18 | { 19 | int pivot = arr[high]; // pivot 20 | int i = (low - 1); // Index of smaller element 21 | 22 | for (int j = low; j <= high- 1; j++) 23 | { 24 | // If current element is smaller than or 25 | // equal to pivot 26 | if (arr[j] <= pivot) 27 | { 28 | i++; // increment index of smaller element 29 | swap(&arr[i], &arr[j]); 30 | } 31 | } 32 | swap(&arr[i + 1], &arr[high]); 33 | return (i + 1); 34 | } 35 | 36 | /* The main function that implements QuickSort 37 | arr[] --> Array to be sorted, 38 | low --> Starting index, 39 | high --> Ending index */ 40 | void quickSort(int arr[], int low, int high) 41 | { 42 | if (low < high) 43 | { 44 | /* pi is partitioning index, arr[p] is now 45 | at right place */ 46 | int pi = partition(arr, low, high); 47 | 48 | // Separately sort elements before 49 | // partition and after partition 50 | quickSort(arr, low, pi - 1); 51 | quickSort(arr, pi + 1, high); 52 | } 53 | } 54 | 55 | /* Function to print an array */ 56 | void printArray(int arr[], int size) 57 | { 58 | int i; 59 | for (i=0; i < size; i++) 60 | printf("%d ", arr[i]); 61 | printf("\n"); 62 | } 63 | 64 | // Driver program to test above functions 65 | int main() 66 | { 67 | int arr[] = {10, 7, 8, 9, 1, 5}; 68 | int n = sizeof(arr)/sizeof(arr[0]); 69 | quickSort(arr, 0, n-1); 70 | printf("Sorted array: \n"); 71 | printArray(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Algorithms/Quicksort.cpp: -------------------------------------------------------------------------------- 1 | /* C implementation QuickSort */ 2 | #include 3 | 4 | // A utility function to swap two elements 5 | void swap(int* a, int* b) 6 | { 7 | int t = *a; 8 | *a = *b; 9 | *b = t; 10 | } 11 | 12 | /* This function takes last element as pivot, places 13 | the pivot element at its correct position in sorted 14 | array, and places all smaller (smaller than pivot) 15 | to left of pivot and all greater elements to right 16 | of pivot */ 17 | int partition (int arr[], int low, int high) 18 | { 19 | int pivot = arr[high]; // pivot 20 | int i = (low - 1); // Index of smaller element 21 | 22 | for (int j = low; j <= high- 1; j++) 23 | { 24 | // If current element is smaller than or 25 | // equal to pivot 26 | if (arr[j] <= pivot) 27 | { 28 | i++; // increment index of smaller element 29 | swap(&arr[i], &arr[j]); 30 | } 31 | } 32 | swap(&arr[i + 1], &arr[high]); 33 | return (i + 1); 34 | } 35 | 36 | /* The main function that implements QuickSort 37 | arr[] --> Array to be sorted, 38 | low --> Starting index, 39 | high --> Ending index */ 40 | void quickSort(int arr[], int low, int high) 41 | { 42 | if (low < high) 43 | { 44 | /* pi is partitioning index, arr[p] is now 45 | at right place */ 46 | int pi = partition(arr, low, high); 47 | 48 | // Separately sort elements before 49 | // partition and after partition 50 | quickSort(arr, low, pi - 1); 51 | quickSort(arr, pi + 1, high); 52 | } 53 | } 54 | 55 | /* Function to print an array */ 56 | void printArray(int arr[], int size) 57 | { 58 | int i; 59 | for (i=0; i < size; i++) 60 | printf("%d ", arr[i]); 61 | printf("\n"); 62 | } 63 | 64 | // Driver program to test above functions 65 | int main() 66 | { 67 | int arr[] = {10, 7, 8, 9, 1, 5}; 68 | int n = sizeof(arr)/sizeof(arr[0]); 69 | quickSort(arr, 0, n-1); 70 | printf("Sorted array: \n"); 71 | printArray(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Algorithms/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Algorithms/Radixsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Radix Sort 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to get maximum value in arr[] 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | // A function to do counting sort of arr[] according to 16 | // the digit represented by exp. 17 | void countSort(int arr[], int n, int exp) 18 | { 19 | int output[n]; // output array 20 | int i, count[10] = {0}; 21 | 22 | // Store count of occurrences in count[] 23 | for (i = 0; i < n; i++) 24 | count[(arr[i] / exp) % 10]++; 25 | 26 | // Change count[i] so that count[i] now contains actual 27 | // position of this digit in output[] 28 | for (i = 1; i < 10; i++) 29 | count[i] += count[i - 1]; 30 | 31 | // Build the output array 32 | for (i = n - 1; i >= 0; i--) 33 | { 34 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 35 | count[(arr[i] / exp) % 10]--; 36 | } 37 | 38 | // Copy the output array to arr[], so that arr[] now 39 | // contains sorted numbers according to current digit 40 | for (i = 0; i < n; i++) 41 | arr[i] = output[i]; 42 | } 43 | 44 | // The main function to that sorts arr[] of size n using 45 | // Radix Sort 46 | void radixsort(int arr[], int n) 47 | { 48 | // Find the maximum number to know number of digits 49 | int m = getMax(arr, n); 50 | 51 | // Do counting sort for every digit. Note that instead 52 | // of passing digit number, exp is passed. exp is 10^i 53 | // where i is current digit number 54 | for (int exp = 1; m / exp > 0; exp *= 10) 55 | countSort(arr, n, exp); 56 | } 57 | 58 | // A utility function to print an array 59 | void print(int arr[], int n) 60 | { 61 | for (int i = 0; i < n; i++) 62 | cout << arr[i] << " "; 63 | } 64 | 65 | // Driver Code 66 | int main() 67 | { 68 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 69 | int n = sizeof(arr) / sizeof(arr[0]); 70 | 71 | // Function Call 72 | radixsort(arr, n); 73 | print(arr, n); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /* C++ Program to remove duplicates from a sorted linked list */ 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node* next; 11 | }; 12 | 13 | /* The function removes duplicates from a sorted list */ 14 | void removeDuplicates(Node* head) 15 | { 16 | /* Pointer to traverse the linked list */ 17 | Node* current = head; 18 | 19 | /* Pointer to store the next pointer of a node to be deleted*/ 20 | Node* next_next; 21 | 22 | /* do nothing if the list is empty */ 23 | if (current == NULL) 24 | return; 25 | 26 | /* Traverse the list till last node */ 27 | while (current->next != NULL) 28 | { 29 | /* Compare current node with next node */ 30 | if (current->data == current->next->data) 31 | { 32 | /* The sequence of steps is important*/ 33 | next_next = current->next->next; 34 | free(current->next); 35 | current->next = next_next; 36 | } 37 | else /* This is tricky: only advance if no deletion */ 38 | { 39 | current = current->next; 40 | } 41 | } 42 | } 43 | 44 | /* UTILITY FUNCTIONS */ 45 | /* Function to insert a node at the beginning of the linked list */ 46 | void push(Node** head_ref, int new_data) 47 | { 48 | /* allocate node */ 49 | Node* new_node = new Node(); 50 | 51 | /* put in the data */ 52 | new_node->data = new_data; 53 | 54 | /* link the old list off the new node */ 55 | new_node->next = (*head_ref); 56 | 57 | /* move the head to point to the new node */ 58 | (*head_ref) = new_node; 59 | } 60 | 61 | /* Function to print nodes in a given linked list */ 62 | void printList(Node *node) 63 | { 64 | while (node!=NULL) 65 | { 66 | cout<<" "<data; 67 | node = node->next; 68 | } 69 | } 70 | 71 | /* Driver program to test above functions*/ 72 | int main() 73 | { 74 | /* Start with the empty list */ 75 | Node* head = NULL; 76 | 77 | /* Let us create a sorted linked list to test the functions 78 | Created linked list will be 11->11->11->13->13->20 */ 79 | push(&head, 20); 80 | push(&head, 13); 81 | push(&head, 13); 82 | push(&head, 11); 83 | push(&head, 11); 84 | push(&head, 11); 85 | 86 | cout<<"Linked list before duplicate removal "; 87 | printList(head); 88 | 89 | /* Remove duplicates from linked list */ 90 | removeDuplicates(head); 91 | 92 | cout<<"\nLinked list after duplicate removal "; 93 | printList(head); 94 | 95 | return 0; 96 | } 97 | 98 | // This code is contributed by rathbhupendra 99 | -------------------------------------------------------------------------------- /Algorithms/Reverse_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void display(int A[],int n){ 5 | for(int i=0; i>n; 25 | int A[n]; 26 | 27 | for(int i=0; i>A[i]; 29 | } 30 | 31 | reverse(A,n); 32 | display(A,n); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Tower Of Hanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void TOH(int n,char a,char b,char c) 5 | { 6 | if(n==1) 7 | { 8 | cout<<"Move Disk "< 8 | #include 9 | 10 | using namespace std; 11 | 12 | vector z_function(string &p,string &t) 13 | { 14 | string s=p+'#'+t; 15 | int n=s.size(),l=0,r=0; //[l,r] is the current segment matching with the prefix 16 | vector z(n,0); 17 | for(int i=1;i length upto upper index bound 21 | //z[i-l]--> previously matching segement length for prefix 22 | 23 | while(i+z[i]r) //i+z[i]-1 last index of the matching prefix pattern 26 | l=i,r=i+z[i]-1; 27 | } 28 | return z; 29 | } 30 | 31 | int main() 32 | { 33 | string p,t; 34 | cout<<"\nEnter a pattern : "; 35 | cin>>p; 36 | cout<<"\nEnter a text to be searched for the pattern : "; 37 | cin>>t; 38 | vector z=z_function(p,t); 39 | vector ans; 40 | for(int i=0;i 5 | using namespace std; 6 | 7 | int binarySearch(int array[], int x, int low, int high) { 8 | 9 | // Repeat until the pointers low and high meet each other 10 | while (low <= high) { 11 | int mid = low + (high - low) / 2; 12 | 13 | if (array[mid] == x) 14 | return mid; 15 | 16 | if (array[mid] < x) 17 | low = mid + 1; 18 | 19 | else 20 | high = mid - 1; 21 | } 22 | 23 | return -1; 24 | } 25 | 26 | int main(void) { 27 | int array[] = {3, 4, 5, 6, 7, 8, 9}; 28 | int x = 4; 29 | int n = sizeof(array) / sizeof(array[0]); 30 | int result = binarySearch(array, x, 0, n - 1); 31 | if (result == -1) 32 | printf("Not found"); 33 | else 34 | printf("Element is found at index %d", result); 35 | } -------------------------------------------------------------------------------- /Algorithms/binary_search_Recursive.cpp: -------------------------------------------------------------------------------- 1 | int binsearch(int A[], int low, int high, int key){ 2 | 3 | if (low<=high){ 4 | int mid = low + (high-low)/2; 5 | 6 | if(key== A[mid]){ 7 | return mid; 8 | } 9 | 10 | else if (key>m; 26 | int A[m]; 27 | 28 | for(int i=0; i>A[i]; 30 | } 31 | //Example code to call the binary function 32 | //cout<= 0): 23 | y=y+1 24 | slope_error =slope_error - 2 * (x2 - x1) 25 | 26 | 27 | 28 | x1= int(input()) 29 | x2= int(input()) 30 | y1= int(input()) 31 | y2= int(input()) 32 | 33 | point1 = [x1,y1] 34 | point2 = [x2, y2] 35 | 36 | x_values = [point1[0], point2[0]] 37 | 38 | 39 | y_values = [point1[1], point2[1]] 40 | 41 | 42 | plt.plot(x_values,y_values) 43 | plt.show() 44 | 45 | -------------------------------------------------------------------------------- /Algorithms/circular queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define size 3 4 | void insert(); 5 | void delete(); 6 | void display(); 7 | int front=-1; 8 | int rear =-1; 9 | int a[size]; 10 | int main() 11 | { 12 | int d; 13 | printf("\n\n\n LIST OF CHOICES AND MENU"); 14 | printf("=========================>>"); 15 | printf("\n 1. insert"); 16 | printf("\n 2. delete"); 17 | printf("\n 3. DISPLAY"); 18 | printf("\n 4. BYE BYE"); 19 | while(1) 20 | { 21 | printf("\n\n enter your choice="); 22 | scanf("%d",&d); 23 | switch(d) 24 | { 25 | case 1: 26 | { 27 | insert(); 28 | break; 29 | } 30 | case 2: 31 | { 32 | delete(); 33 | break; 34 | } 35 | case 3: 36 | { 37 | display(); 38 | break; 39 | } 40 | case 4: 41 | { 42 | exit(0); 43 | } 44 | default: 45 | { 46 | printf("\n INVALID INPUT !!!!!!"); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/duplicate_elements_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, i,j ,Ld=0; 7 | cout << "How many numbers? "; 8 | cin >> n; 9 | int A[n]; 10 | cout << "Enter the numbers : "; 11 | for (i = 0; i < n; i++) 12 | cin >> A[i]; 13 | 14 | for (int i = 0; i < n; i++) 15 | { 16 | if (A[i]==A[i+1] && A[i]!=Ld) 17 | { 18 | cout<<"Duplicates element are "< 2 | using namespace std; 3 | 4 | int max(int A[], int n) 5 | { 6 | int m = A[0]; 7 | for (int i = 0; i < n; i++) 8 | { 9 | if (A[i] > m) 10 | m = A[i]; 11 | } 12 | return m; 13 | } 14 | 15 | int main() 16 | { 17 | int n, i; 18 | cout << "How many numbers? "; 19 | cin >> n; 20 | int A[n]; 21 | cout << "Enter the numbers : "; 22 | for (i = 0; i < n; i++) 23 | cin >> A[i]; 24 | 25 | int h = max(A, n) + 1; 26 | int *H = new int[h]; 27 | for (i = 0; i < h; i++) 28 | H[i] = 0; 29 | for (i = 0; i < n; i++) 30 | H[A[i]]++; 31 | for (i = 0; i <= h; i++) 32 | { 33 | if (H[i] > 1) 34 | cout << i << " occurs " << H[i] << " times" << endl; 35 | } 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Algorithms/heap_sort.cpp: -------------------------------------------------------------------------------- 1 | void heapify(int arr[], int n, int i) 2 | { 3 | int largest = i; 4 | int l = 2*i + 1; 5 | int r = 2*i + 2; 6 | 7 | if(l arr[largest]) 8 | largest = l; 9 | 10 | if(r arr[largest]) 11 | largest = r; 12 | 13 | if(largest != i) 14 | { 15 | swap(arr[i], arr[largest]); 16 | heapify(arr, n, largest); 17 | } 18 | 19 | } 20 | 21 | 22 | void buildHeap(int arr[], int n) 23 | { 24 | for(int i= (n/2)-1; i>=0; i--) 25 | heapify(arr, n, i); 26 | } 27 | 28 | 29 | void heapSort(int arr[], int n) 30 | { 31 | buildHeap(arr, n); 32 | for(int i= n-1; i>0; i--) 33 | { 34 | swap(arr[0], arr[i]); 35 | heapify(arr, i, 0); 36 | } 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /Algorithms/insertion-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Function to sort an array using insertion sort*/ 5 | void insertionSort(int arr[], int n) 6 | { 7 | int i, key, j; 8 | for (i = 1; i < n; i++) 9 | { 10 | key = arr[i]; 11 | j = i - 1; 12 | 13 | /* Move elements of arr[0..i-1], that are 14 | greater than key, to one position ahead 15 | of their current position */ 16 | while (j >= 0 && arr[j] > key) 17 | { 18 | arr[j + 1] = arr[j]; 19 | j = j - 1; 20 | } 21 | arr[j + 1] = key; 22 | } 23 | } 24 | 25 | // A utility function to print an array of size n 26 | void printArray(int arr[], int n) 27 | { 28 | int i; 29 | for (i = 0; i < n; i++) 30 | cout << arr[i] << " "; 31 | cout << endl; 32 | } 33 | 34 | /* Driver code */ 35 | int main() 36 | { 37 | int arr[] = { 12, 11, 13, 5, 6 }; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | 40 | insertionSort(arr, n); 41 | printArray(arr, n); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/job_sequencing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #define MAX 100 6 | 7 | #include 8 | 9 | #include 10 | 11 | using namespace std; 12 | 13 | class Job 14 | 15 | { 16 | 17 | public: 18 | char id[5]; 19 | int deadline; 20 | int Profit; 21 | 22 | }; 23 | 24 | void jobSequencing(Job jobs[], int n); 25 | 26 | int minvalue(int x, int y) 27 | 28 | { 29 | 30 | if (x < y) 31 | 32 | return x; 33 | 34 | return y; 35 | 36 | } 37 | 38 | int main(void) 39 | 40 | { 41 | 42 | int i, j, n; 43 | 44 | Job jobs[5]; 45 | 46 | cout << "\Enter the number of jobs:"; 47 | 48 | cin >> n; 49 | 50 | for (i = 0; i < n; i++) 51 | 52 | { 53 | 54 | cout << "\nEnter the job:"; 55 | 56 | cin >> jobs[i].id; 57 | 58 | cout << "\nEnter the Profit:"; 59 | 60 | cin >> jobs[i].Profit; 61 | 62 | cout << "\nEnter deadline:"; 63 | 64 | cin >> jobs[i].deadline; 65 | 66 | } 67 | 68 | Job temp; 69 | 70 | cout << "\nJob(i)\t\t Profit\t\t Deadline\t \n\n"; 71 | 72 | cout << "--------------------------------------------------"; 73 | 74 | for (i = 0; i < n; i++) 75 | 76 | { 77 | 78 | cout << "\n\n"; 79 | 80 | cout << jobs[i].id << "\t\t" << jobs[i].Profit << "\t\t" << jobs[i].deadline; 81 | 82 | } 83 | 84 | for (i = 1; i < n; i++) 85 | 86 | { 87 | 88 | for (j = 0; j < n - i; j++) 89 | 90 | { 91 | 92 | if (jobs[j + 1].Profit > jobs[j].Profit) 93 | 94 | { 95 | 96 | temp = jobs[j + 1]; 97 | 98 | jobs[j + 1] = jobs[j]; // descending order 99 | 100 | jobs[j] = temp; 101 | 102 | } 103 | 104 | } 105 | 106 | } 107 | 108 | cout << "\n\nTotal nuber of jobs:" << n << endl; 109 | 110 | jobSequencing(jobs, n); 111 | 112 | getch(); 113 | 114 | return 0; 115 | 116 | } 117 | 118 | void jobSequencing(Job jobs[], int n) 119 | 120 | { 121 | 122 | int i, j, k, maxprofit; 123 | 124 | int timeslot[MAX]; 125 | 126 | int filledTimeSlot = 0; 127 | 128 | int dmax = 0; 129 | 130 | for (i = 0; i < n; i++) 131 | 132 | { 133 | 134 | if (jobs[i].deadline > dmax) 135 | 136 | { 137 | 138 | dmax = jobs[i].deadline; 139 | 140 | } 141 | } 142 | 143 | 144 | 145 | cout << "\nTotal time slot: " << dmax << endl; 146 | 147 | for (i = 1; i <= dmax; i++) 148 | 149 | { 150 | 151 | timeslot[i] = -1; 152 | 153 | } 154 | 155 | cout << "\n\nnumber of jobs done: " << dmax << endl; 156 | 157 | for (i = 1; i <= n; i++) 158 | 159 | { 160 | 161 | k = minvalue(dmax, jobs[i - 1].deadline); 162 | 163 | while (k >= 1) 164 | 165 | { 166 | 167 | if (timeslot[k] == -1) 168 | 169 | { 170 | 171 | timeslot[k] = i - 1; 172 | 173 | filledTimeSlot++; 174 | 175 | break; 176 | 177 | } 178 | 179 | k--; 180 | 181 | } 182 | 183 | if (filledTimeSlot == dmax) 184 | 185 | { 186 | 187 | break; 188 | 189 | } 190 | 191 | } 192 | 193 | // cout<<"\nJobs done \:n"; 194 | 195 | for (i = 1; i <= dmax; i++) 196 | 197 | { 198 | 199 | cout << "\tJob" << jobs[timeslot[i]].id << " at time:" << i << endl; // at particular time slot 200 | 201 | } 202 | 203 | maxprofit = 0; 204 | 205 | for (i = 1; i <= dmax; i++) 206 | 207 | { 208 | 209 | maxprofit += jobs[timeslot[i]].Profit; 210 | 211 | } 212 | 213 | cout << "\ntotal profit: " << maxprofit; 214 | 215 | } 216 | -------------------------------------------------------------------------------- /Algorithms/kadane_algo.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print largest contiguous array sum using KADANE ALGORITHM 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0, 9 | start =0, end = 0, s=0; 10 | 11 | for (int i=0; i< size; i++ ) 12 | { 13 | max_ending_here += a[i]; 14 | 15 | if (max_so_far < max_ending_here) 16 | { 17 | max_so_far = max_ending_here; 18 | start = s; 19 | end = i; 20 | } 21 | 22 | if (max_ending_here < 0) 23 | { 24 | max_ending_here = 0; 25 | s = i + 1; 26 | } 27 | } 28 | cout << "Maximum contiguous sum is " 29 | << max_so_far << endl; 30 | cout << "Starting index "<< start 31 | << endl << "Ending index "<< end << endl; 32 | } 33 | 34 | /*Driver program to test maxSubArraySum*/ 35 | int main() 36 | { 37 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 38 | int n = sizeof(a)/sizeof(a[0]); 39 | int max_sum = maxSubArraySum(a, n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/kth largest element in array.cpp: -------------------------------------------------------------------------------- 1 | // Approach --- using min heap 2 | 3 | #include 4 | using namespace std; 5 | 6 | int kthlargest(vectorv ,int k){ 7 | 8 | priority_queue,greater> minh; 9 | for(int i=0;ik) 12 | { 13 | minh.pop(); 14 | } 15 | } 16 | return minh.top(); 17 | } 18 | 19 | int main(){ 20 | 21 | vectorv; 22 | int k= 2 , ans; 23 | 24 | v.push_back(6); 25 | v.push_back(5); 26 | v.push_back(3); 27 | v.push_back(2); 28 | v.push_back(8); 29 | v.push_back(10); 30 | 31 | ans= kthlargest(v,k); 32 | cout<<"kth largest element is "< 6 | using namespace std; 7 | 8 | // A linked list node 9 | struct Node 10 | { 11 | int data; 12 | struct Node *next; 13 | }; 14 | 15 | /*----------------Function to insert a new node in front of the list-------------------*/ 16 | void push(struct Node **head, int node_data) 17 | { 18 | /* 1. create and allocate node */ 19 | struct Node *newNode = new Node; 20 | 21 | /* 2. assign data to node */ 22 | newNode->data = node_data; 23 | 24 | /* 3. set next of new node as head */ 25 | newNode->next = (*head); 26 | 27 | /* 4. move the head to point to the new node */ 28 | (*head) = newNode; 29 | } 30 | 31 | /*----------------Function to insert new node after a given node--------------------*/ 32 | void insertAfter(struct Node *prev_node, int node_data) 33 | { 34 | /*1. check if the given prev_node is NULL */ 35 | if (prev_node == NULL) 36 | { 37 | cout << "the given previous node is required,cannot be NULL"; 38 | return; 39 | } 40 | 41 | /* 2. create and allocate new node */ 42 | struct Node *newNode = new Node; 43 | 44 | /* 3. assign data to the node */ 45 | newNode->data = node_data; 46 | 47 | /* 4. Make next of new node as next of prev_node */ 48 | newNode->next = prev_node->next; 49 | 50 | /* 5. move the next of prev_node as new_node */ 51 | prev_node->next = newNode; 52 | } 53 | 54 | /*----------------Function to insert new node at the end of the linked list------------------ */ 55 | void append(struct Node **head, int node_data) 56 | { 57 | /* 1. create and allocate node */ 58 | struct Node *newNode = new Node; 59 | 60 | struct Node *last = *head; /* used in step 5*/ 61 | 62 | /* 2. assign data to the node */ 63 | newNode->data = node_data; 64 | 65 | /* 3. set next pointer of new node to null as its the last node*/ 66 | newNode->next = NULL; 67 | 68 | /* 4. if list is empty, new node becomes first node */ 69 | if (*head == NULL) 70 | { 71 | *head = newNode; 72 | return; 73 | } 74 | 75 | /* 5. Else traverse till the last node */ 76 | while (last->next != NULL) 77 | last = last->next; 78 | 79 | /* 6. Change the next of last node */ 80 | last->next = newNode; 81 | return; 82 | } 83 | 84 | /*-------------------Function to display linked list contents ------------------------*/ 85 | void displayList(struct Node *node) 86 | { 87 | //traverse the list to display each node 88 | while (node != NULL) 89 | { 90 | cout << node->data << "-->"; 91 | node = node->next; 92 | } 93 | 94 | if (node == NULL) 95 | cout << "null"; 96 | } 97 | 98 | /*-----------------------------------MAIN FUNCTION-------------------------------------*/ 99 | int main() 100 | { 101 | /* empty list */ 102 | struct Node *head = NULL; 103 | 104 | // Insert 10. 105 | append(&head, 10); 106 | 107 | // Insert 20 at the beginning. 108 | push(&head, 20); 109 | 110 | // Insert 30 at the beginning. 111 | push(&head, 30); 112 | 113 | // Insert 40 at the end. 114 | append(&head, 40); // 115 | 116 | // Insert 50, after 20. 117 | insertAfter(head->next, 50); 118 | 119 | cout << "Final linked list: " << endl; 120 | displayList(head); 121 | 122 | return 0; 123 | } -------------------------------------------------------------------------------- /Algorithms/merge_sort_C++.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Merges two subarrays of array[]. 7 | // First subarray is arr[begin..mid] 8 | // Second subarray is arr[mid+1..end] 9 | void merge(vector& array, int const left, int const mid, int const right) 10 | { 11 | auto const subArr1 = mid - left + 1; 12 | auto const subArr2 = right - mid; 13 | 14 | // Create temp arrays 15 | auto *leftArray = new int[subArr1], 16 | *rightArray = new int[subArr2]; 17 | 18 | // Copying data to temp arrays 19 | for (auto i = 0; i < subArr1; i++) 20 | leftArray[i] = array[left + i]; 21 | for (auto j = 0; j < subArr2; j++) 22 | rightArray[j] = array[mid + 1 + j]; 23 | 24 | auto idxSubArr1 = 0, // Initial index of first sub-array 25 | idxSubArr2 = 0; // Initial index of second sub-array 26 | int idxMrgArr = left; // Initial index of merged array 27 | 28 | // Merge the temp arrays back into array[left..right] 29 | while (idxSubArr1 < subArr1 && idxSubArr2 < subArr2) { 30 | if (leftArray[idxSubArr1] <= rightArray[idxSubArr2]) { 31 | array[idxMrgArr] = leftArray[idxSubArr1]; 32 | idxSubArr1++; 33 | } 34 | else { 35 | array[idxMrgArr] = rightArray[idxSubArr2]; 36 | idxSubArr2++; 37 | } 38 | idxMrgArr++; 39 | } 40 | // Copy the remaining elements of 41 | // left[], if there are any 42 | while (idxSubArr1 < subArr1) { 43 | array[idxMrgArr] = leftArray[idxSubArr1]; 44 | idxSubArr1++; 45 | idxMrgArr++; 46 | } 47 | // Copy the remaining elements of 48 | // right[], if there are any 49 | while (idxSubArr2 < subArr2) { 50 | array[idxMrgArr] = rightArray[idxSubArr2]; 51 | idxSubArr2++; 52 | idxMrgArr++; 53 | } 54 | } 55 | 56 | // begin is for left index and end is 57 | // right index of the sub-array 58 | // of arr to be sorted */ 59 | void mergeSort(vector& array, int const begin, int const end) 60 | { 61 | if (begin >= end) 62 | return; // Returns recursively 63 | 64 | auto mid = begin + (end - begin) / 2; 65 | mergeSort(array, begin, mid); 66 | mergeSort(array, mid + 1, end); 67 | merge(array, begin, mid, end); 68 | } 69 | 70 | // Function to print an array 71 | void printArray(vector& A, int size) 72 | { 73 | for (auto i = 0; i < size; i++) 74 | cout << A[i] << " "; 75 | } 76 | 77 | // Driver code 78 | int main() 79 | { 80 | int n, input; 81 | cout<<"enter no. of array elements:"; 82 | cin>> n; 83 | 84 | vector arr; 85 | for (int i = 0; i < n; i++) 86 | { 87 | cin>> input; 88 | arr.push_back(input); 89 | } 90 | 91 | 92 | cout << "Input array is: "; 93 | printArray(arr, n); 94 | 95 | mergeSort(arr, 0, n - 1); 96 | 97 | cout << "\nSorted array is: "; 98 | printArray(arr, n); 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /Algorithms/mergesort.py: -------------------------------------------------------------------------------- 1 | 2 | # Merges two subarrays of arr[]. 3 | # First subarray is arr[l..m] 4 | # Second subarray is arr[m+1..r] 5 | 6 | 7 | def merge(arr, l, m, r): 8 | n1 = m - l + 1 9 | n2 = r - m 10 | 11 | # create temp arrays 12 | L = [0] * (n1) 13 | R = [0] * (n2) 14 | 15 | # Copy data to temp arrays L[] and R[] 16 | for i in range(0, n1): 17 | L[i] = arr[l + i] 18 | 19 | for j in range(0, n2): 20 | R[j] = arr[m + 1 + j] 21 | 22 | # Merge the temp arrays back into arr[l..r] 23 | i = 0 # Initial index of first subarray 24 | j = 0 # Initial index of second subarray 25 | k = l # Initial index of merged subarray 26 | 27 | while i < n1 and j < n2: 28 | if L[i] <= R[j]: 29 | arr[k] = L[i] 30 | i += 1 31 | else: 32 | arr[k] = R[j] 33 | j += 1 34 | k += 1 35 | 36 | # Copy the remaining elements of L[], if there 37 | # are any 38 | while i < n1: 39 | arr[k] = L[i] 40 | i += 1 41 | k += 1 42 | 43 | # Copy the remaining elements of R[], if there 44 | # are any 45 | while j < n2: 46 | arr[k] = R[j] 47 | j += 1 48 | k += 1 49 | 50 | # l is for left index and r is right index of the 51 | # sub-array of arr to be sorted 52 | 53 | 54 | def mergeSort(arr, l, r): 55 | if l < r: 56 | 57 | # Same as (l+r)//2, but avoids overflow for 58 | # large l and h 59 | m = l+(r-l)//2 60 | 61 | # Sort first and second halves 62 | mergeSort(arr, l, m) 63 | mergeSort(arr, m+1, r) 64 | merge(arr, l, m, r) 65 | 66 | 67 | # Driver code to test above 68 | arr = [12, 11, 13, 5, 6, 7] 69 | n = len(arr) 70 | print("Given array is") 71 | for i in range(n): 72 | print("%d" % arr[i]), 73 | 74 | mergeSort(arr, 0, n-1) 75 | print("\n\nSorted array is") 76 | for i in range(n): 77 | print("%d" % arr[i]), 78 | 79 | -------------------------------------------------------------------------------- /Algorithms/missingelement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int Missing_Elements_1(int A[]) 5 | { 6 | int diff,l=A[0],i; 7 | diff=l-0; 8 | for (int i = 0; i < 10; i++) 9 | { 10 | if (A[i]-i!=diff) 11 | { 12 | while (diff 2 | using namespace std; 3 | 4 | int max(int A[], int n) 5 | { 6 | int m = A[0]; 7 | for (int i = 0; i < n; i++) 8 | { 9 | if (A[i] > m) 10 | m = A[i]; 11 | } 12 | return m; 13 | } 14 | int main() 15 | { 16 | int n, i; 17 | cout << "How many numbers? "; 18 | cin >> n; 19 | int A[n]; 20 | cout << "Enter the numbers : "; 21 | for (i = 0; i < n; i++) 22 | cin >> A[i]; 23 | cout << "The numbers are : "; 24 | for (i = 0; i < n; i++) 25 | cout << A[i] << " "; 26 | cout << endl; 27 | int l = A[0]; 28 | int h = max(A, n) ; 29 | int *H = new int[h]; 30 | for (i = 0; i < h; i++) 31 | H[i] = 0; 32 | 33 | cout << "The hash table is : "; 34 | for (i = 0; i < h; i++) 35 | cout << H[i] << " "; 36 | 37 | for (i = 0; i < n; i++) 38 | H[A[i]]++; 39 | cout << endl 40 | << "Missing Elements" << endl; 41 | for (i = 1; i <= h; i++) 42 | { 43 | if (H[i] == 0) 44 | cout << i << " "; 45 | } 46 | cout << endl; 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/queue_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Define the default capacity of a queue 6 | #define SIZE 10 7 | 8 | // A class to store a queue 9 | class queue 10 | { 11 | int *arr; // array to store queue elements 12 | int capacity; // maximum capacity of the queue 13 | int front; // front points to the front element in the queue (if any) 14 | int rear; // rear points to the last element in the queue 15 | int count; // current size of the queue 16 | 17 | public: 18 | queue(int size = SIZE); // constructor 19 | ~queue(); // destructor 20 | 21 | void dequeue(); 22 | void enqueue(int x); 23 | int peek(); 24 | int size(); 25 | bool isEmpty(); 26 | bool isFull(); 27 | }; 28 | 29 | // Constructor to initialize a queue 30 | queue::queue(int size) 31 | { 32 | arr = new int[size]; 33 | capacity = size; 34 | front = 0; 35 | rear = -1; 36 | count = 0; 37 | } 38 | 39 | // Destructor to free memory allocated to the queue 40 | queue::~queue() 41 | { 42 | delete[] arr; 43 | } 44 | 45 | // Utility function to dequeue the front element 46 | void queue::dequeue() 47 | { 48 | // check for queue underflow 49 | if (isEmpty()) 50 | { 51 | cout << "Underflow\nProgram Terminated\n"; 52 | exit(EXIT_FAILURE); 53 | } 54 | 55 | cout << "Removing " << arr[front] << endl; 56 | 57 | front = (front + 1) % capacity; 58 | count--; 59 | } 60 | 61 | // Utility function to add an item to the queue 62 | void queue::enqueue(int item) 63 | { 64 | // check for queue overflow 65 | if (isFull()) 66 | { 67 | cout << "Overflow\nProgram Terminated\n"; 68 | exit(EXIT_FAILURE); 69 | } 70 | 71 | cout << "Inserting " << item << endl; 72 | 73 | rear = (rear + 1) % capacity; 74 | arr[rear] = item; 75 | count++; 76 | } 77 | 78 | // Utility function to return the front element of the queue 79 | int queue::peek() 80 | { 81 | if (isEmpty()) 82 | { 83 | cout << "Underflow\nProgram Terminated\n"; 84 | exit(EXIT_FAILURE); 85 | } 86 | return arr[front]; 87 | } 88 | 89 | // Utility function to return the size of the queue 90 | int queue::size() 91 | { 92 | return count; 93 | } 94 | 95 | // Utility function to check if the queue is empty or not 96 | bool queue::isEmpty() 97 | { 98 | return (size() == 0); 99 | } 100 | 101 | // Utility function to check if the queue is full or not 102 | bool queue::isFull() 103 | { 104 | return (size() == capacity); 105 | } 106 | 107 | int main() 108 | { 109 | // create a queue of capacity 5 110 | queue q(5); 111 | 112 | q.enqueue(1); 113 | q.enqueue(2); 114 | q.enqueue(3); 115 | 116 | cout << "The front element is " << q.peek() << endl; 117 | q.dequeue(); 118 | 119 | q.enqueue(4); 120 | 121 | cout << "The queue size is " << q.size() << endl; 122 | 123 | q.dequeue(); 124 | q.dequeue(); 125 | q.dequeue(); 126 | 127 | if (q.isEmpty()) 128 | { 129 | cout << "The queue is empty\n"; 130 | } 131 | else 132 | { 133 | cout << "The queue is not empty\n"; 134 | } 135 | 136 | return 0; 137 | } -------------------------------------------------------------------------------- /Algorithms/remove_duplicates_in_sorted_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int removeDuplicates(int arr[], int n) 4 | { 5 | if (n==0 || n==1) 6 | return n; 7 | int temp[n]; 8 | int j = 0; 9 | for (int i=0; i>n; 25 | int arr[n]; 26 | for(int i = 0;i>arr[i]; 28 | 29 | n = removeDuplicates(arr, n); 30 | 31 | //Displaying updated array 32 | for (int i=0; i 2 | #define MAX 50 3 | 4 | using namespace std; 5 | 6 | void swap1(int &x, int &y){ 7 | int temp = x; 8 | x = y; 9 | y = temp; 10 | } 11 | 12 | void selectionSort(int arr[], int n){ 13 | int minindex; 14 | for (int i = 0; i < n-1; i++){ 15 | minindex = i; 16 | for(int j = i+1; j < n; j++){ 17 | if(arr[j] < arr[minindex]){ 18 | minindex = j; 19 | } 20 | } 21 | if(minindex != i){ 22 | swap1(arr[i], arr[minindex]); 23 | } 24 | } 25 | } 26 | 27 | void print1(int arr[], int n){ 28 | cout<<"After Sorting:"<> n; 38 | for(int i=0; i>arr[i]; 40 | } 41 | cout<<"Before Sorting: "< 3 | 4 | void ShellSort(int sortedArray[], int size) 5 | { 6 | for (int t = size / 2; t > 0; t /= 2) 7 | { 8 | for (int i = t; i < size; i++) 9 | { 10 | int temp = sortedArray[i]; 11 | int j; 12 | for (j = i; j >= t && sortedArray[j - t] > temp; j -= t) 13 | { 14 | sortedArray[j] = sortedArray[j - t]; 15 | } 16 | sortedArray[j] = temp; 17 | } 18 | } 19 | } 20 | 21 | int main() 22 | { 23 | int n; 24 | cout << "Enter the size of the array "; 25 | cin >> n; 26 | int arr[n]; 27 | cout << "Enter the elements in the array \n"; 28 | for (int i = 0; i < n; i++) 29 | { 30 | cin >> arr[i]; 31 | } 32 | 33 | cout << "\n"; 34 | 35 | cout << "Original Array "; 36 | cout << "["; 37 | for (int i = 0; i < n; i++) 38 | { 39 | cout << arr[i] << ", "; 40 | } 41 | cout << "\b\b"; 42 | cout << "]"; 43 | 44 | cout << "\n"; 45 | ShellSort(arr, n); 46 | 47 | cout << "Array after Shell Sort is "; 48 | cout << "["; 49 | for (int i = 0; i < n; i++) 50 | { 51 | cout << arr[i] << ", "; 52 | } 53 | cout << "\b\b"; 54 | cout << "]"; 55 | cout << endl; 56 | 57 | cout << "\n"; 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Algorithms/stack_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int stack[100], n = 100, top = -1; 4 | void push(int val) 5 | { 6 | if (top >= n - 1) 7 | cout << "Stack Overflow" << endl; 8 | else 9 | { 10 | top++; 11 | stack[top] = val; 12 | } 13 | } 14 | void pop() 15 | { 16 | if (top <= -1) 17 | cout << "Stack Underflow" << endl; 18 | else 19 | { 20 | cout << "The popped element is " << stack[top] << endl; 21 | top--; 22 | } 23 | } 24 | void display() 25 | { 26 | if (top >= 0) 27 | { 28 | cout << "Stack elements are:"; 29 | for (int i = top; i >= 0; i--) 30 | cout << stack[i] << " "; 31 | cout << endl; 32 | } 33 | else 34 | cout << "Stack is empty"; 35 | } 36 | int main() 37 | { 38 | int ch, val; 39 | cout << "1) Push in stack" << endl; 40 | cout << "2) Pop from stack" << endl; 41 | cout << "3) Display stack" << endl; 42 | cout << "4) Exit" << endl; 43 | do 44 | { 45 | cout << "Enter choice: " << endl; 46 | cin >> ch; 47 | switch (ch) 48 | { 49 | case 1: 50 | { 51 | cout << "Enter value to be pushed:" << endl; 52 | cin >> val; 53 | push(val); 54 | break; 55 | } 56 | case 2: 57 | { 58 | pop(); 59 | break; 60 | } 61 | case 3: 62 | { 63 | display(); 64 | break; 65 | } 66 | case 4: 67 | { 68 | cout << "Exit" << endl; 69 | break; 70 | } 71 | default: 72 | { 73 | cout << "Invalid Choice" << endl; 74 | } 75 | } 76 | } while (ch != 4); 77 | return 0; 78 | } -------------------------------------------------------------------------------- /CompanywiseSolution/ADOBE/Linked_List/question.md: -------------------------------------------------------------------------------- 1 | Clone a linked list with next and random pointer. 2 | 3 | You are given a special linked list with N nodes where each node has a next pointer pointing to its next node. You are also given M random pointers, where you will be given M number of pairs denoting two nodes a and b i.e. a->arb = b. 4 | 5 | Construct a copy of the given list. The copy should consist of exactly N new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. 6 | 7 | For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. 8 | 9 | Return the head of the copied linked list. 10 | 11 | Example 1: 12 | 13 | N = 4, M = 2 14 | value = {1,2,3,4} 15 | pairs = {{1,2},{2,4}} 16 | Output: 1 17 | Explanation: In this test case, there 18 | are 4 nodes in linked list. Among these 19 | 4 nodes, 2 nodes have arbitrary pointer 20 | set, rest two nodes have arbitrary pointer 21 | as NULL. Second line tells us the value 22 | of four nodes. The third line gives the 23 | information about arbitrary pointers. 24 | The first node arbitrary pointer is set to 25 | node 2. The second node arbitrary pointer 26 | is set to node 4. -------------------------------------------------------------------------------- /CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp: -------------------------------------------------------------------------------- 1 | // Problem Statement - Given an array in which all numbers except two are repeated once. 2 | // (i.e. we have 2n+2 numbers and n numbers are occurring twice and remaining two have occurred once). Find those two numbers in the most efficient way. 3 | 4 | /* Examples - 5 | Input: = 2 6 | arr[] = {1, 2, 3, 2, 1, 4} 7 | Output: 8 | 3 4 9 | Explanation: 10 | 3 and 4 occur exactly once. 11 | 12 | Input: 13 | N = 1 14 | arr[] = {2, 1, 3, 2} 15 | Output: 16 | 1 3 17 | Explanation: 18 | 1 3 occur exactly once. 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | 24 | int setBit(int n, int pos) { 25 | return ((n & (1 << pos)) != 0); 26 | } 27 | void uniquenumber(int arr[], int n) { 28 | int xorsum = 0; 29 | for (int i = 0; i < n; i++) { 30 | xorsum = xorsum ^ arr[i]; 31 | } 32 | int tempxor = xorsum; 33 | int setbit = 0; 34 | int pos = 0; 35 | while (setbit != 1) { 36 | setbit = xorsum & 1; 37 | pos++; 38 | xorsum = xorsum >> 1; 39 | } 40 | int newxor = 0; 41 | for (int i = 0; i < n; i++) { 42 | if (setBit(arr[i], pos - 1)) { 43 | newxor = newxor ^ arr[i]; 44 | } 45 | } 46 | cout< 17 | using namespace std; 18 | 19 | int getBit(int n, int pos) { 20 | return ((n & (1 << pos)) != 0); 21 | } 22 | 23 | int setBit(int n, int pos) { 24 | return (n | (1 << pos)); 25 | } 26 | int uniquenumber(int arr[], int n) { 27 | int result = 0; 28 | for (int i = 0; i < 64; i++) { 29 | int sum = 0; 30 | for (int j = 0; j < n; j++) { 31 | if (getBit(arr[j], i)) { 32 | sum++; 33 | } 34 | } 35 | if (sum % 3 != 0) { 36 | result = setBit(result, i); 37 | } 38 | } 39 | return result; 40 | } 41 | 42 | int main() { 43 | int arr[] = {1,2,3,4,1,2,3,1,2,3}; 44 | 45 | cout< 18 | using namespace std; 19 | 20 | int numberofones(int n) { 21 | int count = 0; 22 | while (n) { 23 | n = n & (n - 1); 24 | count++; 25 | } 26 | return count; 27 | } 28 | 29 | int main() { 30 | int n; 31 | cin>>n; 32 | 33 | cout< 17 | using namespace std; 18 | 19 | int copysetbits(int x, int y, int l, int r) { 20 | if (1 < l || r > 32) { 21 | return false; 22 | } 23 | 24 | for (int i = l; i <= r; i++) { 25 | int mask = 1 << (i - 1); 26 | 27 | if (y & mask) { 28 | x = x | mask; 29 | } 30 | } 31 | return x; 32 | } 33 | 34 | int main () { 35 | int x, y, l, r; 36 | cin>>x>>y>>l>>r; 37 | cout< 22 | using namespace std; 23 | 24 | int countsetbitsutil(int x) { 25 | if ( x <= 0) { 26 | return 0; 27 | } 28 | return (x % 2 == 0 ? 0 : 1) + countsetbitsutil(x / 2); 29 | } 30 | 31 | int numberofones(int n) { 32 | int count = 0; 33 | for (int i = 0; i <= n; i++) { 34 | count += countsetbitsutil(i); 35 | } 36 | return count; 37 | } 38 | 39 | int main() { 40 | int n; 41 | cin>>n; 42 | 43 | cout< 11 | using namespace std; 12 | 13 | int divide2int(int n) { 14 | if (n == 0) { 15 | return 0; 16 | } 17 | 18 | int x = n >> 1; 19 | return x; 20 | } 21 | 22 | int main() { 23 | int n; 24 | cin>>n; 25 | cout< 4 | using namespace std; 5 | 6 | int flipped(int a, int b) { 7 | int ans = a ^ b; 8 | int count = 0; 9 | while (ans) { 10 | ans = ans & (ans - 1); 11 | count++; 12 | } 13 | return count; 14 | } 15 | 16 | int main () { 17 | int a,b; 18 | cin>>a>>b; 19 | 20 | cout< 14 | 15 | using namespace std; 16 | long long int count(int S[], int m, int n) { 17 | 18 | 19 | 20 | long long t[m+1][n+1]; 21 | 22 | for(int i=0;i>t; 48 | while(t--){ 49 | int n,m; 50 | cin>>n>>m; 51 | int arr[m]; 52 | for(int i=0;i>arr[i]; 54 | 55 | long long ans=count(arr,m,n); 56 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | 8 | public: 9 | int minDifference(int arr[], int n) { 10 | 11 | 12 | 13 | int sum = 0; 14 | for (int i = 0; i < n; i++) 15 | sum += arr[i]; 16 | 17 | bool dp[n + 1][sum + 1]; 18 | 19 | for (int i = 0; i <= n; i++) 20 | dp[i][0] = true; 21 | 22 | for (int i = 1; i <= sum; i++) 23 | dp[0][i] = false; 24 | 25 | for (int i = 1; i <= n; i++) { 26 | for (int j = 1; j <= sum; j++) { 27 | 28 | 29 | if (arr[i - 1] <= j) 30 | dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i-1][j]; 31 | else 32 | dp[i][j] = dp[i - 1][j]; 33 | } 34 | } 35 | 36 | 37 | 38 | int mn=INT_MAX; 39 | for(int z=0;z<(sum/2)+1;z++) 40 | { 41 | if(dp[n][z]==true) 42 | mn=min(mn,sum-2*z); 43 | } 44 | return mn; 45 | 46 | 47 | 48 | } 49 | }; 50 | 51 | 52 | // { Driver Code Starts. 53 | int main() 54 | { 55 | 56 | 57 | int t; 58 | cin >> t; 59 | while (t--) 60 | { 61 | int n; 62 | cin >> n; 63 | 64 | int a[n]; 65 | for(int i = 0; i < n; i++) 66 | cin >> a[i]; 67 | 68 | 69 | 70 | Solution ob; 71 | cout << ob.minDifference(a, n) << "\n"; 72 | 73 | } 74 | return 0; 75 | } // } Driver Code Ends -------------------------------------------------------------------------------- /CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Equilibrium { 3 | public static void main(String[] args){ 4 | Scanner sc = new Scanner(System.in); 5 | System.out.println("Enter the size of an array :"); 6 | int N = sc.nextInt(); 7 | long [] temp = new long[N]; 8 | System.out.println("Enter the number: "); 9 | for(int i =0 ; i duplicates(int arr[], int n) { 6 | // code here 7 | ArrayList ar=new ArrayList<>(); 8 | for (int i = 0; i = arr.length * 2) { 15 | ar.add(i); 16 | } 17 | } 18 | if(ar.isEmpty()) 19 | ar.add(-1); 20 | return ar; 21 | } 22 | public static void main(String args[]) 23 | { 24 | Scanner sc=new Scanner(System.in); 25 | System.out.println("Enter length of array arr"); 26 | int n=sc.nextInt(); 27 | System.out.println("Enter an array"); 28 | int arr[]=new int[n]; 29 | for(int i=0;i ans=duplicates(arr,n); 34 | for(Integer val:ans) 35 | System.out.print(val+" "); 36 | System.out.println(); 37 | } 38 | } -------------------------------------------------------------------------------- /CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class MaxSecondMax { 3 | public static void main(String[] args){ 4 | Scanner sc = new Scanner(System.in); 5 | System.out.println("Enter the size: "); 6 | int N = sc.nextInt(); 7 | int [] TempArr = new int [N]; 8 | for(int j =0 ; j< N ; j++){ 9 | System.out.println("Enter the Number: "); 10 | TempArr[j] = sc.nextInt(); 11 | } 12 | 13 | System.out.println(Max(TempArr , N)); 14 | sc.close(); 15 | } 16 | 17 | public static ArrayList Max( int arr[] , int size) 18 | { 19 | int counter = 0; 20 | int temp =-1; 21 | for(int i = 0 ; icounter){ 23 | counter = arr[i]; 24 | } 25 | } 26 | 27 | for(int i =0 ; i al = new ArrayList(); 35 | al.add(counter); 36 | al.add(temp); 37 | 38 | return al;//code here. 39 | } 40 | } -------------------------------------------------------------------------------- /CompanywiseSolution/Amazon/Max and Second Max/question.md: -------------------------------------------------------------------------------- 1 | Given an array arr[] of size N of positive integers which may have duplicates. The task is to find the maximum and second maximum from the array, and both of them should be distinct, so If no second max exists, then the second max will be -1. -------------------------------------------------------------------------------- /CompanywiseSolution/Amazon/check_for_BST/questions.txt: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree. Check whether it is a BST or not. 2 | Note: We are considering that BSTs can not contain duplicate Nodes. 3 | A BST is defined as follows: 4 | The left subtree of a node contains only nodes with keys less than the node's key. 5 | The right subtree of a node contains only nodes with keys greater than the node's key. 6 | Both the left and right subtrees must also be binary search trees. 7 | 8 | Example 1: 9 | 10 | Input: 11 | 2 12 | / \ 13 | 1 3 14 | Output: 1 15 | Explanation: 16 | The left subtree of root node contains node 17 | with key lesser than the root node’s key and 18 | the right subtree of root node contains node 19 | with key greater than the root node’s key. 20 | Hence, the tree is a BST. 21 | 22 | Example 2: 23 | 24 | Input: 25 | 2 26 | \ 27 | 7 28 | \ 29 | 6 30 | \ 31 | 5 32 | \ 33 | 9 34 | \ 35 | 2 36 | \ 37 | 6 38 | Output: 0 39 | Explanation: 40 | Since the node with value 7 has right subtree 41 | nodes with keys less than 7, this is not a BST. 42 | Your Task: 43 | You don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree as a parameter and returns true if the given binary tree is BST, else returns false. 44 | 45 | Expected Time Complexity: O(N). 46 | Expected Auxiliary Space: O(Height of the BST). 47 | 48 | 49 | -------------------------------------------------------------------------------- /CompanywiseSolution/Amazon/check_for_BST/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to check whether a Binary Tree is BST or not. 5 | bool helper(Node* root, int min, int max){ 6 | if (root == NULL){ 7 | return true; 8 | } 9 | if (root->data < min ){ 10 | return false; 11 | } 12 | if (root->data >= max){ 13 | return false; 14 | } 15 | return helper(root->left, min, root->data) && helper(root->right, root->data, max); 16 | 17 | } 18 | bool isBST(Node* root) 19 | { 20 | // Your code here 21 | int min = -1000001; 22 | int max = 1000001; 23 | 24 | return helper(root, min, max); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Question.txt: -------------------------------------------------------------------------------- 1 | Kadane’s Algorithm: 2 | 3 | Initialize: 4 | max_so_far = INT_MIN 5 | max_ending_here = 0 6 | 7 | Loop for each element of the array 8 | (a) max_ending_here = max_ending_here + a[i] 9 | (b) if(max_so_far < max_ending_here) 10 | max_so_far = max_ending_here 11 | (c) if(max_ending_here < 0) 12 | max_ending_here = 0 13 | return max_so_far 14 | 15 | Explanation: 16 | The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far 17 | 18 | Lets take the example: 19 | {-2, -3, 4, -1, -2, 1, 5, -3} 20 | 21 | max_so_far = max_ending_here = 0 22 | 23 | for i=0, a[0] = -2 24 | max_ending_here = max_ending_here + (-2) 25 | Set max_ending_here = 0 because max_ending_here < 0 26 | 27 | for i=1, a[1] = -3 28 | max_ending_here = max_ending_here + (-3) 29 | Set max_ending_here = 0 because max_ending_here < 0 30 | 31 | for i=2, a[2] = 4 32 | max_ending_here = max_ending_here + (4) 33 | max_ending_here = 4 34 | max_so_far is updated to 4 because max_ending_here greater 35 | than max_so_far which was 0 till now 36 | 37 | for i=3, a[3] = -1 38 | max_ending_here = max_ending_here + (-1) 39 | max_ending_here = 3 40 | 41 | for i=4, a[4] = -2 42 | max_ending_here = max_ending_here + (-2) 43 | max_ending_here = 1 44 | 45 | for i=5, a[5] = 1 46 | max_ending_here = max_ending_here + (1) 47 | max_ending_here = 2 48 | 49 | for i=6, a[6] = 5 50 | max_ending_here = max_ending_here + (5) 51 | max_ending_here = 7 52 | max_so_far is updated to 7 because max_ending_here is 53 | greater than max_so_far 54 | 55 | for i=7, a[7] = -3 56 | max_ending_here = max_ending_here + (-3) 57 | max_ending_here = 4 58 | -------------------------------------------------------------------------------- /CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Solution.java.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | // Java program to print largest contiguous array sum 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 | -------------------------------------------------------------------------------- /CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt: -------------------------------------------------------------------------------- 1 | Given a string S. The task is to convert characters of string to lowercase. 2 | 3 | Example 1: 4 | 5 | Input: S = "ABCddE" 6 | Output: "abcdde" 7 | Explanation: A, B, C and E are converted to 8 | a, b, c and E thus all uppercase characters 9 | of the string converted to lowercase letter. 10 | Example 2: 11 | 12 | Input: S = "LMNOppQQ" 13 | Output: "lmnoppqq" 14 | Explanation: L, M, N, O, and Q are 15 | converted to l, m, n, o and q thus 16 | all uppercase characters of the 17 | string converted to lowercase letter. 18 | Your Task: 19 | You dont need to read input or print anything. Complete the function toLower() which takes S as input parameter and returns the converted string. 20 | 21 | Expected Time Complexity:O(n) 22 | Expected Auxiliary Space: O(1) 23 | 24 | Constraints: 25 | 1 <= |S| <= 1000 -------------------------------------------------------------------------------- /CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java: -------------------------------------------------------------------------------- 1 | // Initial template for Java 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | class GFG { 7 | public static void main(String args[]) throws IOException { 8 | BufferedReader read = 9 | new BufferedReader(new InputStreamReader(System.in)); 10 | System.out.println("Enter no of words you want to check"); 11 | int t = Integer.parseInt(read.readLine()); 12 | 13 | while (t-- > 0) { 14 | System.out.println("Enter Word to conver to lowercase"); 15 | String S = read.readLine(); 16 | Solution ob = new Solution(); 17 | 18 | System.out.println(ob.toLower(S)); 19 | } 20 | } 21 | }// } Driver Code Ends 22 | 23 | 24 | // User function template for Java 25 | 26 | class Solution { 27 | static String toLower(String S) { 28 | String S1=S.toLowerCase(); 29 | return S1; 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /CompanywiseSolution/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /CompanywiseSolution/deshaw/question.txt: -------------------------------------------------------------------------------- 1 | Search a number in a sorted rotated array. Basically an array is given 2 | and its is rotated or pivoted from a certain index . Basically we have ro 3 | tell that an element is present or not in that array 4 | 5 | sample input 6 | input line 1- enter the number of elements 7 | input line 2-enter the key needed to find 8 | input line 3- enter all the elements to this 9 | 10 | 11 | output line 1-basically print the index of the element if present 12 | else print a -1 if not present 13 | 14 | example1- 15 | input 16 | 9 17 | 10 18 | 5 6 7 8 9 10 1 2 3 19 | 20 | output-5 21 | 22 | example-2 23 | 9 24 | 15 25 | 5 6 7 8 9 10 1 2 3 26 | 27 | output- (-1) 28 | 29 | -------------------------------------------------------------------------------- /CompanywiseSolution/deshaw/search_in_a_sortedarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | #define pb push_back 8 | #define fz(i,a,b) for(ll i=a; i=b; i--) 10 | #define debug(x) cout << #x << " " << x << endl; 11 | typedef long long int ll; 12 | typedef long double lld; 13 | 14 | /*#define debug(x); 15 | printf(x);*/ 16 | 17 | void init() 18 | { 19 | #ifndef ONLINE_JUDGE 20 | freopen("input.txt" , "r" ,stdin); 21 | freopen("output.txt" , "w" ,stdout); 22 | #endif 23 | 24 | } 25 | 26 | void debugger() 27 | { 28 | #ifndef ONLINE_JUDGE 29 | freopen("input.txt" , "r" ,stdin); 30 | freopen("output.txt" , "w" ,stdout); 31 | #endif 32 | #ifdef debugger 33 | #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; 34 | #else 35 | #define debugger(x); 36 | #endif 37 | } 38 | 39 | 40 | const int MAXN = (int)((1e5) + 100); 41 | int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);} 42 | int max(int a, int b) {if (a > b) return a; else return b;} 43 | int min(int a, int b) {if (a < b) return a; else return b;} 44 | 45 | 46 | void precision(int a) 47 | { 48 | cout << setprecision(a) << fixed; 49 | } 50 | 51 | 52 | //** pritishcf307 **// 53 | //**------------------------------------------------------------------------------------------------------**// 54 | 55 | 56 | 57 | int main() 58 | { 59 | init(); 60 | 61 | ll n; 62 | cin >> n; 63 | ll x; 64 | cin >> x; 65 | bool found=false; 66 | vector v; 67 | for(int i=0;i> a; 71 | v.push_back(a); 72 | } 73 | 74 | ll lo=0; 75 | ll hi=n-1; 76 | ll mid,ans; 77 | 78 | while(hi-lo >= 0) 79 | { 80 | mid=(lo+hi)/2; 81 | if(v[mid]==x) 82 | { 83 | found=true; 84 | ans=mid; 85 | break; 86 | } 87 | //left part is sorted 88 | else if(v[lo] <= v[mid]) 89 | { 90 | if(x>=v[lo] && x<=v[mid]) 91 | { 92 | hi=mid-1; 93 | } 94 | else 95 | { 96 | lo=mid+1; 97 | } 98 | } 99 | else 100 | { 101 | if(x>=v[mid] && x<=v[hi]) 102 | { 103 | lo=mid+1; 104 | } 105 | else 106 | { 107 | hi=mid-1; 108 | } 109 | } 110 | } 111 | if(found==true) 112 | { 113 | cout << ans << endl; 114 | } 115 | else 116 | { 117 | cout << -1 << endl; 118 | } 119 | return 0; 120 | } 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /Competitive programming/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drishyadamodaran/hacktoberfest2021_CP/5154a57d7453121b903eb4f485579db6c2c909fc/Competitive programming/.DS_Store -------------------------------------------------------------------------------- /Competitive programming/C#/FindElementInArray.cs: -------------------------------------------------------------------------------- 1 | # Question is how to find a element in an array 2 | 3 | using System; 4 | using System.Linq; 5 | 6 | 7 | public static class Extensions 8 | { 9 | public static bool find(this T[] array, T target) { 10 | return array.Contains(target); 11 | } 12 | } 13 | 14 | public class FindElement 15 | { 16 | public static bool Find(int target, int[] array) 17 | { 18 | bool exists = array.find(target); 19 | return exists; 20 | } 21 | 22 | public static void Test() 23 | { 24 | int[] array = { 1, 2, 3, 4, 5 }; 25 | 26 | if(Find(4, array)) 27 | { 28 | Console.WriteLine("Found Element"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Competitive programming/C#/README.md: -------------------------------------------------------------------------------- 1 | # hacktoberfest2021_CP 2 | You can contribute competitive programming in C# here. 3 | 4 | ## Basics of Git and GitHub 5 | ### Git & GitHub 6 | Before we proceed, it's better to know the difference between Git and Github. Git is a version control system (VCS) that allows us to keep track of the history of our source code , whereas GitHub is a service that hosts Git projects. 7 | 8 | We assume you have created an account on Github and installed Git on your System. 9 | 10 | Now enter your name and E-mail (used on Github) address in Git, by using following command. 11 | 12 | `$ git config --global user.name "YOUR NAME"` `$ git config --global user.email "YOUR EMAIL ADDRESS"` 13 | This is an important step to mark your commits to your name and email. 14 | 15 | 16 | ### Fork a project 17 | You can make a copy of the project to your account. This process is called forking a project to your Github account. On Upper right side of project page on Github, you can see. 18 | Click on fork to create a copy of project to your account. This creates a separate copy for you to work on. 19 | 20 | ### Clone the forked project 21 | You have forked the project you want to contribute to your github account. To get this project on your development machine we use clone command of git. 22 | 23 | `$ git clone https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 24 | Now you have the project on your local machine. 25 | 26 | 27 | ### Add a remote (upstream) to original project repository 28 | Remote means the remote location of project on Github. By cloning, we have a remote called origin which points to your forked repository. Now we will add a remote to the original repository from where we had forked. 29 | 30 | `$ cd ` `$ git remote add upstream https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 31 | You will see the benefits of adding remote later. 32 | 33 | ### Synchronizing your fork 34 | Open Source projects have a number of contributors who can push code anytime. So it is necessary to make your forked copy equal with the original repository. The remote added above called Upstream helps in this. 35 | 36 | `$ git checkout main` `$ git fetch upstream` `$ git merge upstream/main` `$ git push origin main` 37 | The last command pushes the latest code to your forked repository on Github. The origin is the remote pointing to your forked repository on github. 38 | 39 | 40 | Create a new branch for a feature or bugfix 41 | Usually, all repositories have a main branch that is regarded to be stable, and any new features should be developed on a separate branch before being merged into the main branch. As a result, we should establish a new branch for our feature or bugfix and go to work on the issue. 42 | 43 | `$ git checkout -b ` This will create a new branch out of master branch. Now start working on the problem and commit your changes. 44 | 45 | `$ git add --all` `$ git commit -m ""` The first command adds all the files or you can add specific files by removing -a and adding the file names. The second command gives a message to your changes so you can know in future what changes this commit makes. If you are solving an issue on original repository, you should add the issue number like #35 to your commit message. This will show the reference to commits in the issue. 46 | 47 | 48 | ### Push code and create a pull request 49 | You now have a new branch containing the modifications you want in the project you forked. Now, push your new branch to your remote github fork. 50 | 51 | `$ git push origin ` Now you are ready to help the project by opening a pull request means you now tell the project managers to add the feature or bug fix to original repository. You can open a pull request by clicking on green icon - 52 | 53 | 54 | 55 | Remember your upstream base branch should be main and source should be your feature branch. Click on create pull request and add a name to your pull request. You can also describe your feature. 56 | 57 | Fantastic! You've already made your first contribution.🥳 58 | 59 | BE OPEN! 60 | Happy Coding!💻 61 | 62 | -------------------------------------------------------------------------------- /Competitive programming/C++/ADACRA.cpp: -------------------------------------------------------------------------------- 1 | // The problem link is https://www.codechef.com/problems/ADACRA 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | int t; 8 | cin >> t; 9 | while(t--){ 10 | int count_u = 0, count_d = 0; 11 | string S; 12 | cin >> S; 13 | for(int i = 1; i < S.length(); i++){ 14 | if(S[i]!=S[i+1]){ 15 | if(S[i]=='U'){ 16 | count_u += 1; 17 | } 18 | else{ 19 | count_d += 1; 20 | } 21 | } 22 | } 23 | if(S[0] == 'U'){ 24 | count_u += 1; 25 | } 26 | else{ 27 | count_d += 1; 28 | } 29 | int ans = min(count_d, count_u); 30 | cout << ans << "\n"; 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Competitive programming/C++/Arrays_Left_Rotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n,d,x; 9 | cin>>n>>d; 10 | vector a; 11 | for(int i=0;i>x; 13 | a.push_back(x); 14 | } 15 | 16 | vector b; 17 | // //int n = a.size(); 18 | int k = d%n; 19 | //b[0] = a[k]; 20 | b.push_back(a[k]); 21 | for(int i=k+1;i 4 | 5 | using namespace std; 6 | 7 | int stockBuySell(int arr[],int n) 8 | { 9 | int max_profit =0; 10 | int minSofar=arr[0]; 11 | for(int i=0;i 2 | using namespace std ; 3 | 4 | #define ff first 5 | #define ss second 6 | #define ull unsigned long long 7 | #define mod 1000000007 8 | #define inf 1e18 9 | #define w(x) int x;cin>>x;while(x--) 10 | #define f(x,y) for( x=0;x>a>>b; 17 | s1=ceil((b-(a-1))/2)+ceil(((a-1)-a)/2); 18 | s2=ceil((b-(a+1))/2)+ceil(((a+1)-a)/2); 19 | // cout<<"i is "<b){ 26 | x=s1; 27 | } 28 | else{ 29 | x=s2; 30 | } cout<https://codeforces.com/contest/1560/problem/B 2 | //Who's opposite 3 | #include 4 | using namespace std; 5 | int main(){ 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | int a,b,c; 10 | cin>>a>>b>>c; 11 | int s=2*(abs(a-b)); 12 | if(a<=s && b<=s && c<=s){ 13 | if((s/2+c)>s){ 14 | cout< 2 | using namespace std; 3 | 4 | int countStepsToOne(int n) 5 | { 6 | int arr[n+1]; 7 | for(int i = 0; i> n; 41 | cout << countStepsToOne(n); 42 | } -------------------------------------------------------------------------------- /Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md: -------------------------------------------------------------------------------- 1 | Code : Min Steps to 1 using DP 2 | 3 | Given a positive integer 'n', find and return the minimum number of steps that 'n' has to take to get reduced to 1. You can perform any one of the following 3 steps: 4 | 1.) Subtract 1 from it. (n = n - ­1) , 5 | 2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) , 6 | 3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ). 7 | Input format : 8 | The first and the only line of input contains an integer value, 'n'. 9 | Output format : 10 | Print the minimum number of steps. 11 | Constraints : 12 | 1 <= n <= 10 ^ 6 13 | Time Limit: 1 sec 14 | Sample Input 1 : 15 | 4 16 | Sample Output 1 : 17 | 2 18 | Explanation of Sample Output 1 : 19 | For n = 4 20 | Step 1 : n = 4 / 2 = 2 21 | Step 2 : n = 2 / 2 = 1 22 | Sample Input 2 : 23 | 7 24 | Sample Output 2 : 25 | 3 26 | Explanation of Sample Output 2 : 27 | For n = 7 28 | Step 1 : n = 7 ­- 1 = 6 29 | Step 2 : n = 6 / 3 = 2 30 | Step 3 : n = 2 / 2 = 1 -------------------------------------------------------------------------------- /Competitive programming/C++/FLOW017.cpp: -------------------------------------------------------------------------------- 1 | // The problem link is https://www.codechef.com/problems/FLOW017 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | long long int t, a, b, c; 7 | cin >> t; 8 | for(int i = 0; i < t; i++){ 9 | cin >> a >> b >> c; 10 | if(a < max(b,c) && a > min(b,c)){ 11 | cout< min(a,c) && b < max(a,c)){ 14 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | long double factorial = 1.0; 7 | 8 | cout << "Enter a positive integer: "; 9 | cin >> n; 10 | 11 | if (n < 0) 12 | cout << "Error! Factorial of a negative number doesn't exist."; 13 | else { 14 | for(int i = 1; i <= n; ++i) { 15 | factorial *= i; 16 | } 17 | cout << "Factorial of " << n << " = " << factorial; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Competitive programming/C++/FakeGCD.cpp: -------------------------------------------------------------------------------- 1 | // This is the link to the problem : https://www.codechef.com/COOK133C/problems/FAKEGCD 2 | // Below is my solution 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | int t; 8 | cin >> t; 9 | 10 | while(t--) 11 | { 12 | int n; 13 | cin >> n; 14 | 15 | int k=1; 16 | 17 | for(int i=0; i 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | int x; 8 | float y,d; 9 | cin>>x; 10 | cin>>y; 11 | d=x+0.50; 12 | if(d>y||x%5!=0) 13 | { 14 | cout< 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | int isOperand(char x) 15 | { 16 | if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^' || x == '(' || x == ')') 17 | { 18 | return 0; 19 | } 20 | return 1; 21 | } 22 | 23 | int outPrecedence(char x) 24 | { 25 | if (x == '+' || x == '-') 26 | { 27 | return 1; 28 | } 29 | else if (x == '*' || x == '/') 30 | { 31 | return 3; 32 | } 33 | else if (x == '^') 34 | { 35 | return 6; 36 | } 37 | else if (x == '(') 38 | { 39 | return 7; 40 | } 41 | else if (x == ')') 42 | { 43 | return 0; 44 | } 45 | return -1; 46 | } 47 | 48 | int inPrecedence(char x) 49 | { 50 | if (x == '+' || x == '-') 51 | { 52 | return 2; 53 | } 54 | else if (x == '*' || x == '/') 55 | { 56 | return 4; 57 | } 58 | else if (x == '^') 59 | { 60 | return 5; 61 | } 62 | else if (x == '(') 63 | { 64 | return 0; 65 | } 66 | return -1; 67 | } 68 | 69 | char *convert(char *infix) 70 | { 71 | char *postfix = new char[strlen(infix) + 1]; 72 | 73 | stack stk; 74 | 75 | int i = 0; 76 | int j = 0; 77 | 78 | while (infix[i] != '\0') 79 | { 80 | if (isOperand(infix[i])) 81 | { 82 | postfix[j++] = infix[i++]; 83 | } 84 | else 85 | { 86 | if (stk.empty() || outPrecedence(infix[i]) > inPrecedence(stk.top())) 87 | { 88 | stk.push(infix[i++]); 89 | } 90 | else if (outPrecedence(infix[i]) == inPrecedence(stk.top())) 91 | { 92 | stk.pop(); 93 | } 94 | else 95 | { 96 | postfix[j++] = stk.top(); 97 | stk.pop(); 98 | } 99 | } 100 | } 101 | 102 | while (!stk.empty() && stk.top() != ')') 103 | { 104 | postfix[j++] = stk.top(); 105 | stk.pop(); 106 | } 107 | 108 | postfix[j] = '\0'; 109 | 110 | return postfix; 111 | } 112 | 113 | int main() 114 | { 115 | ios_base::sync_with_stdio(false); 116 | cin.tie(NULL); 117 | 118 | char infix[] = "((a+b)*c)-d^e^f"; 119 | 120 | cout << convert(infix) << endl; 121 | } -------------------------------------------------------------------------------- /Competitive programming/C++/Kindergarten_Adventures.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int N; 6 | cin >> N; 7 | vector A(N); 8 | for(int i = 0; i < N; i++) { 9 | cin >> A[i]; 10 | } 11 | 12 | int start = 0; 13 | 14 | vector D(N+1, 0); 15 | for(int i = 0; i < N; i++) { 16 | if(A[i] <= i) { 17 | start++; 18 | D[i-A[i]]--; 19 | D[i]++; 20 | } else { 21 | D[i-A[i]+N]--; 22 | D[i]++; 23 | } 24 | } 25 | 26 | int best = start; 27 | int bi = 0; 28 | int cur = start; 29 | for(int i = 0; i < N; i++) { 30 | if(cur > best) { 31 | best = cur; 32 | bi = i; 33 | } 34 | cur += D[i]; 35 | } 36 | 37 | cout << (bi+1) << endl; 38 | } -------------------------------------------------------------------------------- /Competitive programming/C++/LazySegmentedTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define inf 1e18 6 | 7 | 8 | int lazy[10000] = {0}; 9 | void lazyUpdate(int tree[], int s, int e, int l, int r, int val , int index) { 10 | if (lazy[index] != 0) { 11 | tree[index] += lazy[index]; 12 | if (e != s) { 13 | lazy[2 * index] += lazy[index]; 14 | lazy[2 * index + 1] += lazy[index]; 15 | } 16 | lazy[index] = 0; 17 | } 18 | 19 | if (s > r or e < l) return; 20 | 21 | if (s >= l and e <= r) { 22 | tree[index] += val; 23 | if (e != s) { 24 | lazy[2 * index] += val; 25 | lazy[2 * index + 1] += val; 26 | } 27 | return; 28 | } 29 | 30 | int mid = (s + e) / 2; 31 | lazyUpdate(tree, s, mid, l, r, val, 2 * index); 32 | lazyUpdate(tree, mid + 1, e, l, r, val, 2 * index + 1); 33 | tree[index] = min(tree[2 * index], tree[2 * index + 1]); 34 | return; 35 | } 36 | 37 | int lazyQuery(int tree[], int s, int e, int l, int r, int index) { 38 | if (lazy[index] != 0) { 39 | tree[index] += lazy[index]; 40 | if (e != s) { 41 | lazy[2 * index] = lazy[index]; 42 | lazy[2 * index + 1] = lazy[index]; 43 | } 44 | lazy[index] = 0; 45 | } 46 | 47 | if (s > r or e < l) return inf; 48 | if (s >= l and e <= r) return tree[index]; 49 | 50 | int mid = (s + e) / 2; 51 | int left = lazyQuery(tree, s, mid, l, r, 2 * index); 52 | int right = lazyQuery(tree, mid + 1, e, l, r, 2 * index + 1); 53 | return min(left, right); 54 | 55 | 56 | } 57 | 58 | void build(int a[], int tree[], int s, int e, int index) { 59 | if (s == e) { 60 | tree[index] = a[e]; 61 | return; 62 | } 63 | int mid = (s + e) / 2; 64 | build(a, tree, s, mid, 2 * index); 65 | build(a, tree, mid + 1, e, 2 * index + 1); 66 | tree[index] = min(tree[2 * index], tree[2 * index + 1]); 67 | return; 68 | } 69 | 70 | 71 | int32_t main() 72 | { 73 | //An example of implementing this code 74 | // int a[] = {1, 3, 2, -5, 6, 4}; 75 | // int n = sizeof(a) / sizeof(int); 76 | // int tree[4 * n + 1]; 77 | // build(a, tree, 0, n - 1, 1); 78 | // lazyUpdate(tree, 0, n - 1, 0, 2, 10, 1); 79 | // return 0; 80 | } 81 | -------------------------------------------------------------------------------- /Competitive programming/C++/MajorityElementInarray: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void findMajority(int arr[], int size) 5 | { 6 | unordered_map m; 7 | for(int i = 0; i < size; i++) 8 | m[arr[i]]++; 9 | int count = 0; 10 | for(auto i : m) 11 | { 12 | if(i.second > size / 2) 13 | { 14 | count =1; 15 | cout << "Majority found :" << i.first< 5 | 6 | using namespace std; 7 | 8 | int maxSubArraySum(int arr[],int n) 9 | { 10 | int maxSum =0 ; 11 | int currSum=0; 12 | for(int i=0;imaxSum) 16 | { 17 | maxSum=currSum; 18 | } 19 | if(currSum<0) 20 | { 21 | currSum=0; 22 | } 23 | 24 | } 25 | return maxSum; 26 | } 27 | int main() 28 | { 29 | int arr[] = {5,-4,-2,6,-1}; 30 | int n = sizeof(arr)/sizeof(arr[0]); 31 | int maxsum = maxSubArraySum(arr, n); 32 | cout << "Maximum subarray sum is " << maxsum; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Competitive programming/C++/Move all zeroes to end: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | void pushZerosToEnd(int arr[], int n) 7 | { 8 | int count = 0; // Count of non-zero elements 9 | 10 | 11 | for (int i = 0; i < n; i++) 12 | if (arr[i] != 0) 13 | arr[count++] = arr[i]; // here count is 14 | // incremented 15 | 16 | 17 | while (count < n) 18 | arr[count++] = 0; 19 | } 20 | 21 | 22 | int main() 23 | { 24 | int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; 25 | int n = sizeof(arr) / sizeof(arr[0]); 26 | pushZerosToEnd(arr, n); 27 | cout << "Array after pushing all zeros to end of array :\n"; 28 | for (int i = 0; i < n; i++) 29 | cout << arr[i] << " "; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Competitive programming/C++/Move the elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sample Input 3 | 4 | 10 5 | -6 7 13 10 -8 15 5 -9 2 -1 6 | Sample Output 7 | 8 | 7 9 | 13 10 | 10 11 | 15 12 | 5 13 | 2 14 | -6 15 | -8 16 | -9 17 | -1 18 | */ 19 | 20 | void moveElements(int arr[], int n){ 21 | int key,j; 22 | for (int i = 0; i < n; i++) 23 | { 24 | key = arr[i]; 25 | j = i-1; 26 | while (j>=0 && arr[j]<0 && key>=0) 27 | { 28 | arr[j+1] = arr[j]; 29 | j--; 30 | } 31 | arr[j+1] = key; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Competitive programming/C++/Permutation Minimization by Deque.c: -------------------------------------------------------------------------------- 1 | //https://codeforces.com/contest/1579/problem/E1 2 | 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int t; 8 | cin>>t; 9 | while(t--) 10 | { 11 | int n; 12 | cin>>n; 13 | deque v; 14 | for(int i=0;i>x; 18 | if(i==0) 19 | v.push_back(x); 20 | 21 | int x1=v[0]; 22 | int x2=v[v.size()-1]; 23 | if(i!=0) 24 | { 25 | if(x==x1) 26 | v.push_front(x); 27 | else if (x==x2) 28 | v.push_back(x); 29 | if(xx2 && x>x1) 35 | v.push_back(x); 36 | else if(x>x1 && xx2 && x 3 | using namespace std; 4 | void printSubsetsOfArray(int input[], int size,int output[],int len) { 5 | if(size==0){ 6 | for(int i=0;i> length; 25 | for(int i=0; i < length; i++) 26 | cin >> input[i]; 27 | printSubsetsOfArray(input, length); 28 | } 29 | -------------------------------------------------------------------------------- /Competitive programming/C++/Print all Codes - String(C++)): -------------------------------------------------------------------------------- 1 | Question: Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. 2 | You are given a numeric string S. Write a program to print the list of all possible codes that can be generated from the given string. 3 | 4 | Solution: 5 | 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | char itoc(int i){ //int to char 12 | char c = 'a'+i-1; 13 | return c; 14 | } 15 | int ctoi(char a){ //char to int 16 | int i = a - '0'; 17 | return i; 18 | } 19 | 20 | void helper(string input,string output){ 21 | if(input.length()==0){ 22 | cout<1){ 33 | 34 | if(ctoi(input[0])*10+ctoi(input[1])>=10 &&ctoi(input[0])*10+ctoi(input[1])<=26){ 35 | char c2 = itoc(ctoi(input[0])*10+ctoi(input[1])); 36 | //output = output+c2; 37 | helper(input.substr(2),output+c2); 38 | //print(output); 39 | } 40 | } 41 | 42 | } 43 | void printAllPossibleCodes(string input) { 44 | /* 45 | Given the input as a string, print all its possible combinations. You do not need to return anything. 46 | */ 47 | string output; 48 | helper(input,output); 49 | } 50 | 51 | int main(){ 52 | string input; 53 | cin >> input; 54 | 55 | printAllPossibleCodes(input); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Competitive programming/C++/README.md: -------------------------------------------------------------------------------- 1 | # hacktoberfest2021_CP 2 | You can contribute competitive programming in c++ 3 | 4 | ## Basics of Git and GitHub 5 | ### Git & GitHub 6 | Before we proceed, it's better to know the difference between Git and Github. Git is a version control system (VCS) that allows us to keep track of the history of our source code , whereas GitHub is a service that hosts Git projects. 7 | 8 | We assume you have created an account on Github and installed Git on your System. 9 | 10 | Now enter your name and E-mail (used on Github) address in Git, by using following command. 11 | 12 | `$ git config --global user.name "YOUR NAME"` `$ git config --global user.email "YOUR EMAIL ADDRESS"` 13 | This is an important step to mark your commits to your name and email. 14 | 15 | 16 | ### Fork a project 17 | You can make a copy of the project to your account. This process is called forking a project to your Github account. On Upper right side of project page on Github, you can see. 18 | Click on fork to create a copy of project to your account. This creates a separate copy for you to work on. 19 | 20 | ### Clone the forked project 21 | You have forked the project you want to contribute to your github account. To get this project on your development machine we use clone command of git. 22 | 23 | `$ git clone https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 24 | Now you have the project on your local machine. 25 | 26 | 27 | ### Add a remote (upstream) to original project repository 28 | Remote means the remote location of project on Github. By cloning, we have a remote called origin which points to your forked repository. Now we will add a remote to the original repository from where we had forked. 29 | 30 | `$ cd ` `$ git remote add upstream https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 31 | You will see the benefits of adding remote later. 32 | 33 | ### Synchronizing your fork 34 | Open Source projects have a number of contributors who can push code anytime. So it is necessary to make your forked copy equal with the original repository. The remote added above called Upstream helps in this. 35 | 36 | `$ git checkout main` `$ git fetch upstream` `$ git merge upstream/main` `$ git push origin main` 37 | The last command pushes the latest code to your forked repository on Github. The origin is the remote pointing to your forked repository on github. 38 | 39 | 40 | Create a new branch for a feature or bugfix 41 | Usually, all repositories have a main branch that is regarded to be stable, and any new features should be developed on a separate branch before being merged into the main branch. As a result, we should establish a new branch for our feature or bugfix and go to work on the issue. 42 | 43 | `$ git checkout -b ` This will create a new branch out of master branch. Now start working on the problem and commit your changes. 44 | 45 | `$ git add --all` `$ git commit -m ""` The first command adds all the files or you can add specific files by removing -a and adding the file names. The second command gives a message to your changes so you can know in future what changes this commit makes. If you are solving an issue on original repository, you should add the issue number like #35 to your commit message. This will show the reference to commits in the issue. 46 | 47 | 48 | ### Push code and create a pull request 49 | You now have a new branch containing the modifications you want in the project you forked. Now, push your new branch to your remote github fork. 50 | 51 | `$ git push origin ` Now you are ready to help the project by opening a pull request means you now tell the project managers to add the feature or bug fix to original repository. You can open a pull request by clicking on green icon - 52 | 53 | 54 | 55 | Remember your upstream base branch should be main and source should be your feature branch. Click on create pull request and add a name to your pull request. You can also describe your feature. 56 | 57 | Fantastic! You've already made your first contribution.🥳 58 | 59 | BE OPEN! 60 | Happy Coding!💻 61 | 62 | -------------------------------------------------------------------------------- /Competitive programming/C++/Reverse_a_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n, reversedNumber = 0, remainder; 6 | 7 | cout << "Enter an integer: "; 8 | cin >> n; 9 | 10 | while(n != 0) { 11 | remainder = n%10; 12 | reversedNumber = reversedNumber*10 + remainder; 13 | n /= 10; 14 | } 15 | 16 | cout << "Reversed Number = " << reversedNumber; 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Competitive programming/C++/Search an element in sorted and rotated array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int Search(vector ,int ); 5 | 6 | int main(){ 7 | 8 | int t; 9 | cin >> t; 10 | 11 | while(t--){ 12 | int n; 13 | cin >> n; 14 | 15 | vector vec(n); 16 | 17 | for(int i =0;i> vec[i]; 19 | 20 | int target; 21 | cin >> target; 22 | 23 | cout << Search(vec,target) << "\n"; 24 | 25 | } 26 | } 27 | 28 | 29 | // vec : given vector of elements 30 | // K : given value whose index we need to find 31 | int Search(vector vec, int k) { 32 | //code here - rahul 33 | int low=0, mid; 34 | int high=vec.size()-1; 35 | while(low<=high) 36 | { 37 | mid=(low+high)/2; 38 | if(vec[mid]==k) 39 | return mid; 40 | if(vec[low]<=vec[mid]) 41 | { 42 | if(k=vec[low]) 43 | { high=mid-1; } 44 | else 45 | { low=mid+1; } 46 | 47 | } 48 | else 49 | { 50 | if(k>vec[mid]&& k<=vec[high]) 51 | { low=mid+1; } 52 | else 53 | { high=mid-1; } 54 | } 55 | 56 | } 57 | return -1; 58 | } 59 | -------------------------------------------------------------------------------- /Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t,i,j,k;; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int n,c=0; 10 | cin>>n; 11 | int A[n]; 12 | for(i=1;i<=n;i++) 13 | { 14 | cin>>A[i]; 15 | } 16 | for(i=1;i<=n;i++) 17 | { 18 | if(i%2==1) 19 | { 20 | for(j=1;j<=n;j++) 21 | { 22 | if(A[j]>0) 23 | { 24 | if(A[j]%2==0) 25 | { 26 | c++; 27 | A[j]=0; 28 | break; 29 | } 30 | } 31 | } 32 | } 33 | else if(i%2==0) 34 | { 35 | for(j=1;j<=n;j++) 36 | { 37 | if(A[j]>0) 38 | { 39 | if(A[j]%2==1) 40 | { 41 | c++; 42 | A[j]=0; 43 | break; 44 | } 45 | } 46 | } 47 | } 48 | 49 | } 50 | cout< 3 | using namespace std; 4 | 5 | bool subArrayExists(int arr[], int n) 6 | { 7 | unordered_set sumSet; 8 | 9 | 10 | int sum = 0; 11 | for (int i = 0; i < n; i++) 12 | { 13 | sum += arr[i]; 14 | 15 | 16 | if (sum == 0 17 | || sumSet.find(sum) 18 | != sumSet.end()) 19 | return true; 20 | 21 | sumSet.insert(sum); 22 | } 23 | return false; 24 | } 25 | 26 | int main() 27 | { 28 | int arr[] = { -3, 2, -1, -1, 6 }; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | if (subArrayExists(arr, n)) 31 | cout << "Found a subarray"; 32 | else 33 | cout << "No Such Sub Array "; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Competitive programming/C++/Symmetric_Tree.cpp: -------------------------------------------------------------------------------- 1 | // Link for Question-->https://leetcode.com/problems/symmetric-tree/ 2 | class Solution { 3 | public: 4 | bool isSymmetric(TreeNode* root) { 5 | return check(root->left,root->right); 6 | } 7 | bool check(TreeNode* r1,TreeNode* r2){ 8 | if(r1==NULL && r2==NULL)// if left and root null 9 | { 10 | return true; 11 | } 12 | else if(r1==NULL || r2==NULL || r1->val!=r2->val) //one is not null 13 | { 14 | return false; 15 | } 16 | else{ 17 | //comparing left subtree's left child with right subtree's 18 | //right child AND comparing left subtree's right child with right subtree's left child 19 | return check(r1->left,r2->right) && check(r1->right,r2->left); 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Competitive programming/C++/Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "QueueCpp.h" 4 | using namespace std; 5 | class Tree 6 | { 7 | Node *root; 8 | 9 | public: 10 | Tree() { root = NULL; } 11 | void CreateTree(); 12 | void Preorder() { Preorder(root); } 13 | void Preorder(Node *p); 14 | void Postorder() { Postorder(root); } 15 | void Postorder(Node *p); 16 | void Inorder() { Inorder(root); } 17 | void Inorder(Node *p); 18 | void Levelorder() { Levelorder(root); } 19 | void Levelorder(Node *p); 20 | int Height() { return Height(root); } 21 | int Height(Node *root); 22 | }; 23 | void Tree::CreateTree() 24 | { 25 | Node *p, *t; 26 | int x; 27 | Queue q(100); 28 | printf("Enter root value "); 29 | scanf("%d", &x); 30 | root = new Node; 31 | root->data = x; 32 | root->lchild = root->rchild = NULL; 33 | q.enqueue(root); 34 | while (!q.isEmpty()) 35 | { 36 | p = q.dequeue(); 37 | printf("Enter left child of %d ", p->data); 38 | scanf("%d", &x); 39 | if (x != -1) 40 | { 41 | t = new Node; 42 | t->data = x; 43 | t->lchild = t->rchild = NULL; 44 | p->lchild = t; 45 | q.enqueue(t); 46 | } 47 | printf("eneter right child of %d ", p->data); 48 | scanf("%d", &x); 49 | if (x != -1) 50 | { 51 | t = new Node; 52 | t->data = x; 53 | t->lchild = t->rchild = NULL; 54 | p->rchild = t; 55 | q.enqueue(t); 56 | } 57 | } 58 | } 59 | void Tree::Preorder(struct Node *p) 60 | { 61 | if (p) 62 | { 63 | printf("%d ", p->data); 64 | Preorder(p->lchild); 65 | Preorder(p->rchild); 66 | } 67 | } 68 | void Tree::Inorder(struct Node *p) 69 | { 70 | if (p) 71 | { 72 | Inorder(p->lchild); 73 | printf("%d ", p->data); 74 | Inorder(p->rchild); 75 | } 76 | } 77 | void Tree::Postorder(struct Node *p) 78 | { 79 | if (p) 80 | { 81 | Postorder(p->lchild); 82 | Postorder(p->rchild); 83 | printf("%d ", p->data); 84 | } 85 | } 86 | void Tree::Levelorder(struct Node *root) 87 | { 88 | Queue q(100); 89 | printf("%d ", root->data); 90 | q.enqueue(root); 91 | while (!q.isEmpty(q)) 92 | { 93 | root = q.dequeue(); 94 | if (root->lchild) 95 | { 96 | printf("%d ", root->lchild->data); 97 | q.enqueue(root->lchild); 98 | } 99 | if (root->rchild) 100 | { 101 | printf("%d ", root->rchild->data); 102 | q.enqueue(root->rchild); 103 | } 104 | } 105 | } 106 | int Tree::Height(struct Node *root) 107 | { 108 | int x = 0, y = 0; 109 | if (root == 0) 110 | return 0; 111 | x = Height(root->lchild); 112 | y = Height(root->rchild); 113 | if (x > y) 114 | return x + 1; 115 | else 116 | return y + 1; 117 | } 118 | int main() 119 | { 120 | Tree t; 121 | t.CreateTree(); 122 | cout << "Preorder "; 123 | t.Preorder(); 124 | cout << endl; 125 | cout << "Inorder "; 126 | t.Inorder(); 127 | cout << endl 128 | << endl; 129 | return 0; 130 | } -------------------------------------------------------------------------------- /Competitive programming/C++/Trie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct trie{ 5 | struct trie* child[26]; 6 | bool is_end; 7 | trie(){ 8 | memset(child,0,sizeof(child)); 9 | is_end=false; 10 | } 11 | }; 12 | 13 | struct trie* root; 14 | //inserts a word to the trie 15 | void insert(string s){ 16 | struct trie* temp=root; 17 | //traverses over each character 18 | //if the character already exists then it simply iterates over 19 | //otherwise creates a new node and inserts the character 20 | for(char c: s){ 21 | if(!temp->child[c-'a']) 22 | temp->child[c-'a']=new trie; 23 | temp=temp->child[c-'a']; 24 | } 25 | //sets the last letter's boolean value to true 26 | temp->is_end=true; 27 | } 28 | //returns true if the word exists, false otherwise 29 | bool check(string s){ 30 | struct trie* temp=root; 31 | //iterates over the character of the word 32 | for(char c: s){ 33 | //if at any point the char of the word being check is not found it return false 34 | if(!temp->child[c-'a']) 35 | return false; 36 | temp=temp->child[c-'a']; 37 | } 38 | //returns the last letters boolean value 39 | return temp->is_end; 40 | } 41 | 42 | int main(){ 43 | ios_base::sync_with_stdio(false); 44 | cin.tie(NULL); 45 | root=new trie; 46 | int n; 47 | cout << "Input the number of words in the List" << endl; 48 | cin >> n; 49 | string word; 50 | cout<<"Enter the words"<> word ; 54 | insert(word); 55 | } 56 | cout << "Enter the number of words you want to check exist in the List" << endl; 57 | int m; 58 | cin >> m; 59 | //the words to be checked 60 | for(int i=0; i> word ; 62 | if(check(word)) 63 | cout<< "This word exist in the list" < 2 | 3 | using namespace std; 4 | 5 | 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | 15 | while (j >= 0 && arr[j] > key) 16 | { 17 | arr[j + 1] = arr[j]; 18 | j = j - 1; 19 | } 20 | arr[j + 1] = key; 21 | } 22 | } 23 | 24 | 25 | 26 | int main() 27 | { 28 | int n=0, *a, i,c=0,tsum=0,j,sum=0; 29 | cin>>n; 30 | a=new int[n]; 31 | for(i=0;i>a[i]; 34 | tsum+=a[i]; 35 | } 36 | 37 | insertionSort(a, n); 38 | 39 | for(i=n-1;i>=0;i--) 40 | { 41 | sum=0; 42 | c++; 43 | for(j=n-1;j>=i;j--) 44 | { 45 | sum+=a[j]; 46 | } 47 | if((2*sum)>tsum) 48 | { 49 | cout< 2 | using namespace std; 3 | 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | //arr1,arr2 : the arrays 9 | // n, m: size of arrays 10 | //Function to return a list containing the union of the two arrays. 11 | vector findUnion(int arr1[], int arr2[], int n, int m) 12 | { 13 | //Your code here - rahul 14 | //return vector with correct order of elements 15 | vector vec; 16 | int arr3[n+m]; 17 | for(int i=0 ; i> T; 37 | 38 | while(T--){ 39 | 40 | 41 | 42 | int N, M; 43 | cin >>N >> M; 44 | 45 | int arr1[N]; 46 | int arr2[M]; 47 | 48 | for(int i = 0;i> arr1[i]; 50 | } 51 | 52 | for(int i = 0;i> arr2[i]; 54 | } 55 | Solution ob; 56 | vector ans = ob.findUnion(arr1,arr2, N, M); 57 | for(int i: ans)cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | long long l, *a, max1=0; 10 | int n,i; 11 | cin>>n>>l; 12 | a=new long long[n]; 13 | for(i=0;i>a[i]; 16 | } 17 | sort(a, a+n); 18 | for(i=0;i 2 | using namespace std; 3 | 4 | struct student 5 | { 6 | char name[50]; 7 | int roll; 8 | float marks; 9 | }; 10 | 11 | int main() 12 | { 13 | student s; 14 | cout << "Enter information," << endl; 15 | cout << "Enter name: "; 16 | cin >> s.name; 17 | cout << "Enter roll number: "; 18 | cin >> s.roll; 19 | cout << "Enter marks: "; 20 | cin >> s.marks; 21 | 22 | cout << "\nDisplaying Information," << endl; 23 | cout << "Name: " << s.name << endl; 24 | cout << "Roll: " << s.roll << endl; 25 | cout << "Marks: " << s.marks << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Competitive programming/C++/decimal_to_binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin>>n; 10 | vector v; 11 | int rem; 12 | while(n>0){ 13 | rem=n%2; 14 | v.push_back(rem); 15 | n=n/2; 16 | } 17 | reverse(v.begin(), v.end()); 18 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int isBalanced(char *exp) 9 | { 10 | 11 | // Create map 12 | map mapping; 13 | mapping['}'] = '{'; 14 | mapping[')'] = '('; 15 | mapping[']'] = '['; 16 | 17 | // Create map iterator 18 | map::iterator itr; 19 | 20 | // Create stack 21 | stack stk; 22 | 23 | for (int i = 0; i < strlen(exp); i++) 24 | { 25 | if (exp[i] == '{' || exp[i] == '[' || exp[i] == '(') 26 | { 27 | stk.push(exp[i]); 28 | } 29 | else if (exp[i] == '}' || exp[i] == ']' || exp[i] == ')') 30 | { 31 | if (stk.empty()) 32 | { 33 | return false; 34 | } 35 | else 36 | { 37 | char temp = stk.top(); 38 | itr = mapping.find(exp[i]); 39 | if (temp == itr->second) 40 | { // itr->first is key, itr->second is value 41 | stk.pop(); 42 | } 43 | else 44 | { 45 | return false; 46 | } 47 | } 48 | } 49 | } 50 | return stk.empty() ? true : false; 51 | } 52 | 53 | int main() 54 | { 55 | ios_base::sync_with_stdio(false); 56 | cin.tie(NULL); 57 | 58 | char A[] = "{([a+b]*[c-d*g])/e}"; 59 | cout << isBalanced(A) << endl; 60 | 61 | char B[] = "{([a+b]}*[c-d])/e}"; 62 | cout << isBalanced(B) << endl; 63 | 64 | char C[] = "{([{a+b]*[c-d])/e}"; 65 | cout << isBalanced(C) << endl; 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /Competitive programming/C++/generate_pattern.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to demonstrate star pattern 2 | #include 3 | using namespace std; 4 | 5 | void pypart(int n) 6 | { 7 | for (int i = n; i > 0; i--) { 8 | 9 | for (int j = 0; j < i; j++) { 10 | 11 | cout << "* "; 12 | } 13 | 14 | cout << endl; 15 | } 16 | } 17 | 18 | int main() 19 | { 20 | int n = 5; 21 | pypart(n); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Competitive programming/C++/inverted_pattern.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to demonstrate star pattern 2 | #include 3 | using namespace std; 4 | 5 | void pypart(int n) 6 | { 7 | for (int i = n; i > 0; i--) { 8 | 9 | for (int j = 0; j < i; j++) { 10 | 11 | cout << "* "; 12 | } 13 | 14 | cout << endl; 15 | } 16 | } 17 | 18 | int main() 19 | { 20 | int n = 5; 21 | pypart(n); 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Competitive programming/C++/majority_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | 8 | int n; 9 | cin>>n; 10 | int arr[n]; 11 | for(int i=0;i>arr[i]; 13 | } 14 | sort(arr,arr+n); 15 | int count; 16 | vector v; 17 | for(int i=0;i 2 | typedef long long int ll; 3 | using namespace std; 4 | 5 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 6 | int n1 = nums1.size(); 7 | int n2 = nums2.size(); 8 | 9 | if (n2 < n1) return findMedianSortedArrays(nums2, nums1); 10 | 11 | int lo = 0; 12 | int hi = n1; 13 | 14 | while (lo<=hi) { 15 | int partitionX = (lo+hi)/2; 16 | int partitionY = (n1+n2+1)/2 - partitionX; 17 | 18 | int maxLeftX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1]; 19 | int minRightX = (partitionX == n1) ? INT_MAX : nums1[partitionX]; 20 | 21 | int maxLeftY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1]; 22 | int minRightY = (partitionY == n2) ? INT_MAX : nums2[partitionY]; 23 | 24 | if (maxLeftX <= minRightY and maxLeftY <= minRightX) { // Correct Partition 25 | if ((n1 + n2) % 2 == 0) // Even 26 | return double(max(maxLeftX, maxLeftY) + min(minRightX, minRightY))/2; 27 | else 28 | return double(max(maxLeftX, maxLeftY)); 29 | } 30 | else if (maxLeftX > minRightY) hi = partitionX - 1; 31 | else lo = partitionX + 1; 32 | } 33 | return -1; 34 | } 35 | 36 | int main() { 37 | 38 | int n1, n2; 39 | cin >> n1 >> n2; 40 | 41 | vector nums1(n1), nums2(n2); 42 | 43 | for (int i = 0; i < n1; i++) { 44 | cin >> nums1[i]; 45 | } 46 | for (int i = 0; i < n2; i++) { 47 | cin >> nums2[i]; 48 | } 49 | 50 | cout << "Median = " << findMedianSortedArrays(nums1, nums2); 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Competitive programming/C++/parenthesismatching.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Stack 6 | { 7 | private: 8 | int size; 9 | int top; 10 | char *S; 11 | 12 | public: 13 | Stack(int size); 14 | ~Stack(); 15 | void push(char x); 16 | char pop(); 17 | char peek(int index); 18 | int isFull(); 19 | int isEmpty(); 20 | void display(); 21 | char stackTop(); 22 | }; 23 | 24 | Stack::Stack(int size) 25 | { 26 | this->size = size; 27 | top = -1; 28 | S = new char[size]; 29 | } 30 | 31 | Stack::~Stack() 32 | { 33 | delete[] S; 34 | } 35 | 36 | void Stack::push(char x) 37 | { 38 | if (isFull()) 39 | { 40 | cout << "Stack Overflow!" << endl; 41 | } 42 | else 43 | { 44 | top++; 45 | S[top] = x; 46 | } 47 | } 48 | 49 | char Stack::pop() 50 | { 51 | char x = 1; 52 | if (isEmpty()) 53 | { 54 | cout << "Stack Underflow!" << endl; 55 | } 56 | else 57 | { 58 | x = S[top]; 59 | top--; 60 | } 61 | return x; 62 | } 63 | 64 | char Stack::peek(int index) 65 | { 66 | char x = -1; 67 | if (top - index + 1 < 0 || top - index + 1 == size) 68 | { 69 | cout << "Invalid position!" << endl; 70 | } 71 | else 72 | { 73 | x = S[top - index + 1]; 74 | } 75 | return x; 76 | } 77 | 78 | int Stack::isFull() 79 | { 80 | if (top == size - 1) 81 | { 82 | return 1; 83 | } 84 | return 0; 85 | } 86 | 87 | int Stack::isEmpty() 88 | { 89 | if (top == -1) 90 | { 91 | return 1; 92 | } 93 | return 0; 94 | } 95 | 96 | void Stack::display() 97 | { 98 | for (int i = top; i >= 0; i--) 99 | { 100 | cout << S[i] << " | " << flush; 101 | } 102 | cout << endl; 103 | } 104 | 105 | char Stack::stackTop() 106 | { 107 | if (isEmpty()) 108 | { 109 | return -1; 110 | } 111 | return S[top]; 112 | } 113 | 114 | bool isBalanced(char *exp) 115 | { 116 | 117 | // Create a stack 118 | Stack stk((int)strlen(exp)); 119 | 120 | // Process expression 121 | for (int i = 0; i < strlen(exp); i++) 122 | { 123 | 124 | // ( found: Push to stack 125 | if (exp[i] == '(') 126 | { 127 | stk.push(exp[i]); 128 | 129 | // ( found 130 | } 131 | else if (exp[i] == ')') 132 | { 133 | 134 | // ) and stack is empty: Unbalanced expression 135 | if (stk.isEmpty()) 136 | { 137 | return false; 138 | 139 | // ) and stack is not empty 140 | } 141 | else 142 | { 143 | stk.pop(); 144 | } 145 | } 146 | } 147 | 148 | // If stack is empty then balanced else unbalanced 149 | return stk.isEmpty() ? true : false; 150 | } 151 | 152 | int main() 153 | { 154 | 155 | char E[] = "((a+b)*(c-d))"; 156 | cout << isBalanced(E) << endl; 157 | 158 | char F[] = "((a+b)*(c-d)))"; 159 | cout << isBalanced(F) << endl; 160 | 161 | char G[] = "(((a+b)*(c-d))"; 162 | cout << isBalanced(G) << endl; 163 | return 0; 164 | } -------------------------------------------------------------------------------- /Competitive programming/C++/stackLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | }; 10 | 11 | class Stack 12 | { 13 | private: 14 | Node *top; 15 | 16 | public: 17 | Stack(); 18 | ~Stack(); 19 | void push(int x); 20 | void Display(); 21 | int pop(); 22 | int peek(int index); 23 | int isEmpty(); 24 | int isFull(); 25 | int stackTop(); 26 | }; 27 | 28 | Stack::Stack() 29 | { 30 | top = nullptr; 31 | } 32 | 33 | Stack::~Stack() 34 | { 35 | Node *p = top; 36 | while (top) 37 | { 38 | top = top->next; 39 | delete p; 40 | p = top; 41 | } 42 | } 43 | 44 | void Stack::push(int x) 45 | { 46 | Node *t = new Node; 47 | if (t == nullptr) 48 | { 49 | cout << "Stack Overflow!" << endl; 50 | } 51 | else 52 | { 53 | t->data = x; 54 | t->next = top; 55 | top = t; 56 | } 57 | } 58 | 59 | int Stack::pop() 60 | { 61 | Node *p; 62 | int x = -1; 63 | if (top == NULL) 64 | { 65 | cout << "Stack Underflow!" << endl; 66 | } 67 | else 68 | { 69 | p = top; 70 | x = p->data; 71 | top = top->next; 72 | delete p; 73 | } 74 | return x; 75 | } 76 | 77 | void Stack::Display() 78 | { 79 | Node *p = top; 80 | while(p!=NULL) 81 | { 82 | cout<data<<" "; 83 | p=p->next; 84 | } 85 | cout<<"\n"; 86 | } 87 | 88 | int Stack::isFull() 89 | { 90 | Node *t = new Node; 91 | int r = t ? 1 : 0; 92 | delete t; 93 | return r; 94 | } 95 | 96 | int Stack::isEmpty() 97 | { 98 | return top ? 0 : 1; 99 | } 100 | 101 | int Stack::stackTop() 102 | { 103 | if (top) 104 | { 105 | return top->data; 106 | } 107 | return -1; 108 | } 109 | 110 | int Stack::peek(int index) 111 | { 112 | if (isEmpty()) 113 | { 114 | return -1; 115 | } 116 | else 117 | { 118 | Node *p = top; 119 | 120 | for (int i = 0; p != nullptr && i < index - 1; i++) 121 | { 122 | p = p->next; 123 | } 124 | 125 | if (p != nullptr) 126 | { 127 | return p->data; 128 | } 129 | else 130 | { 131 | return -1; 132 | } 133 | } 134 | } 135 | 136 | int main() 137 | { 138 | 139 | int A[] = {1, 3, 5, 7, 9}; 140 | 141 | Stack stk; 142 | 143 | // Populate stack 144 | for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) 145 | { 146 | stk.push(A[i]); 147 | } 148 | 149 | cout << "Stack peek at 3rd: " << stk.peek(3) << endl; 150 | cout << "Stack peek at 10th: " << stk.peek(10) << endl; 151 | cout << "Stack top: " << stk.stackTop() << endl; 152 | cout << "Stack full: " << stk.isFull() << endl; 153 | cout << "Stack empty: " << stk.isEmpty() << endl; 154 | 155 | // Pop out elements from stack 156 | cout << "Popped: " << flush; 157 | for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) 158 | { 159 | cout << stk.pop() << ", " << flush; 160 | } 161 | cout << endl; 162 | 163 | // Underflow 164 | cout << stk.pop() << endl; 165 | 166 | return 0; 167 | } -------------------------------------------------------------------------------- /Competitive programming/C++/triplet sum to a given value: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | bool find3Numbers(int A[], int arr_size, int sum) 7 | { 8 | 9 | for (int i = 0; i < arr_size - 2; i++) 10 | { 11 | 12 | 13 | unordered_set s; 14 | int curr_sum = sum - A[i]; 15 | for (int j = i + 1; j < arr_size; j++) 16 | { 17 | if (s.find(curr_sum - A[j]) != s.end()) 18 | { 19 | printf("Triplet is %d, %d, %d", A[i], 20 | A[j], curr_sum - A[j]); 21 | return true; 22 | } 23 | s.insert(A[j]); 24 | } 25 | } 26 | 27 | 28 | return false; 29 | } 30 | 31 | 32 | int main() 33 | { 34 | int A[] = { 1, 4, 45, 6, 10, 8 }; 35 | int sum = 22; 36 | int arr_size = sizeof(A) / sizeof(A[0]); 37 | 38 | find3Numbers(A, arr_size, sum); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Competitive programming/C/ArmstrongNumber.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n,r,sum=0,temp; 5 | printf("enter the number="); 6 | scanf("%d",&n); 7 | temp=n; 8 | while(n>0) 9 | { 10 | r=n%10; 11 | sum=sum+(r*r*r); 12 | n=n/10; 13 | } 14 | if(temp==sum) 15 | printf("armstrong number "); 16 | else 17 | printf("not armstrong number"); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Competitive programming/C/Find Remainder.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int T; 6 | scanf("%d", &T); 7 | while (T--) 8 | { 9 | 10 | int a, b; 11 | scanf("%d %d", &a, &b); 12 | 13 | int ans =a%b ; 14 | printf("%d\n", ans); 15 | } 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /Competitive programming/C/Matrix multiplication.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void merge(int Array[],int iterator1,int j1,int iterator2,int j2) 4 | { 5 | int TemporaryArray[50]; //array used for merging 6 | int i,j,k; 7 | i=iterator1; //beginning of the first list 8 | j=iterator2; //beginning of the second list 9 | k=0; 10 | 11 | while(i<=j1 && j<=j2) //while elements in both lists 12 | { 13 | if(Array[i] 2 | 3 | void merge(int Array[],int iterator1,int j1,int iterator2,int j2) 4 | { 5 | int TemporaryArray[50]; //array used for merging 6 | int i,j,k; 7 | i=iterator1; //beginning of the first list 8 | j=iterator2; //beginning of the second list 9 | k=0; 10 | 11 | while(i<=j1 && j<=j2) //while elements in both lists 12 | { 13 | if(Array[i] 2 | #define SIZE 6 3 | 4 | void enQueue(int); 5 | void deQueue(); 6 | void display(); 7 | 8 | int items[SIZE], front = -1, rear = -1; 9 | 10 | int main() { 11 | //deQueue is not possible on empty queue 12 | deQueue(); 13 | 14 | //enQueue 5 elements 15 | enQueue(1); 16 | enQueue(2); 17 | enQueue(3); 18 | enQueue(4); 19 | enQueue(5); 20 | enQueue(6); 21 | 22 | // 7th element can't be added to because the queue is full 23 | enQueue(7); 24 | enQueue(8); 25 | 26 | display(); 27 | 28 | //deQueue removes element entered first i.e. 1 29 | deQueue(); 30 | 31 | //Now we have just 5 elements 32 | display(); 33 | 34 | return 0; 35 | } 36 | 37 | void enQueue(int value) { 38 | if (rear == SIZE - 1) 39 | printf("\nQueue is Full!!"); 40 | else { 41 | if (front == -1) 42 | front = 0; 43 | rear++; 44 | items[rear] = value; 45 | printf("\nInserted -> %d", value); 46 | } 47 | } 48 | 49 | void deQueue() { 50 | if (front == -1) 51 | printf("\nQueue is Empty!!"); 52 | else { 53 | printf("\nDeleted : %d", items[front]); 54 | front++; 55 | if (front > rear) 56 | front = rear = -1; 57 | } 58 | } 59 | 60 | void display() { 61 | if (rear == -1) 62 | printf("\nQueue is Empty!!!"); 63 | else { 64 | int i; 65 | printf("\nQueue elements are:\n"); 66 | for (i = front; i <= rear; i++) 67 | printf("%d ", items[i]); 68 | } 69 | printf("\n"); 70 | } -------------------------------------------------------------------------------- /Competitive programming/C/README.md: -------------------------------------------------------------------------------- 1 | # hacktoberfest2021_CP 2 | You can contribute competitive programming in C 3 | 4 | ## Basics of Git and GitHub 5 | ### Git & GitHub 6 | Before we proceed, it's better to know the difference between Git and Github. Git is a version control system (VCS) that allows us to keep track of the history of our source code , whereas GitHub is a service that hosts Git projects. 7 | 8 | We assume you have created an account on Github and installed Git on your System. 9 | 10 | Now enter your name and E-mail (used on Github) address in Git, by using following command. 11 | 12 | `$ git config --global user.name "YOUR NAME"` `$ git config --global user.email "YOUR EMAIL ADDRESS"` 13 | This is an important step to mark your commits to your name and email. 14 | 15 | 16 | ### Fork a project 17 | You can make a copy of the project to your account. This process is called forking a project to your Github account. On Upper right side of project page on Github, you can see. 18 | Click on fork to create a copy of project to your account. This creates a separate copy for you to work on. 19 | 20 | ### Clone the forked project 21 | You have forked the project you want to contribute to your github account. To get this project on your development machine we use clone command of git. 22 | 23 | `$ git clone https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 24 | Now you have the project on your local machine. 25 | 26 | 27 | ### Add a remote (upstream) to original project repository 28 | Remote means the remote location of project on Github. By cloning, we have a remote called origin which points to your forked repository. Now we will add a remote to the original repository from where we had forked. 29 | 30 | `$ cd ` `$ git remote add upstream https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 31 | You will see the benefits of adding remote later. 32 | 33 | ### Synchronizing your fork 34 | Open Source projects have a number of contributors who can push code anytime. So it is necessary to make your forked copy equal with the original repository. The remote added above called Upstream helps in this. 35 | 36 | `$ git checkout main` `$ git fetch upstream` `$ git merge upstream/main` `$ git push origin main` 37 | The last command pushes the latest code to your forked repository on Github. The origin is the remote pointing to your forked repository on github. 38 | 39 | 40 | Create a new branch for a feature or bugfix 41 | Usually, all repositories have a main branch that is regarded to be stable, and any new features should be developed on a separate branch before being merged into the main branch. As a result, we should establish a new branch for our feature or bugfix and go to work on the issue. 42 | 43 | `$ git checkout -b ` This will create a new branch out of master branch. Now start working on the problem and commit your changes. 44 | 45 | `$ git add --all` `$ git commit -m ""` The first command adds all the files or you can add specific files by removing -a and adding the file names. The second command gives a message to your changes so you can know in future what changes this commit makes. If you are solving an issue on original repository, you should add the issue number like #35 to your commit message. This will show the reference to commits in the issue. 46 | 47 | 48 | ### Push code and create a pull request 49 | You now have a new branch containing the modifications you want in the project you forked. Now, push your new branch to your remote github fork. 50 | 51 | `$ git push origin ` Now you are ready to help the project by opening a pull request means you now tell the project managers to add the feature or bug fix to original repository. You can open a pull request by clicking on green icon - 52 | 53 | 54 | 55 | Remember your upstream base branch should be main and source should be your feature branch. Click on create pull request and add a name to your pull request. You can also describe your feature. 56 | 57 | Fantastic! You've already made your first contribution.🥳 58 | 59 | BE OPEN! 60 | Happy Coding!💻 61 | 62 | -------------------------------------------------------------------------------- /Competitive programming/C/Reflection.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | void main() 6 | { 7 | int poly[30],a[9][3],b[3][3],c[9][3],poly2[30]; 8 | int x,y,p,i,j,k,xc,yc; 9 | int gd=DETECT,gm; 10 | clrscr(); 11 | initgraph(&gd,&gm,"c:\\turboc3\\bgi"); 12 | xc=getmaxx()/2; 13 | yc=getmaxy()/2; 14 | printf("\n Enter number of points : "); 15 | scanf("%d",&p); 16 | j=0; 17 | for(i=0;i=max) 11 | { 12 | printf("Not Possible"); 13 | return 0; 14 | } 15 | for(i=0; i=a) 23 | { 24 | printf("yes, its possible"); 25 | return 0; 26 | } 27 | printf("%d",n[loc]); 28 | } 29 | 30 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | /* 33 | 34 | Output :- 35 | 36 | Enter how many numbers:- 37 | 5 38 | Enter integers:- 39 | 4 40 | Enter integers:- 41 | 9 42 | Enter integers:- 43 | 7 44 | Enter integers:- 45 | 15 46 | Enter integers:- 47 | 22 48 | Enter the location:- 49 | 2 50 | 7 51 | 52 | */ 53 | -------------------------------------------------------------------------------- /Competitive programming/C/Stacks.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 10 5 | 6 | int count = 0; 7 | 8 | // Creating a stack 9 | struct stack { 10 | int items[MAX]; 11 | int top; 12 | }; 13 | typedef struct stack st; 14 | 15 | void createEmptyStack(st* s) { 16 | s->top = -1; 17 | } 18 | 19 | // Check if the stack is full 20 | int isfull(st* s) { 21 | if (s->top == MAX - 1) 22 | return 1; 23 | else 24 | return 0; 25 | } 26 | 27 | // Check if the stack is empty 28 | int isempty(st* s) { 29 | if (s->top == -1) 30 | return 1; 31 | else 32 | return 0; 33 | } 34 | 35 | // adding elements in the stack 36 | void push(st* s, int newitem) { 37 | if (isfull(s)) { 38 | printf("STACK FULL"); 39 | } 40 | else { 41 | s->top++; 42 | s->items[s->top] = newitem; 43 | } 44 | count++; 45 | } 46 | 47 | // Remove element from stack 48 | void pop(st* s) { 49 | if (isempty(s)) { 50 | printf("\n STACK EMPTY \n"); 51 | } 52 | else { 53 | printf("Item popped= %d", s->items[s->top]); 54 | s->top--; 55 | } 56 | count--; 57 | printf("\n"); 58 | } 59 | 60 | // Print elements of stack 61 | void printStack(st* s) { 62 | printf("Stack: "); 63 | for (int i = 0; i < count; i++) { 64 | printf("%d ", s->items[i]); 65 | } 66 | printf("\n"); 67 | } 68 | 69 | int main() { 70 | int ch; 71 | st* s = (st*)malloc(sizeof(st)); 72 | 73 | createEmptyStack(s); 74 | 75 | push(s, 1); 76 | push(s, 2); 77 | push(s, 3); 78 | push(s, 4); 79 | push(s, 5); 80 | 81 | printStack(s); 82 | 83 | pop(s); 84 | 85 | printf("\nAfter popping out top element\n"); 86 | printStack(s); 87 | } 88 | -------------------------------------------------------------------------------- /Competitive programming/C/matrix-addition.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int r, c, a[100][100], b[100][100], sum[100][100], i, j; 4 | printf("Enter the number of rows (between 1 and 100): "); 5 | scanf("%d", &r); 6 | printf("Enter the number of columns (between 1 and 100): "); 7 | scanf("%d", &c); 8 | 9 | printf("\nEnter elements of 1st matrix:\n"); 10 | for (i = 0; i < r; ++i) 11 | for (j = 0; j < c; ++j) { 12 | printf("Enter element a%d%d: ", i + 1, j + 1); 13 | scanf("%d", &a[i][j]); 14 | } 15 | 16 | printf("Enter elements of 2nd matrix:\n"); 17 | for (i = 0; i < r; ++i) 18 | for (j = 0; j < c; ++j) { 19 | printf("Enter element b%d%d: ", i + 1, j + 1); 20 | scanf("%d", &b[i][j]); 21 | } 22 | 23 | 24 | for (i = 0; i < r; ++i) 25 | for (j = 0; j < c; ++j) { 26 | sum[i][j] = a[i][j] + b[i][j]; 27 | } 28 | 29 | 30 | printf("\nSum of two matrices: \n"); 31 | for (i = 0; i < r; ++i) 32 | for (j = 0; j < c; ++j) { 33 | printf("%d ", sum[i][j]); 34 | if (j == c - 1) { 35 | printf("\n\n"); 36 | } 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Competitive programming/JAVA/0001spiral_traversal_2d.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | public class SpiralTraversalOf2DArray { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | System.out.println("Enter number of rows"); 9 | int row = scanner.nextInt(); 10 | System.out.println("Enter number of column"); 11 | int column = scanner.nextInt(); 12 | int[][] matrix = new int[row][column]; 13 | System.out.println("Enter the elements of 2X2 matrix"); 14 | for (int i = 0; i < row; i++) { 15 | System.out.println("Enter "+ column +" elements for " + i +" row"); 16 | for (int j = 0; j < column; j++) { 17 | matrix[i][j] = scanner.nextInt(); 18 | } 19 | } 20 | List traversalList = spiralTraversal(matrix); 21 | printTraversal(traversalList); 22 | } 23 | public static List spiralTraversal(int matrix[][]){ 24 | List ans = new ArrayList(); 25 | if(matrix.length == 0){ 26 | return ans; 27 | } 28 | int row = matrix.length, column = matrix[0].length; 29 | boolean[][] seen = new boolean[row][column]; 30 | int[] dr = {0, 1, 0, -1}; 31 | int[] dc = {1, 0, -1, 0}; 32 | int r=0, c=0, di=0, cr=0, cc=0; 33 | for (int i = 0; i < row * column; i++) { 34 | ans.add(matrix[r][c]); 35 | seen[r][c] = true; 36 | cr = r + dr[di]; 37 | cc = c + dc[di]; 38 | if(0<=cr && cr list){ 51 | for (int i = 0; i < list.size(); i++) { 52 | System.out.print(list.get(i)+ ((i1<=>2 17 | Example 2: 18 | --------- 19 | Input: 20 | 10 21 | / \ 22 | 20 30 23 | / \ 24 | 40 60 25 | Output: 26 | 40 20 60 10 30 27 | 30 10 60 20 40 28 | Explanation: DLL would be 40<=>20<=>60<=>10<=>30. 29 | Your Task: You don't have to take input. Complete the function bToDLL() that takes root node of the tree as a parameter 30 | and returns the head of DLL . The driver code prints the DLL both ways. 31 | Expected Time Complexity: O(N). 32 | Expected Auxiliary Space: O(H). 33 | Note: H is the height of the tree and this space is used implicitly for recursion stack. 34 | */ 35 | 36 | // Link --> https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1 37 | 38 | // Code: 39 | class Solution 40 | { 41 | Node head; 42 | Node bToDLL(Node root) 43 | { 44 | if(root == null) 45 | return null; 46 | 47 | bToDLL(root.right); 48 | root.right = head; 49 | 50 | if(head != null) 51 | head.left = root; 52 | 53 | head = root; 54 | bToDLL(root.left); 55 | 56 | return head; 57 | } 58 | } -------------------------------------------------------------------------------- /Competitive programming/JAVA/Counting Sort.java: -------------------------------------------------------------------------------- 1 | 2 | class CountingSort { 3 | void sort(char arr[]) 4 | { 5 | int n = arr.length; 6 | 7 | 8 | char output[] = new char[n]; 9 | 10 | int count[] = new int[256]; 11 | for (int i = 0; i < 256; ++i) 12 | count[i] = 0; 13 | 14 | 15 | for (int i = 0; i < n; ++i) 16 | ++count[arr[i]]; 17 | 18 | for (int i = 1; i <= 255; ++i) 19 | count[i] += count[i - 1]; 20 | 21 | 22 | for (int i = n - 1; i >= 0; i--) { 23 | output[count[arr[i]] - 1] = arr[i]; 24 | --count[arr[i]]; 25 | } 26 | 27 | for (int i = 0; i < n; ++i) 28 | arr[i] = output[i]; 29 | } 30 | 31 | public static void main(String args[]) 32 | { 33 | CountingSort ob = new CountingSort(); 34 | char arr[] = { 'D','E','M','O','I','C','N'}; 35 | 36 | ob.sort(arr); 37 | 38 | System.out.print("Sorted character array is "); 39 | for (int i = 0; i < arr.length; ++i) 40 | System.out.print(arr[i]); 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Competitive programming/JAVA/Longest_Harmonious_Subsequence.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | leetcode-Longest Harmonious Subsequence 4 | Problem Statement: 5 | ----------------- 6 | We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. 7 | A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. 8 | 9 | Example 1: 10 | Input: nums = [1,3,2,2,5,2,3,7] 11 | Output: 5 12 | Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 13 | 14 | Example 2: 15 | Input: nums = [1,2,3,4] 16 | Output: 2 17 | */ 18 | // Link -->https://leetcode.com/problems/longest-harmonious-subsequence/ 19 | 20 | 21 | 22 | 23 | 24 | // Code: 25 | 26 | class Solution { 27 | public int findLHS(int[] nums) { 28 | int rst = 0; 29 | Map map = new HashMap<>(); 30 | 31 | // put the number and its occurence in the map 32 | for (int num : nums) { 33 | map.put(num, map.getOrDefault(num, 0) + 1); 34 | } 35 | 36 | // Traverse the map to get the longest harmonious subsequence 37 | for (int key : map.keySet()) { 38 | if (map.containsKey(key + 1)) { 39 | rst = Math.max(rst, map.get(key) + map.get(key + 1)); 40 | } 41 | } 42 | return rst; 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Competitive programming/JAVA/MergeSort.java: -------------------------------------------------------------------------------- 1 | /* Java program for Merge Sort */ 2 | class MergeSort 3 | { 4 | // Merges two subarrays of arr[]. 5 | // First subarray is arr[l..m] 6 | // Second subarray is arr[m+1..r] 7 | void merge(int arr[], int l, int m, int r) 8 | { 9 | // Find sizes of two subarrays to be merged 10 | int n1 = m - l + 1; 11 | int n2 = r - m; 12 | 13 | /* Create temp arrays */ 14 | int L[] = new int [n1]; 15 | int R[] = new int [n2]; 16 | 17 | /*Copy data to temp arrays*/ 18 | for (int i=0; i (rItem).priority) { 41 | newNode.next = null; 42 | (rItem).next = newNode; 43 | newNode.prev = (rItem).next; 44 | rItem = newNode; 45 | } // Handle other cases 46 | else { 47 | 48 | // Find position where we need to 49 | // insert. 50 | Node start = (fItem).next; 51 | while (start.priority > p) { 52 | start = start.next; 53 | } 54 | (start.prev).next = newNode; 55 | newNode.next = start.prev; 56 | newNode.prev = (start.prev).next; 57 | start.prev = newNode.next; 58 | } 59 | } 60 | head = fItem; 61 | rear = rItem; 62 | } 63 | 64 | // Return the value at rear 65 | static int peek(Node fItem) { 66 | return fItem.data; 67 | } 68 | 69 | static boolean isEmpty(Node fItem) { 70 | return (fItem == null); 71 | } 72 | 73 | // Removes the element with the 74 | // least priority value form the list 75 | static int pop(Node fItem, Node rItem) { 76 | Node temp = fItem; 77 | int res = temp.data; 78 | (fItem) = (fItem).next; 79 | if (fItem == null) { 80 | fItem = null; 81 | } 82 | 83 | head = fItem; 84 | rear = rItem; 85 | return res; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Competitive programming/JAVA/Recursive_Bubble_Sort.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.Arrays; 4 | 5 | public class DEMONIC 6 | { 7 | 8 | static void bubbleSort(int arr[], int n) 9 | { 10 | if (n == 1) 11 | return; 12 | 13 | for (int i=0; i arr[i+1]) 15 | { 16 | 17 | int temp = arr[i]; 18 | arr[i] = arr[i+1]; 19 | arr[i+1] = temp; 20 | } 21 | 22 | bubbleSort(arr, n-1); 23 | } 24 | 25 | 26 | public static void main(String[] args) 27 | { 28 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 29 | 30 | bubbleSort(arr, arr.length); 31 | 32 | System.out.println("Sorted array : "); 33 | System.out.println(Arrays.toString(arr)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Competitive programming/JAVA/Split_Array_Largest_Sum.java: -------------------------------------------------------------------------------- 1 | //Leetcode-410 :Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. 2 | //Write an algorithm to minimize the largest sum among these m subarrays. 3 | 4 | 5 | //Solution :- 6 | class Solution { 7 | public int splitArray(int[] nums, int m) { 8 | // Max ans = split 1 9 | //Min ans = split to the length 10 | int start =0; 11 | int end =0; 12 | for(int i =0;imid){ 24 | sum= num; 25 | pices++; 26 | } 27 | else{ 28 | sum+=num; 29 | } 30 | } 31 | if(pices>m){ 32 | start=mid+1; 33 | }else 34 | end= mid; 35 | } 36 | return end; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Competitive programming/JAVA/longest_rep_sub_sequence.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Main { 5 | static int LongestRepSubSeq(String str) { 6 | int n = str.length(); 7 | int[][] dp = new int[n + 1][n + 1]; 8 | for (int i = 1; i <= n; i++) { 9 | for (int j = 1; j <= n; j++) { 10 | if (str.charAt(i - 1) == str.charAt(j - 1) && i != j) 11 | dp[i][j] = 1 + dp[i - 1][j - 1]; 12 | else 13 | dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); 14 | } 15 | } 16 | return dp[n][n]; 17 | } 18 | 19 | public static void main(String[] args) { 20 | String str = "HHHHHHaaaacccckTTToberFFFeest"; 21 | System.out.println("The length of the largest subsequence that repeats itself is : " + LongestRepSubSeq(str)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drishyadamodaran/hacktoberfest2021_CP/5154a57d7453121b903eb4f485579db6c2c909fc/Competitive programming/PYTHON/.DS_Store -------------------------------------------------------------------------------- /Competitive programming/PYTHON/FAKESWAP.py: -------------------------------------------------------------------------------- 1 | # The link to the problem is : https://www.codechef.com/COOK133C/problems/FAKESWAP 2 | # Below is my solution 3 | for i in range(int(input())): 4 | a=int(input()) 5 | b=input() 6 | c=input() 7 | d=e=0 8 | if b==c: 9 | print("YES") 10 | else: 11 | for i in range(a): 12 | if c[i]=='1': 13 | d+=1 14 | else: 15 | e+=1 16 | if d>0 and e>0: 17 | print("YES") 18 | else: 19 | print("NO") 20 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/Fibonacci.py: -------------------------------------------------------------------------------- 1 | # -- Case-1 -->> Using Function 2 | # This is a program to find fibonacci series using simple function 3 | def fib(n): 4 | if n < 1: # Fibonacci is not defined for negative numbers 5 | return None 6 | if n < 3: # The first two elements of fibonacci are 1 7 | return 1 8 | elem1 = elem2 = 1 9 | sum = 0 10 | for i in range(3, n+1): 11 | sum = elem1+elem2 12 | elem1, elem2 = elem2, sum 13 | # First element becomes becomes second element 14 | # Second element becomes the sum of previous two elements 15 | 16 | return sum 17 | 18 | 19 | #--Main--# 20 | for i in range(1, 10): 21 | print(i, " -->> ", fib(i)) 22 | 23 | 24 | # -- Case-2 -->> Using Recursive Function 25 | def fib_rec(n): 26 | if n < 0: 27 | return None 28 | if n < 3: 29 | return 1 30 | return fib(n-1)+fib(n-2) 31 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/Find an Element in an array.py: -------------------------------------------------------------------------------- 1 | # Question is how to find a element in an array 2 | 3 | from array import* 4 | my_array = array('i',[10001,1001,1122,15423]) 5 | print(my_array.index(1122) 6 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/Frequent_WORD.py: -------------------------------------------------------------------------------- 1 | # # Here we will find the maximum frequent word in the dataset 2 | # # We will use the concept of dictionary. 3 | # inp = list(input("Enter").split()) 4 | # d = {} 5 | # for x in inp: 6 | # d[x] = 0 7 | # for x in inp: 8 | # d[x] = d[x]+1 9 | 10 | # max = 0 11 | # ans = '' 12 | # for x in inp: 13 | # if(d[x] > max): 14 | # max = d[x] 15 | # ans = x 16 | # print(d) 17 | # print(max) 18 | # print("Max Repeating word = ", ans.upper()) 19 | def f(str): 20 | new = {} 21 | freq = {} 22 | str = list(str.lower().split(' ')) 23 | for i in str: 24 | if i not in new: 25 | new[i] = 0 26 | new[i] += 1 27 | else: 28 | new[i] += 1 29 | for i in sorted(list(new.values())): 30 | freq[i] = [] 31 | for x in freq: 32 | for word in new: 33 | if new[word] == x: 34 | freq[x] += [word] 35 | print(str, end='\n\n\n') 36 | print(new) 37 | print(freq) 38 | 39 | 40 | f('My name is Lalit Kumar. My house is in #### %4^ 8') 41 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/N_Queen.py: -------------------------------------------------------------------------------- 1 | count = 0 2 | 3 | 4 | def solution(n): 5 | board = [0] 6 | visited = [False] * (n + 1) 7 | queen(n, board, visited) 8 | print(count) 9 | 10 | 11 | def check(board, x): 12 | for i in range(1, len(board)): 13 | if abs(i - len(board)) == abs(board[i] - x): 14 | return False 15 | return True 16 | 17 | 18 | def queen(n, board, visited): 19 | global count 20 | if len(board) == n + 1: 21 | count += 1 22 | else: 23 | for i in range(1, n + 1): 24 | if not visited[i]: 25 | if not check(board, i): 26 | continue 27 | board.append(i) 28 | visited[i] = True 29 | queen(n, board, visited) 30 | visited[i] = False 31 | board.pop() 32 | 33 | printf("how many?") 34 | solution(int(input())) 35 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/SUDOKU.py: -------------------------------------------------------------------------------- 1 | # A function that checks whether a list passed as an argument contains 2 | # nine digits from '1' to '9'. 3 | def checkset(digs): 4 | return sorted(list(digs)) == [chr(x + ord('0')) for x in range(1, 10)] 5 | 6 | 7 | # A list of rows representing the sudoku. 8 | rows = [ ] 9 | for r in range(9): 10 | ok = False 11 | while not ok: 12 | row = input("Enter row #" + str(r + 1) + ": ") 13 | ok = len(row) == 9 or row.isdigit() 14 | if not ok: 15 | print("Incorrect row data - 9 digits required") 16 | rows.append(row) 17 | 18 | ok = True 19 | 20 | # Check if all rows are good. 21 | for r in range(9): 22 | if not checkset(rows[r]): 23 | ok = False 24 | break 25 | 26 | # Check if all columns are good. 27 | if ok: 28 | for c in range(9): 29 | col = [] 30 | for r in range(9): 31 | col.append(rows[r][c]) 32 | if not checkset(col): 33 | ok = False 34 | break 35 | 36 | # Check if all sub-squares (3x3) are good. 37 | if ok: 38 | for r in range(0, 9, 3): 39 | for c in range(0, 9, 3): 40 | sqr = '' 41 | # Make a string containing all digits from a sub-square. 42 | for i in range(3): 43 | sqr += rows[r+i][c:c+3] 44 | if not checkset(list(sqr)): 45 | ok = False 46 | break 47 | 48 | # Print the final verdict. 49 | if ok: 50 | print("Yes") 51 | else: 52 | print("No") 53 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/Special Numbers/Auto_Bio.py: -------------------------------------------------------------------------------- 1 | # Autobiographical numbers within range 0 to N 2 | #An autobiographical number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there and so on. 3 | #For example, 1210 has 1 zero, 2 ones, 1 two and 0 threes. 4 | 5 | from math import pow 6 | 7 | def isAutoBio(N): 8 | 9 | #Converting number to string for simpler execution 10 | Str = str(N) 11 | 12 | for i in range(0, len(Str)): 13 | 14 | #Extracting character at each index and converting back to integer 15 | index = int(Str[i]) 16 | 17 | c = 0 #counter variable for counting 0's,1's, and so on 18 | 19 | for j in range(0, len(Str)): 20 | 21 | num = int(Str[j]) 22 | 23 | # Check if equal to the index, if true then increment count 24 | if num == i: 25 | 26 | #An Autobiographical number 27 | c += 1 28 | 29 | # Return false if counter and index not equal 30 | if c != index: 31 | 32 | return False 33 | 34 | return True 35 | 36 | # Function to print autobiographical number 37 | 38 | def findAutoBios(n): 39 | 40 | 41 | flag= 0 42 | 43 | #print("********AUTOBIOGRAPHICAL NUMBERS IN THIS RANGE 0 TO ",n) 44 | 45 | for i in range(0,n+1): 46 | 47 | #Passing every number from 0 to n+1 to check for Autobiographical number 48 | 49 | if isAutoBio(i): 50 | flag = 1 51 | print i,"is an autobiographical number\n" 52 | 53 | 54 | # Driver Code 55 | 56 | if __name__ == "__main__": 57 | 58 | N = input("Please enter the max range\n") 59 | 60 | findAutoBios(N) -------------------------------------------------------------------------------- /Competitive programming/PYTHON/knight_moves.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # input 4 | #The input begins with the number n of scenarios on a single line by itself. 5 | # Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 ≤ l ≤ 300). The entire board has size l × l. The second and third line contain pair of integers {0, ..., l−1}× {0, ..., l−1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario 6 | # output 7 | # For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal, distance is zero. The distance must be written on a single line. 8 | import sys 9 | from collections import deque 10 | 11 | 12 | def solution(): 13 | move = [[2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2], [1, -2], [2, -1]] 14 | IC = int(sys.stdin.readline()) 15 | for _ in range(IC): 16 | row = int(sys.stdin.readline()) 17 | arr = [[0 for _ in range(row)] for _ in range(row)] 18 | sy, sx = list(map(int, sys.stdin.readline().split())) 19 | dy, dx = list(map(int, sys.stdin.readline().split())) 20 | queue = deque() 21 | queue.append((sy, sx)) 22 | while queue: 23 | cy, cx = queue.popleft() 24 | if dx == cx and dy == cy: 25 | print(arr[dy][dx]) 26 | break 27 | for i in range(8): 28 | my = cy + move[i][0] 29 | mx = cx + move[i][1] 30 | if not (0 <= my and 0 <= mx and my < row and mx < row): 31 | continue 32 | if arr[my][mx]: 33 | continue 34 | arr[my][mx] = arr[cy][cx] + 1 35 | queue.append((my, mx)) 36 | 37 | 38 | solution() 39 | -------------------------------------------------------------------------------- /Competitive programming/PYTHON/maxprofit.py: -------------------------------------------------------------------------------- 1 | liStocks = [100, 180, 260, 310, 40, 535, 695] 2 | 3 | #find local minima 4 | def findMin(liStocks): 5 | for i, val in enumerate(liStocks[:-1]): 6 | if val < liStocks[i+1]: 7 | return i, val 8 | return -1, -1 9 | 10 | #find local maxima 11 | def findMax(liStocks): 12 | for i, val in enumerate(liStocks[:-1]): 13 | if val > liStocks[i+1]: 14 | return i, val 15 | return i+1, liStocks[-1] 16 | 17 | 18 | 19 | def buySellStock(): 20 | index=0 21 | while index < len(liStocks): 22 | i, val = findMin(liStocks[index:]) 23 | if i > -1: 24 | index=i+index 25 | print("bye stock on day ", index+1, val) 26 | else: 27 | break 28 | 29 | i, val = findMax(liStocks[index:]) 30 | index=i+index 31 | print("sell stock on day ", index+1, val) 32 | 33 | 34 | if __name__ == "__main__": 35 | buySellStock() 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # hacktoberfest2021_CP 3 | ![image](https://user-images.githubusercontent.com/56961626/135728682-586fe6e3-7fe0-4ae7-b4df-6d5278f53688.png) 4 | 5 | You can contribute here! 6 | 7 | ## Basics of Git and GitHub 8 | ### Git & GitHub 9 | Before we proceed, it's better to know the difference between Git and Github. Git is a version control system (VCS) that allows us to keep track of the history of our source code , whereas GitHub is a service that hosts Git projects. 10 | 11 | We assume you have created an account on Github and installed Git on your System. 12 | 13 | Now enter your name and E-mail (used on Github) address in Git, by using following command. 14 | 15 | `$ git config --global user.name "YOUR NAME"` `$ git config --global user.email "YOUR EMAIL ADDRESS"` 16 | This is an important step to mark your commits to your name and email. 17 | 18 | 19 | ### Fork a project 20 | You can make a copy of the project to your account. This process is called forking a project to your Github account. On Upper right side of project page on Github, you can see. 21 | Click on fork to create a copy of project to your account. This creates a separate copy for you to work on. 22 | 23 | ### Clone the forked project 24 | You have forked the project you want to contribute to your github account. To get this project on your development machine we use clone command of git. 25 | 26 | `$ git clone https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 27 | Now you have the project on your local machine. 28 | 29 | 30 | ### Add a remote (upstream) to original project repository 31 | Remote means the remote location of project on Github. By cloning, we have a remote called origin which points to your forked repository. Now we will add a remote to the original repository from where we had forked. 32 | 33 | `$ cd ` `$ git remote add upstream https://github.com/drishyadamodaran/hacktoberfest2021_CP.git` 34 | You will see the benefits of adding remote later. 35 | 36 | ### Synchronizing your fork 37 | Open Source projects have a number of contributors who can push code anytime. So it is necessary to make your forked copy equal with the original repository. The remote added above called Upstream helps in this. 38 | 39 | `$ git checkout main` `$ git fetch upstream` `$ git merge upstream/main` `$ git push origin main` 40 | The last command pushes the latest code to your forked repository on Github. The origin is the remote pointing to your forked repository on github. 41 | 42 | 43 | Create a new branch for a feature or bugfix 44 | Usually, all repositories have a main branch that is regarded to be stable, and any new features should be developed on a separate branch before being merged into the main branch. As a result, we should establish a new branch for our feature or bugfix and go to work on the issue. 45 | 46 | `$ git checkout -b ` This will create a new branch out of master branch. Now start working on the problem and commit your changes. 47 | 48 | `$ git add --all` `$ git commit -m ""` The first command adds all the files or you can add specific files by removing -a and adding the file names. The second command gives a message to your changes so you can know in future what changes this commit makes. If you are solving an issue on original repository, you should add the issue number like #35 to your commit message. This will show the reference to commits in the issue. 49 | 50 | 51 | ### Push code and create a pull request 52 | You now have a new branch containing the modifications you want in the project you forked. Now, push your new branch to your remote github fork. 53 | 54 | `$ git push origin ` Now you are ready to help the project by opening a pull request means you now tell the project managers to add the feature or bug fix to original repository. You can open a pull request by clicking on green icon - 55 | 56 | 57 | 58 | Remember your upstream base branch should be main and source should be your feature branch. Click on create pull request and add a name to your pull request. You can also describe your feature. 59 | 60 | Fantastic! You've already made your first contribution.🥳 61 | 62 | BE OPEN! 63 | Happy Coding!💻 64 | 65 | --------------------------------------------------------------------------------