diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..87c7f68 Binary files /dev/null and b/.DS_Store differ diff --git a/Algorithms/BinarySearch b/Algorithms/BinarySearch new file mode 100644 index 0000000..503e167 --- /dev/null +++ b/Algorithms/BinarySearch @@ -0,0 +1,45 @@ +//srishti1302 +#include +#define COMPARE(x,y) ( (x)<(y)?-1:(x)==(y)? 0 :1 ) +int binsearch(int a[20],int k,int left,int right) +{ + + if(left +using namespace std; + +//Bubble sort : swap two elements walaa technique + +int main(){ + int n; + cin>>n; + int arr[n]; + for(int i=0;i>arr[i]; + } + + int counter = 1; + while(counterarr[i+1]){ + if(arr[i]>arr[i+1]){ + int temp=arr[i]; + arr[i]=arr[i+1]; + arr[i+1]=temp; + } + + } + } + counter++; + } + for(int i=0;i +#include + +using namespace std; + +void Insert(vector& vec, int key){ + // Insert key at the end + auto i = vec.size(); + vec.emplace_back(key); + + // Rearrange elements: O(log n) + while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){ + vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + vec[i] = key; +} + +void InsertInplace(int A[], int n){ + int i = n; + int temp = A[n]; + while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){ + A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + A[i] = temp; +} + +void CreateHeap(vector& vec, int A[], int n){ + // O(n log n) + for (int i=0; i +void Print(T& vec, int n, char c){ + cout << c << ": [" << flush; + for (int i=0; i v; + CreateHeap(v, b, sizeof(b)/sizeof(b[0])); + Print(v, v.size(), 'v'); + + cout << "Inplace Insert" << endl; + createHeap(b, sizeof(b)/sizeof(b[0])); + Print(b, sizeof(b)/sizeof(b[0]), 'b'); + + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Deletion_in_Array.cpp b/Algorithms/Deletion_in_Array.cpp new file mode 100644 index 0000000..2397b83 --- /dev/null +++ b/Algorithms/Deletion_in_Array.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +void display(int A[],int n){ + for(int i=0; i>n; + cout<<"Enter length of the array: "; + cin>>m; + int A[n]; + + for(int i=0; i>A[i]; + } + + //Example function call to delete 2nd element + arr_delete(A,2,m); + + display(A,m-1); + + return 0; + +} diff --git a/Algorithms/Diagnolmatrix.cpp b/Algorithms/Diagnolmatrix.cpp new file mode 100644 index 0000000..58d6db7 --- /dev/null +++ b/Algorithms/Diagnolmatrix.cpp @@ -0,0 +1,74 @@ +#include +using namespace std; + +class Diagnol +{ +private: + int *A; + int n; +public: + Diagnol() + { + n=2; + A=new int[2]; + } + Diagnol(int n) + { + this->n=n; + A=new int[n]; + } + ~Diagnol() + { + delete []A; + } + void Set(int i, int j,int x); + int Get(int i, int j); + void Display(); +}; + +void Diagnol::Set(int i, int j,int x) +{ + if(i==j) + A[i-1]=x; +} + +int Diagnol::Get(int i, int j) +{ + if(i==j) + return A[i-1]; + else + return 0; +} + +void Diagnol::Display() +{ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + if(i==j) + cout< +using namespace std; +class node{ + public: +int data; +node *next;//yaha address store karvana tha toh aysy likha +node(int data){ + this->data=data; + next=NULL; +} +}; +node *middlenode(node *head){ + node *slow=head; + node *fast=head->next; + while(fast && fast->next){ + slow=slow->next; + fast=fast->next->next; + } + if(fast!=NULL){ + return slow->next; + } + return slow; +} + +int main(){ + node n1(81); + node n2(27); + node n3(56); + 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 + n1.next=&n2; + n2.next=&n3;// this is storing address jaha pehle null stored tha + + cout<<"the middle element is "<data; + + + return 0; + + +} + + + + + +//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. diff --git a/Algorithms/Floyd_Warshall.cpp b/Algorithms/Floyd_Warshall.cpp new file mode 100644 index 0000000..2001fef --- /dev/null +++ b/Algorithms/Floyd_Warshall.cpp @@ -0,0 +1,63 @@ +//Problem Statement +//The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. +//The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. +//Time Complexity: O(V^3) + +#include +using namespace std; + +vector> floyd_warshall(vector> graph) { + vector> dist(graph); + + int V = graph.size(); + + // Iterate over all phases 1,2,....,V + for(int k=0;k dist[i][k] + dist[k][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + } + + //Check for negative edge cycle + for(int i=0;i> graph = { + {0,INT_MAX,-2,INT_MAX}, + {4,0,3,INT_MAX}, + {INT_MAX,INT_MAX,0,2}, + {INT_MAX,-1,INT_MAX,0} + }; + + auto it = floyd_warshall(graph); + + //The shortest path from ith node to jth node + for(int i=0;i + +using namespace std; + +struct Item{ + int val; + int w; +}; + +bool cmp(Item i1,Item i2){ + double r1= (double)i1.val/i1.w; + double r2=(double)i2.val/i2.w; + return r1>r2; +} + +int fractionalKnapsack(Item items[],int n,int W){ + sort(items,items+n,cmp); + + int rem=W; + double ans=0; + for(int i=0;ib) + { + gcd = b; + } + else if (b>a) + { + gcd = a; + } + + while(true) + { + if(a% gcd ==0 && b% gcd==0) + { + System.out.println(gcd); + break; + } + --gcd; + } + + + + } + +} diff --git a/Algorithms/Greedyalgo_coinchange.cpp b/Algorithms/Greedyalgo_coinchange.cpp new file mode 100644 index 0000000..f0d780e --- /dev/null +++ b/Algorithms/Greedyalgo_coinchange.cpp @@ -0,0 +1,18 @@ +/* + Author Lakshay Goel + Github profile: https://github.com/MrLakshay + Problem statement : Given coins worth 1 ,5 and 10 in unlimited quantity need to find + minimum number of coins 'x' to make 'n' sum of money input by user. + Input: n + Output : x + Exampple: + 17 + 4 +*/ +#include +using namespace std; +int main(){ + int t; + cin>>t; + cout< +void Insert(int A[], int n) +{ + int i = n, temp; + temp = A[i]; + while (i > 1 && temp > A[i / 2]) + { + A[i] = A[i / 2]; + i = i / 2; + } + A[i] = temp; +} +int Delete(int A[], int n) +{ + int i, j, x, temp, val; + val = A[1]; + x = A[n]; + A[1] = A[n]; + A[n] = val; + i = 1; + j = i * 2; + while (j <= n - 1) + { + if (j < n - 1 && A[j + 1] > A[j]) + j = j + 1; + if (A[i] < A[j]) + { + temp = A[i]; + A[i] = A[j]; + A[j] = temp; + i = j; + j = 2 * j; + } + else + break; + } + return val; +} +int main() +{ + int H[] = {0, 14, 15, 5, 20, 30, 8, 40}; + int i; + for (i = 2; i <= 7; i++) + Insert(H, i); + + for (i = 7; i > 1; i--) + { + Delete(H, i); + } + for (i = 1; i <= 7; i++) + printf("%d ", H[i]); + printf("\n"); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Heapify.cpp b/Algorithms/Heapify.cpp new file mode 100644 index 0000000..d2b8d1e --- /dev/null +++ b/Algorithms/Heapify.cpp @@ -0,0 +1,88 @@ +#include + +using namespace std; + +void swap(int A[], int i, int j){ + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; +} + +int Delete(int A[], int n){ + int x = A[0]; // Max element + A[0] = A[n-1]; + + int i = 0; + int j = 2 * i + 1; + + while (j < n-1){ + // Compare left and right children + if (A[j] < A[j+1]){ + j = j+1; + } + + // Compare parent and largest child + if (A[i] < A[j]){ + swap(A, i, j); + i = j; + j = 2 * i + 1; + } else { + break; + } + } + return x; +} + +void Heapify(int A[], int n){ + // # of leaf elements: (n+1)/2, index of last leaf element's parent = (n/2)-1 + for (int i=(n/2)-1; i>=0; i--){ + + int j = 2 * i + 1; // Left child for current i + + while(j < n-1){ + // Compare left and right children of current i + if (A[j] < A[j+1]){ + j = j+1; + } + + // Compare parent and largest child + if (A[i] < A[j]){ + swap(A, i, j); + i = j; + j = 2 * i + 1; + } else { + break; + } + } + } +} + +template +void Print(T& vec, int n, string s){ + cout << s << ": [" << flush; + for (int i=0; i +#include + +using namespace std; + +// Lecture based +void InsertA(int A[], int n){ + int i = n; + int temp = A[n]; + while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){ + A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + A[i] = temp; +} + + +// STL vector based +void Insert(vector& vec, int key){ + // Insert key at the end + auto i = vec.size(); + vec.emplace_back(key); + + // Rearrange elements: Indices are not DRY :-( + while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){ + vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + vec[i] = key; +} + +template +void Print(T& vec, int n){ + cout << "Max Heap: [" << flush; + for (int i=0; i v = {45, 35, 15, 30, 10, 12, 6, 5, 20}; + Print(v, v.size()); + v.reserve(15); // Reserve space for 15 elements + + Insert(v, 50); + Print(v, v.size()); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Insertion_sort.cpp b/Algorithms/Insertion_sort.cpp new file mode 100644 index 0000000..b65d2a1 --- /dev/null +++ b/Algorithms/Insertion_sort.cpp @@ -0,0 +1,47 @@ +// C++ program for insertion sort +#include +using namespace std; + +/* Function to sort an array using insertion sort*/ +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +/* Driver code */ +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} + +// This is code is contributed by rathbhupendra diff --git a/Algorithms/KadanesAlgo.java b/Algorithms/KadanesAlgo.java new file mode 100644 index 0000000..510c426 --- /dev/null +++ b/Algorithms/KadanesAlgo.java @@ -0,0 +1,38 @@ +class KadanesAlgo +{ + // Function to find the maximum sum of a contiguous subarray + // in a given integer array + public static int kadane(int[] A) + { + // stores the maximum sum subarray found so far + int maxSoFar = 0; + + // stores the maximum sum of subarray ending at the current position + int maxEndingHere = 0; + + // traverse the given array + for (int i: A) + { + // update the maximum sum of subarray "ending" at index `i` (by adding the + // current element to maximum sum ending at previous index `i-1`) + maxEndingHere = maxEndingHere + i; + + // if the maximum sum is negative, set it to 0 (which represents + // an empty subarray) + maxEndingHere = Integer.max(maxEndingHere, 0); + + // update the result if the current subarray sum is found to be greater + maxSoFar = Integer.max(maxSoFar, maxEndingHere); + } + + return maxSoFar; + } + + public static void main(String[] args) + { + int[] A = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; + + System.out.println("The sum of contiguous subarray with the " + + "largest sum is " + kadane(A)); + } +} diff --git a/Algorithms/Kruskal'sMinSpanningTree.cpp b/Algorithms/Kruskal'sMinSpanningTree.cpp new file mode 100644 index 0000000..e7fc3c1 --- /dev/null +++ b/Algorithms/Kruskal'sMinSpanningTree.cpp @@ -0,0 +1,89 @@ +#include + +#define I 32767 // Infinity +#define V 7 // # of vertices in Graph +#define E 9 // # of edges in Graph + +using namespace std; + +void PrintMCST(int T[][V-1], int A[][E]){ + cout << "\nMinimum Cost Spanning Tree Edges\n" << endl; + for (int i {0}; i 0){ + x = s[x]; + } + + while (u != x){ + v = s[u]; + s[u] = x; + u = v; + } + return x; +} + +void KruskalsMCST(int A[3][9]){ + int T[2][V-1]; // Solution array + int track[E] {0}; // Track edges that are included in solution + int set[V+1] = {-1, -1, -1, -1, -1, -1, -1, -1}; // Array for finding cycle + + int i {0}; + while (i < V-1){ + int min = I; + int u {0}; + int v {0}; + int k {0}; + + // Find a minimum cost edge + for (int j {0}; j +using namespace std; + +void display(int A[],int n){ + for(int i=0; i>n; + cout<<"Enter length of the array: "; + cin>>m; + int A[n]; + + for(int i=0; i>A[i]; + } + //Example function call for linear search + cout< + +using namespace std; + +class LowerTri +{ +private: + int *A; + int n; +public: + LowerTri() + { + n=2; + A=new int[2*(2+1)/2]; + } + LowerTri(int n) + { + this->n=n; + A=new int[n*(n+1)/2]; + } + ~LowerTri() + { + delete []A; + } + void Set(int i, int j,int x); + int Get(int i, int j); + void Display(); + int GetDimension(){return n;} +}; + +void LowerTri::Set(int i, int j,int x) +{ + if(i>=j) + // A[i*(i-1)/2+j-1]=x; + A[n*(j-1)-(j-2)*(j-1)/2+i-j]=x; +} + +int LowerTri::Get(int i, int j) +{ + if(i>=j) + // return A[i*(i-1)/2+j-1]; + return A[n*(j-1)-(j-2)*(j-1)/2+i-j]; + return 0; +} + +void LowerTri::Display() +{ + for (int i = 1; i <= n; i++) + { + for (int j = 1; j <= n; j++) + { + if(i>=j) + // cout<>d; + + LowerTri lm(d); + + int x; + cout<<"Enter all elements"<>x; + lm.Set(i,j,x); + + } + + + } + + lm.Display(); + + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Merge_Sort-Iterative.c b/Algorithms/Merge_Sort-Iterative.c new file mode 100644 index 0000000..028dec3 --- /dev/null +++ b/Algorithms/Merge_Sort-Iterative.c @@ -0,0 +1,72 @@ +#include +#include + + +//merging of sub-sorted array +void merging(int a[] , int low , int mid , int high) +{ + int i,j,k; + i = low; + j = mid+1; + k = low; + int b[100]; + while(i <= mid && j <= high) + { + if(a[i] < a[j]) + b[k++] = a[i++]; + else + b[k++] = a[j++]; + } + + for( ; i <=mid ; i++) + b[k++]=a[i]; + + for( ; j <= high ; j++) + b[k++]=a[j]; + + for(i=0 ; i <= high ; i++) + a[i] = b[i]; +} + +void merge_sort(int a[] , int n) +{ + int p,l,h,m,i; + + //this for loop will take account of number of passes + //in each pass number of elements is increasing by previous*2; + for(p=2 ; p <= n ; p=p*2) + { + for(i=0 ; i+p-1 < n ; i=i+p) //for choosing number of elements in each pass + { + l = i; + h = i+p-1; + m = (l+h)/2; + merging(a , l , m , h); + } + } + if(p/2 < n) //when number of elements is odd + merging(a , 0 , p/2 , n-1); +} + + +int main() +{ + int i,n; + + printf("\nEnter total number of elements of array : "); + scanf("%d",&n); + + int a[n]; + + printf("\nEnter elements of array :\n"); + for(i=0 ; i < n ; i++) + scanf("%d" , &a[i]); + + merge_sort(a , n); + + printf("\n\nMerged array is : \n"); + for(i=0 ; i < n ; i++) + printf("%d " , a[i]); + + return 0; +} diff --git a/Algorithms/Merge_Sort-Recursive.c b/Algorithms/Merge_Sort-Recursive.c new file mode 100644 index 0000000..01f0227 --- /dev/null +++ b/Algorithms/Merge_Sort-Recursive.c @@ -0,0 +1,66 @@ +#include +#include + +void merging(int a[] , int low , int mid , int high) +{ + int i,j,k; + i = low; + j = mid+1; + k = low; + int b[100]; + while(i <= mid && j <= high) + { + if(a[i] < a[j]) + b[k++] = a[i++]; + else + b[k++] = a[j++]; + } + + for( ; i <= mid ; i++) + b[k++]=a[i]; + + for( ; j <= high ; j++) + b[k++]=a[j]; + + for(i=0 ; i <= high ; i++) + a[i] = b[i]; +} + +void merge_sort(int a[] , int l , int h) +{ + int mid; + if(l < h) //will check if at least 2 elements are there + { + mid = (l+h)/2; + merge_sort(a , l , mid); + merge_sort(a , mid+1 , h); + merging(a , l , mid , h); + } +} + + +int main() +{ + int i,n,low,high; + + printf("\nEnter total number of elements of array : "); + scanf("%d",&n); + + int a[n]; + + low=0; + high=n-1; + + printf("\nEnter elements of array :\n"); + for(i=0 ; i < n ; i++) + scanf("%d" , &a[i]); + + merge_sort(a , low , high); + + printf("\n\nMerged array is : \n"); + for(i=0 ; i < n ; i++) + printf("%d " , a[i]); + + return 0; +} + diff --git a/Algorithms/Merge_Sort.js b/Algorithms/Merge_Sort.js new file mode 100644 index 0000000..8e31e44 --- /dev/null +++ b/Algorithms/Merge_Sort.js @@ -0,0 +1,24 @@ +function merge_sort(left_part,right_part) +{ + var i = 0; + var j = 0; + var results = []; + + while (i < left_part.length || j < right_part.length) { + if (i === left_part.length) { + // j is the only index left_part + results.push(right_part[j]); + j++; + } + else if (j === right_part.length || left_part[i] <= right_part[j]) { + results.push(left_part[i]); + i++; + } else { + results.push(right_part[j]); + j++; + } + } + return results; +} + +console.log(merge_sort([1,4,6], [8,2,9])); \ No newline at end of file diff --git a/Algorithms/Merge_Sort_Algo.java b/Algorithms/Merge_Sort_Algo.java new file mode 100644 index 0000000..65fd73c --- /dev/null +++ b/Algorithms/Merge_Sort_Algo.java @@ -0,0 +1,70 @@ +//contributed by arunim singhal +import java.util.Scanner; + +public class mergeSort { + void merge(int arr[], int beg, int mid, int end) { + + int l = mid - beg + 1; + int r = end - mid; + + int LeftArray[] = new int[l]; + int RightArray[] = new int[r]; + + for (int i = 0; i < l; ++i) + LeftArray[i] = arr[beg + i]; + + for (int j = 0; j < r; ++j) + RightArray[j] = arr[mid + 1 + j]; + + int i = 0, j = 0; + int k = beg; + while (i < l && j < r) { + if (LeftArray[i] <= RightArray[j]) { + arr[k] = LeftArray[i]; + i++; + } else { + arr[k] = RightArray[j]; + j++; + } + k++; + } + while (i < l) { + arr[k] = LeftArray[i]; + i++; + k++; + } + + while (j < r) { + arr[k] = RightArray[j]; + j++; + k++; + } + } + + void sort(int arr[], int beg, int end) { + if (beg < end) { + int mid = (beg + end) / 2; + sort(arr, beg, mid); + sort(arr, mid + 1, end); + merge(arr, beg, mid, end); + } + } + + public static void main(String args[]) { + int n; + Scanner sc = new Scanner(System.in); + n = sc.nextInt(); + int[] a = new int[10]; + for (int i = 0; i < n; i++) { + + a[i] = sc.nextInt(); + } + mergeSort ob = new mergeSort(); + ob.sort(a, 0, a.length - 1); + + System.out.println("\nSorted array"); + for (int i = 0; i < a.length; i++) { + System.out.print(a[i] + " "); + } + } +} diff --git a/Algorithms/Merge_Two_Arrays.cpp b/Algorithms/Merge_Two_Arrays.cpp new file mode 100644 index 0000000..f998b88 --- /dev/null +++ b/Algorithms/Merge_Two_Arrays.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +int* merge(int A[], int m, int B[], int n) { + + int* C = new int[m+n]; + + int i=0, j=0, k=0; + + while (i>n; + + cout<<"Enter length of the array2: "; + cin>>m; + int A[n]; + int B[m]; + + for(int i=0; i>A[i]; + } + + for(int i=0; i>B[i]; + } + + int* C = merge(A,n,B,m); + display(C,m+n); + + return 0; +} diff --git a/Algorithms/Mergesort.cpp b/Algorithms/Mergesort.cpp new file mode 100644 index 0000000..d68570b --- /dev/null +++ b/Algorithms/Mergesort.cpp @@ -0,0 +1,94 @@ +// C++ program for Merge Sort +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(int array[], int const left, int const mid, int const right) +{ + auto const subArrayOne = mid - left + 1; + auto const subArrayTwo = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArrayOne], + *rightArray = new int[subArrayTwo]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (auto i = 0; i < subArrayOne; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArrayTwo; j++) + rightArray[j] = array[mid + 1 + j]; + + auto indexOfSubArrayOne = 0, // Initial index of first sub-array + indexOfSubArrayTwo = 0; // Initial index of second sub-array + int indexOfMergedArray = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { + if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { + array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + } + else { + array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + } + indexOfMergedArray++; + } + // Copy the remaining elements of + // left[], if there are any + while (indexOfSubArrayOne < subArrayOne) { + array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + indexOfMergedArray++; + } + // Copy the remaining elements of + // right[], if there are any + while (indexOfSubArrayTwo < subArrayTwo) { + array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + indexOfMergedArray++; + } +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int array[], int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + auto arr_size = sizeof(arr) / sizeof(arr[0]); + + cout << "Given array is \n"; + printArray(arr, arr_size); + + mergeSort(arr, 0, arr_size - 1); + + cout << "\nSorted array is \n"; + printArray(arr, arr_size); + return 0; +} + +// This code is contributed by Mayank Tyagi +// This code was revised by Joshua Estes diff --git a/Algorithms/PrimsMinSpanningTree.cpp b/Algorithms/PrimsMinSpanningTree.cpp new file mode 100644 index 0000000..d266a45 --- /dev/null +++ b/Algorithms/PrimsMinSpanningTree.cpp @@ -0,0 +1,112 @@ +#include +#define V 8 +#define I 32767 + +using namespace std; + +void PrintMST(int T[][V - 2], int G[V][V]) +{ + cout << "\nMinimum Spanning Tree Edges (w/ cost)\n" + << endl; + int sum{0}; + for (int i{0}; i < V - 2; i++) + { + int c = G[T[0][i]][T[1][i]]; + cout << "[" << T[0][i] << "]---[" << T[1][i] << "] cost: " << c << endl; + sum += c; + } + cout << endl; + cout << "Total cost of MST: " << sum << endl; +} + +void PrimsMST(int G[V][V], int n) +{ + int u; + int v; + int min{I}; + int track[V]; + int T[2][V - 2]{0}; + + // Initial: Find min cost edge + for (int i{1}; i < V; i++) + { + track[i] = I; // Initialize track array with INFINITY + for (int j{i}; j < V; j++) + { + if (G[i][j] < min) + { + min = G[i][j]; + u = i; + v = j; + } + } + } + T[0][0] = u; + T[1][0] = v; + track[u] = track[v] = 0; + + // Initialize track array to track min cost edges + for (int i{1}; i < V; i++) + { + if (track[i] != 0) + { + if (G[i][u] < G[i][v]) + { + track[i] = u; + } + else + { + track[i] = v; + } + } + } + + // Repeat + for (int i{1}; i < n - 1; i++) + { + int k; + min = I; + for (int j{1}; j < V; j++) + { + if (track[j] != 0 && G[j][track[j]] < min) + { + k = j; + min = G[j][track[j]]; + } + } + T[0][i] = k; + T[1][i] = track[k]; + track[k] = 0; + + // Update track array to track min cost edges + for (int j{1}; j < V; j++) + { + if (track[j] != 0 && G[j][k] < G[j][track[j]]) + { + track[j] = k; + } + } + } + PrintMST(T, G); +} + +int main() +{ + + int cost[V][V]{ + {I, I, I, I, I, I, I, I}, + {I, I, 25, I, I, I, 5, I}, + {I, 25, I, 12, I, I, I, 10}, + {I, I, 12, I, 8, I, I, I}, + {I, I, I, 8, I, 16, I, 14}, + {I, I, I, I, 16, I, 20, 18}, + {I, 5, I, I, I, 20, I, I}, + {I, I, 10, I, 14, 18, I, I}, + }; + + int n = sizeof(cost[0]) / sizeof(cost[0][0]) - 1; + + PrimsMST(cost, n); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Quick_sort.cpp b/Algorithms/Quick_sort.cpp new file mode 100644 index 0000000..c077bd4 --- /dev/null +++ b/Algorithms/Quick_sort.cpp @@ -0,0 +1,73 @@ +/* C implementation QuickSort */ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places +the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) +to left of pivot and all greater elements to right +of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + int arr[] = {10, 7, 8, 9, 1, 5}; + int n = sizeof(arr)/sizeof(arr[0]); + quickSort(arr, 0, n-1); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} diff --git a/Algorithms/Quicksort.cpp b/Algorithms/Quicksort.cpp new file mode 100644 index 0000000..c077bd4 --- /dev/null +++ b/Algorithms/Quicksort.cpp @@ -0,0 +1,73 @@ +/* C implementation QuickSort */ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places +the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) +to left of pivot and all greater elements to right +of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + int arr[] = {10, 7, 8, 9, 1, 5}; + int n = sizeof(arr)/sizeof(arr[0]); + quickSort(arr, 0, n-1); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} diff --git a/Algorithms/Radixsort.cpp b/Algorithms/Radixsort.cpp new file mode 100644 index 0000000..6db9d2d --- /dev/null +++ b/Algorithms/Radixsort.cpp @@ -0,0 +1,75 @@ +// C++ implementation of Radix Sort +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = {0}; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) + { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +} diff --git a/Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp b/Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp new file mode 100644 index 0000000..1f53a76 --- /dev/null +++ b/Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp @@ -0,0 +1,98 @@ +/* C++ Program to remove duplicates from a sorted linked list */ +#include +using namespace std; + +/* Link list node */ +class Node +{ + public: + int data; + Node* next; +}; + +/* The function removes duplicates from a sorted list */ +void removeDuplicates(Node* head) +{ + /* Pointer to traverse the linked list */ + Node* current = head; + + /* Pointer to store the next pointer of a node to be deleted*/ + Node* next_next; + + /* do nothing if the list is empty */ + if (current == NULL) + return; + + /* Traverse the list till last node */ + while (current->next != NULL) + { + /* Compare current node with next node */ + if (current->data == current->next->data) + { + /* The sequence of steps is important*/ + next_next = current->next->next; + free(current->next); + current->next = next_next; + } + else /* This is tricky: only advance if no deletion */ + { + current = current->next; + } + } +} + +/* UTILITY FUNCTIONS */ +/* Function to insert a node at the beginning of the linked list */ +void push(Node** head_ref, int new_data) +{ + /* allocate node */ + Node* new_node = new Node(); + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +/* Function to print nodes in a given linked list */ +void printList(Node *node) +{ + while (node!=NULL) + { + cout<<" "<data; + node = node->next; + } +} + +/* Driver program to test above functions*/ +int main() +{ + /* Start with the empty list */ + Node* head = NULL; + + /* Let us create a sorted linked list to test the functions + Created linked list will be 11->11->11->13->13->20 */ + push(&head, 20); + push(&head, 13); + push(&head, 13); + push(&head, 11); + push(&head, 11); + push(&head, 11); + + cout<<"Linked list before duplicate removal "; + printList(head); + + /* Remove duplicates from linked list */ + removeDuplicates(head); + + cout<<"\nLinked list after duplicate removal "; + printList(head); + + return 0; +} + +// This code is contributed by rathbhupendra diff --git a/Algorithms/Reverse_Array.cpp b/Algorithms/Reverse_Array.cpp new file mode 100644 index 0000000..4b29f6d --- /dev/null +++ b/Algorithms/Reverse_Array.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +void display(int A[],int n){ + for(int i=0; i>n; + int A[n]; + + for(int i=0; i>A[i]; + } + + reverse(A,n); + display(A,n); + + return 0; +} diff --git a/Algorithms/Tower Of Hanoi.cpp b/Algorithms/Tower Of Hanoi.cpp new file mode 100644 index 0000000..947a465 --- /dev/null +++ b/Algorithms/Tower Of Hanoi.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +void TOH(int n,char a,char b,char c) +{ + if(n==1) + { + cout<<"Move Disk "< +#include + +using namespace std; + +vector z_function(string &p,string &t) +{ + string s=p+'#'+t; + int n=s.size(),l=0,r=0; //[l,r] is the current segment matching with the prefix + vector z(n,0); + for(int i=1;i length upto upper index bound + //z[i-l]--> previously matching segement length for prefix + + while(i+z[i]r) //i+z[i]-1 last index of the matching prefix pattern + l=i,r=i+z[i]-1; + } + return z; +} + +int main() +{ + string p,t; + cout<<"\nEnter a pattern : "; + cin>>p; + cout<<"\nEnter a text to be searched for the pattern : "; + cin>>t; + vector z=z_function(p,t); + vector ans; + for(int i=0;i +using namespace std; + +int binarySearch(int array[], int x, int low, int high) { + + // Repeat until the pointers low and high meet each other + while (low <= high) { + int mid = low + (high - low) / 2; + + if (array[mid] == x) + return mid; + + if (array[mid] < x) + low = mid + 1; + + else + high = mid - 1; + } + + return -1; +} + +int main(void) { + int array[] = {3, 4, 5, 6, 7, 8, 9}; + int x = 4; + int n = sizeof(array) / sizeof(array[0]); + int result = binarySearch(array, x, 0, n - 1); + if (result == -1) + printf("Not found"); + else + printf("Element is found at index %d", result); +} \ No newline at end of file diff --git a/Algorithms/binary_search_Recursive.cpp b/Algorithms/binary_search_Recursive.cpp new file mode 100644 index 0000000..d9f9b31 --- /dev/null +++ b/Algorithms/binary_search_Recursive.cpp @@ -0,0 +1,37 @@ +int binsearch(int A[], int low, int high, int key){ + + if (low<=high){ + int mid = low + (high-low)/2; + + if(key== A[mid]){ + return mid; + } + + else if (key>m; + int A[m]; + + for(int i=0; i>A[i]; + } + //Example code to call the binary function + //cout<= 0): + y=y+1 + slope_error =slope_error - 2 * (x2 - x1) + + + +x1= int(input()) +x2= int(input()) +y1= int(input()) +y2= int(input()) + +point1 = [x1,y1] +point2 = [x2, y2] + +x_values = [point1[0], point2[0]] + + +y_values = [point1[1], point2[1]] + + +plt.plot(x_values,y_values) +plt.show() + diff --git a/Algorithms/circular queue.c b/Algorithms/circular queue.c new file mode 100644 index 0000000..19b3748 --- /dev/null +++ b/Algorithms/circular queue.c @@ -0,0 +1,50 @@ +#include +#include +#define size 3 +void insert(); +void delete(); +void display(); +int front=-1; +int rear =-1; +int a[size]; +int main() +{ + int d; + printf("\n\n\n LIST OF CHOICES AND MENU"); + printf("=========================>>"); + printf("\n 1. insert"); + printf("\n 2. delete"); + printf("\n 3. DISPLAY"); + printf("\n 4. BYE BYE"); + while(1) + { + printf("\n\n enter your choice="); + scanf("%d",&d); + switch(d) + { + case 1: + { + insert(); + break; + } + case 2: + { + delete(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + exit(0); + } + default: + { + printf("\n INVALID INPUT !!!!!!"); + } + } + } + } diff --git a/Algorithms/duplicate_elements_1.cpp b/Algorithms/duplicate_elements_1.cpp new file mode 100644 index 0000000..bdd0745 --- /dev/null +++ b/Algorithms/duplicate_elements_1.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +int main() +{ + int n, i,j ,Ld=0; + cout << "How many numbers? "; + cin >> n; + int A[n]; + cout << "Enter the numbers : "; + for (i = 0; i < n; i++) + cin >> A[i]; + + for (int i = 0; i < n; i++) + { + if (A[i]==A[i+1] && A[i]!=Ld) + { + cout<<"Duplicates element are "< +using namespace std; + +int max(int A[], int n) +{ + int m = A[0]; + for (int i = 0; i < n; i++) + { + if (A[i] > m) + m = A[i]; + } + return m; +} + +int main() +{ + int n, i; + cout << "How many numbers? "; + cin >> n; + int A[n]; + cout << "Enter the numbers : "; + for (i = 0; i < n; i++) + cin >> A[i]; + + int h = max(A, n) + 1; + int *H = new int[h]; + for (i = 0; i < h; i++) + H[i] = 0; + for (i = 0; i < n; i++) + H[A[i]]++; + for (i = 0; i <= h; i++) + { + if (H[i] > 1) + cout << i << " occurs " << H[i] << " times" << endl; + } + + return 0; +} \ No newline at end of file diff --git a/Algorithms/heap_sort.cpp b/Algorithms/heap_sort.cpp new file mode 100644 index 0000000..fc00de0 --- /dev/null +++ b/Algorithms/heap_sort.cpp @@ -0,0 +1,39 @@ +void heapify(int arr[], int n, int i) + { + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if(l arr[largest]) + largest = l; + + if(r arr[largest]) + largest = r; + + if(largest != i) + { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } + + } + + +void buildHeap(int arr[], int n) + { + for(int i= (n/2)-1; i>=0; i--) + heapify(arr, n, i); + } + + +void heapSort(int arr[], int n) + { + buildHeap(arr, n); + for(int i= n-1; i>0; i--) + { + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } + } + + diff --git a/Algorithms/insertion-sort.cpp b/Algorithms/insertion-sort.cpp new file mode 100644 index 0000000..9e411ec --- /dev/null +++ b/Algorithms/insertion-sort.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +/* Function to sort an array using insertion sort*/ +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +/* Driver code */ +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} diff --git a/Algorithms/job_sequencing.cpp b/Algorithms/job_sequencing.cpp new file mode 100644 index 0000000..7c5dd6c --- /dev/null +++ b/Algorithms/job_sequencing.cpp @@ -0,0 +1,215 @@ +#include + +#include + +#define MAX 100 + +#include + +#include + +using namespace std; + +class Job + +{ + + public: + char id[5]; + int deadline; + int Profit; + +}; + +void jobSequencing(Job jobs[], int n); + +int minvalue(int x, int y) + +{ + + if (x < y) + + return x; + + return y; + +} + +int main(void) + +{ + + int i, j, n; + + Job jobs[5]; + + cout << "\Enter the number of jobs:"; + + cin >> n; + + for (i = 0; i < n; i++) + + { + + cout << "\nEnter the job:"; + + cin >> jobs[i].id; + + cout << "\nEnter the Profit:"; + + cin >> jobs[i].Profit; + + cout << "\nEnter deadline:"; + + cin >> jobs[i].deadline; + + } + + Job temp; + + cout << "\nJob(i)\t\t Profit\t\t Deadline\t \n\n"; + + cout << "--------------------------------------------------"; + + for (i = 0; i < n; i++) + + { + + cout << "\n\n"; + + cout << jobs[i].id << "\t\t" << jobs[i].Profit << "\t\t" << jobs[i].deadline; + + } + + for (i = 1; i < n; i++) + + { + + for (j = 0; j < n - i; j++) + + { + + if (jobs[j + 1].Profit > jobs[j].Profit) + + { + + temp = jobs[j + 1]; + + jobs[j + 1] = jobs[j]; // descending order + + jobs[j] = temp; + + } + + } + + } + + cout << "\n\nTotal nuber of jobs:" << n << endl; + + jobSequencing(jobs, n); + + getch(); + + return 0; + +} + +void jobSequencing(Job jobs[], int n) + +{ + + int i, j, k, maxprofit; + + int timeslot[MAX]; + + int filledTimeSlot = 0; + + int dmax = 0; + + for (i = 0; i < n; i++) + + { + + if (jobs[i].deadline > dmax) + + { + + dmax = jobs[i].deadline; + + } + } + + + + cout << "\nTotal time slot: " << dmax << endl; + + for (i = 1; i <= dmax; i++) + + { + + timeslot[i] = -1; + + } + + cout << "\n\nnumber of jobs done: " << dmax << endl; + + for (i = 1; i <= n; i++) + + { + + k = minvalue(dmax, jobs[i - 1].deadline); + + while (k >= 1) + + { + + if (timeslot[k] == -1) + + { + + timeslot[k] = i - 1; + + filledTimeSlot++; + + break; + + } + + k--; + + } + + if (filledTimeSlot == dmax) + + { + + break; + + } + + } + + // cout<<"\nJobs done \:n"; + + for (i = 1; i <= dmax; i++) + + { + + cout << "\tJob" << jobs[timeslot[i]].id << " at time:" << i << endl; // at particular time slot + + } + + maxprofit = 0; + + for (i = 1; i <= dmax; i++) + + { + + maxprofit += jobs[timeslot[i]].Profit; + + } + + cout << "\ntotal profit: " << maxprofit; + +} diff --git a/Algorithms/kadane_algo.cpp b/Algorithms/kadane_algo.cpp new file mode 100644 index 0000000..ec22554 --- /dev/null +++ b/Algorithms/kadane_algo.cpp @@ -0,0 +1,41 @@ +// C++ program to print largest contiguous array sum using KADANE ALGORITHM +#include +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0, + start =0, end = 0, s=0; + + for (int i=0; i< size; i++ ) + { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) + { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) + { + max_ending_here = 0; + s = i + 1; + } + } + cout << "Maximum contiguous sum is " + << max_so_far << endl; + cout << "Starting index "<< start + << endl << "Ending index "<< end << endl; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + return 0; +} diff --git a/Algorithms/kth largest element in array.cpp b/Algorithms/kth largest element in array.cpp new file mode 100644 index 0000000..bc6e610 --- /dev/null +++ b/Algorithms/kth largest element in array.cpp @@ -0,0 +1,35 @@ +// Approach --- using min heap + +#include +using namespace std; + +int kthlargest(vectorv ,int k){ + + priority_queue,greater> minh; + for(int i=0;ik) + { + minh.pop(); + } + } + return minh.top(); +} + +int main(){ + + vectorv; + int k= 2 , ans; + + v.push_back(6); + v.push_back(5); + v.push_back(3); + v.push_back(2); + v.push_back(8); + v.push_back(10); + +ans= kthlargest(v,k); + cout<<"kth largest element is "< +using namespace std; + +// A linked list node +struct Node +{ + int data; + struct Node *next; +}; + +/*----------------Function to insert a new node in front of the list-------------------*/ +void push(struct Node **head, int node_data) +{ + /* 1. create and allocate node */ + struct Node *newNode = new Node; + + /* 2. assign data to node */ + newNode->data = node_data; + + /* 3. set next of new node as head */ + newNode->next = (*head); + + /* 4. move the head to point to the new node */ + (*head) = newNode; +} + +/*----------------Function to insert new node after a given node--------------------*/ +void insertAfter(struct Node *prev_node, int node_data) +{ + /*1. check if the given prev_node is NULL */ + if (prev_node == NULL) + { + cout << "the given previous node is required,cannot be NULL"; + return; + } + + /* 2. create and allocate new node */ + struct Node *newNode = new Node; + + /* 3. assign data to the node */ + newNode->data = node_data; + + /* 4. Make next of new node as next of prev_node */ + newNode->next = prev_node->next; + + /* 5. move the next of prev_node as new_node */ + prev_node->next = newNode; +} + +/*----------------Function to insert new node at the end of the linked list------------------ */ +void append(struct Node **head, int node_data) +{ + /* 1. create and allocate node */ + struct Node *newNode = new Node; + + struct Node *last = *head; /* used in step 5*/ + + /* 2. assign data to the node */ + newNode->data = node_data; + + /* 3. set next pointer of new node to null as its the last node*/ + newNode->next = NULL; + + /* 4. if list is empty, new node becomes first node */ + if (*head == NULL) + { + *head = newNode; + return; + } + + /* 5. Else traverse till the last node */ + while (last->next != NULL) + last = last->next; + + /* 6. Change the next of last node */ + last->next = newNode; + return; +} + +/*-------------------Function to display linked list contents ------------------------*/ +void displayList(struct Node *node) +{ + //traverse the list to display each node + while (node != NULL) + { + cout << node->data << "-->"; + node = node->next; + } + + if (node == NULL) + cout << "null"; +} + +/*-----------------------------------MAIN FUNCTION-------------------------------------*/ +int main() +{ + /* empty list */ + struct Node *head = NULL; + + // Insert 10. + append(&head, 10); + + // Insert 20 at the beginning. + push(&head, 20); + + // Insert 30 at the beginning. + push(&head, 30); + + // Insert 40 at the end. + append(&head, 40); // + + // Insert 50, after 20. + insertAfter(head->next, 50); + + cout << "Final linked list: " << endl; + displayList(head); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/merge_sort_C++.cpp b/Algorithms/merge_sort_C++.cpp new file mode 100644 index 0000000..0cd202e --- /dev/null +++ b/Algorithms/merge_sort_C++.cpp @@ -0,0 +1,100 @@ +// C++ program for Merge Sort +#include +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(vector& array, int const left, int const mid, int const right) +{ + auto const subArr1 = mid - left + 1; + auto const subArr2 = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArr1], + *rightArray = new int[subArr2]; + + // Copying data to temp arrays + for (auto i = 0; i < subArr1; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArr2; j++) + rightArray[j] = array[mid + 1 + j]; + + auto idxSubArr1 = 0, // Initial index of first sub-array + idxSubArr2 = 0; // Initial index of second sub-array + int idxMrgArr = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (idxSubArr1 < subArr1 && idxSubArr2 < subArr2) { + if (leftArray[idxSubArr1] <= rightArray[idxSubArr2]) { + array[idxMrgArr] = leftArray[idxSubArr1]; + idxSubArr1++; + } + else { + array[idxMrgArr] = rightArray[idxSubArr2]; + idxSubArr2++; + } + idxMrgArr++; + } + // Copy the remaining elements of + // left[], if there are any + while (idxSubArr1 < subArr1) { + array[idxMrgArr] = leftArray[idxSubArr1]; + idxSubArr1++; + idxMrgArr++; + } + // Copy the remaining elements of + // right[], if there are any + while (idxSubArr2 < subArr2) { + array[idxMrgArr] = rightArray[idxSubArr2]; + idxSubArr2++; + idxMrgArr++; + } +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(vector& array, int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// Function to print an array +void printArray(vector& A, int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int n, input; + cout<<"enter no. of array elements:"; + cin>> n; + + vector arr; + for (int i = 0; i < n; i++) + { + cin>> input; + arr.push_back(input); + } + + + cout << "Input array is: "; + printArray(arr, n); + + mergeSort(arr, 0, n - 1); + + cout << "\nSorted array is: "; + printArray(arr, n); + return 0; +} diff --git a/Algorithms/mergesort.py b/Algorithms/mergesort.py new file mode 100644 index 0000000..40d32d1 --- /dev/null +++ b/Algorithms/mergesort.py @@ -0,0 +1,78 @@ + +# Merges two subarrays of arr[]. +# First subarray is arr[l..m] +# Second subarray is arr[m+1..r] + + +def merge(arr, l, m, r): + n1 = m - l + 1 + n2 = r - m + + # create temp arrays + L = [0] * (n1) + R = [0] * (n2) + + # Copy data to temp arrays L[] and R[] + for i in range(0, n1): + L[i] = arr[l + i] + + for j in range(0, n2): + R[j] = arr[m + 1 + j] + + # Merge the temp arrays back into arr[l..r] + i = 0 # Initial index of first subarray + j = 0 # Initial index of second subarray + k = l # Initial index of merged subarray + + while i < n1 and j < n2: + if L[i] <= R[j]: + arr[k] = L[i] + i += 1 + else: + arr[k] = R[j] + j += 1 + k += 1 + + # Copy the remaining elements of L[], if there + # are any + while i < n1: + arr[k] = L[i] + i += 1 + k += 1 + + # Copy the remaining elements of R[], if there + # are any + while j < n2: + arr[k] = R[j] + j += 1 + k += 1 + +# l is for left index and r is right index of the +# sub-array of arr to be sorted + + +def mergeSort(arr, l, r): + if l < r: + + # Same as (l+r)//2, but avoids overflow for + # large l and h + m = l+(r-l)//2 + + # Sort first and second halves + mergeSort(arr, l, m) + mergeSort(arr, m+1, r) + merge(arr, l, m, r) + + +# Driver code to test above +arr = [12, 11, 13, 5, 6, 7] +n = len(arr) +print("Given array is") +for i in range(n): + print("%d" % arr[i]), + +mergeSort(arr, 0, n-1) +print("\n\nSorted array is") +for i in range(n): + print("%d" % arr[i]), + diff --git a/Algorithms/missingelement.cpp b/Algorithms/missingelement.cpp new file mode 100644 index 0000000..26f9bc7 --- /dev/null +++ b/Algorithms/missingelement.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +int Missing_Elements_1(int A[]) +{ + int diff,l=A[0],i; + diff=l-0; + for (int i = 0; i < 10; i++) + { + if (A[i]-i!=diff) + { + while (diff +using namespace std; + +int max(int A[], int n) +{ + int m = A[0]; + for (int i = 0; i < n; i++) + { + if (A[i] > m) + m = A[i]; + } + return m; +} +int main() +{ + int n, i; + cout << "How many numbers? "; + cin >> n; + int A[n]; + cout << "Enter the numbers : "; + for (i = 0; i < n; i++) + cin >> A[i]; + cout << "The numbers are : "; + for (i = 0; i < n; i++) + cout << A[i] << " "; + cout << endl; + int l = A[0]; + int h = max(A, n) ; + int *H = new int[h]; + for (i = 0; i < h; i++) + H[i] = 0; + + cout << "The hash table is : "; + for (i = 0; i < h; i++) + cout << H[i] << " "; + + for (i = 0; i < n; i++) + H[A[i]]++; + cout << endl + << "Missing Elements" << endl; + for (i = 1; i <= h; i++) + { + if (H[i] == 0) + cout << i << " "; + } + cout << endl; +} diff --git a/Algorithms/queue_implementation.cpp b/Algorithms/queue_implementation.cpp new file mode 100644 index 0000000..92463fc --- /dev/null +++ b/Algorithms/queue_implementation.cpp @@ -0,0 +1,137 @@ +#include +#include +using namespace std; + +// Define the default capacity of a queue +#define SIZE 10 + +// A class to store a queue +class queue +{ + int *arr; // array to store queue elements + int capacity; // maximum capacity of the queue + int front; // front points to the front element in the queue (if any) + int rear; // rear points to the last element in the queue + int count; // current size of the queue + +public: + queue(int size = SIZE); // constructor + ~queue(); // destructor + + void dequeue(); + void enqueue(int x); + int peek(); + int size(); + bool isEmpty(); + bool isFull(); +}; + +// Constructor to initialize a queue +queue::queue(int size) +{ + arr = new int[size]; + capacity = size; + front = 0; + rear = -1; + count = 0; +} + +// Destructor to free memory allocated to the queue +queue::~queue() +{ + delete[] arr; +} + +// Utility function to dequeue the front element +void queue::dequeue() +{ + // check for queue underflow + if (isEmpty()) + { + cout << "Underflow\nProgram Terminated\n"; + exit(EXIT_FAILURE); + } + + cout << "Removing " << arr[front] << endl; + + front = (front + 1) % capacity; + count--; +} + +// Utility function to add an item to the queue +void queue::enqueue(int item) +{ + // check for queue overflow + if (isFull()) + { + cout << "Overflow\nProgram Terminated\n"; + exit(EXIT_FAILURE); + } + + cout << "Inserting " << item << endl; + + rear = (rear + 1) % capacity; + arr[rear] = item; + count++; +} + +// Utility function to return the front element of the queue +int queue::peek() +{ + if (isEmpty()) + { + cout << "Underflow\nProgram Terminated\n"; + exit(EXIT_FAILURE); + } + return arr[front]; +} + +// Utility function to return the size of the queue +int queue::size() +{ + return count; +} + +// Utility function to check if the queue is empty or not +bool queue::isEmpty() +{ + return (size() == 0); +} + +// Utility function to check if the queue is full or not +bool queue::isFull() +{ + return (size() == capacity); +} + +int main() +{ + // create a queue of capacity 5 + queue q(5); + + q.enqueue(1); + q.enqueue(2); + q.enqueue(3); + + cout << "The front element is " << q.peek() << endl; + q.dequeue(); + + q.enqueue(4); + + cout << "The queue size is " << q.size() << endl; + + q.dequeue(); + q.dequeue(); + q.dequeue(); + + if (q.isEmpty()) + { + cout << "The queue is empty\n"; + } + else + { + cout << "The queue is not empty\n"; + } + + return 0; +} \ No newline at end of file diff --git a/Algorithms/remove_duplicates_in_sorted_array.cpp b/Algorithms/remove_duplicates_in_sorted_array.cpp new file mode 100644 index 0000000..7ffbecd --- /dev/null +++ b/Algorithms/remove_duplicates_in_sorted_array.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; +int removeDuplicates(int arr[], int n) +{ + if (n==0 || n==1) + return n; + int temp[n]; + int j = 0; + for (int i=0; i>n; + int arr[n]; + for(int i = 0;i>arr[i]; + + n = removeDuplicates(arr, n); + + //Displaying updated array + for (int i=0; i +#define MAX 50 + +using namespace std; + +void swap1(int &x, int &y){ + int temp = x; + x = y; + y = temp; +} + +void selectionSort(int arr[], int n){ + int minindex; + for (int i = 0; i < n-1; i++){ + minindex = i; + for(int j = i+1; j < n; j++){ + if(arr[j] < arr[minindex]){ + minindex = j; + } + } + if(minindex != i){ + swap1(arr[i], arr[minindex]); + } + } +} + +void print1(int arr[], int n){ + cout<<"After Sorting:"<> n; + for(int i=0; i>arr[i]; + } + cout<<"Before Sorting: "< + +void ShellSort(int sortedArray[], int size) +{ + for (int t = size / 2; t > 0; t /= 2) + { + for (int i = t; i < size; i++) + { + int temp = sortedArray[i]; + int j; + for (j = i; j >= t && sortedArray[j - t] > temp; j -= t) + { + sortedArray[j] = sortedArray[j - t]; + } + sortedArray[j] = temp; + } + } +} + +int main() +{ + int n; + cout << "Enter the size of the array "; + cin >> n; + int arr[n]; + cout << "Enter the elements in the array \n"; + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + cout << "\n"; + + cout << "Original Array "; + cout << "["; + for (int i = 0; i < n; i++) + { + cout << arr[i] << ", "; + } + cout << "\b\b"; + cout << "]"; + + cout << "\n"; + ShellSort(arr, n); + + cout << "Array after Shell Sort is "; + cout << "["; + for (int i = 0; i < n; i++) + { + cout << arr[i] << ", "; + } + cout << "\b\b"; + cout << "]"; + cout << endl; + + cout << "\n"; + + return 0; +} \ No newline at end of file diff --git a/Algorithms/stack_implementation.cpp b/Algorithms/stack_implementation.cpp new file mode 100644 index 0000000..e4a99e5 --- /dev/null +++ b/Algorithms/stack_implementation.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; +int stack[100], n = 100, top = -1; +void push(int val) +{ + if (top >= n - 1) + cout << "Stack Overflow" << endl; + else + { + top++; + stack[top] = val; + } +} +void pop() +{ + if (top <= -1) + cout << "Stack Underflow" << endl; + else + { + cout << "The popped element is " << stack[top] << endl; + top--; + } +} +void display() +{ + if (top >= 0) + { + cout << "Stack elements are:"; + for (int i = top; i >= 0; i--) + cout << stack[i] << " "; + cout << endl; + } + else + cout << "Stack is empty"; +} +int main() +{ + int ch, val; + cout << "1) Push in stack" << endl; + cout << "2) Pop from stack" << endl; + cout << "3) Display stack" << endl; + cout << "4) Exit" << endl; + do + { + cout << "Enter choice: " << endl; + cin >> ch; + switch (ch) + { + case 1: + { + cout << "Enter value to be pushed:" << endl; + cin >> val; + push(val); + break; + } + case 2: + { + pop(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + cout << "Exit" << endl; + break; + } + default: + { + cout << "Invalid Choice" << endl; + } + } + } while (ch != 4); + return 0; +} \ No newline at end of file diff --git a/CompanywiseSolution/ADOBE/Linked_List/question.md b/CompanywiseSolution/ADOBE/Linked_List/question.md new file mode 100644 index 0000000..8989f64 --- /dev/null +++ b/CompanywiseSolution/ADOBE/Linked_List/question.md @@ -0,0 +1,26 @@ +Clone a linked list with next and random pointer. + +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. + +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. + +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. + +Return the head of the copied linked list. + +Example 1: + +N = 4, M = 2 +value = {1,2,3,4} +pairs = {{1,2},{2,4}} +Output: 1 +Explanation: In this test case, there +are 4 nodes in linked list. Among these +4 nodes, 2 nodes have arbitrary pointer +set, rest two nodes have arbitrary pointer +as NULL. Second line tells us the value +of four nodes. The third line gives the +information about arbitrary pointers. +The first node arbitrary pointer is set to +node 2. The second node arbitrary pointer +is set to node 4. \ No newline at end of file diff --git a/CompanywiseSolution/ADOBE/Linked_List/solution.cpp b/CompanywiseSolution/ADOBE/Linked_List/solution.cpp new file mode 100644 index 0000000..b866ed7 --- /dev/null +++ b/CompanywiseSolution/ADOBE/Linked_List/solution.cpp @@ -0,0 +1,191 @@ +#include + +using namespace std; +/* Link list Node */ +struct Node { + int data; + Node *next; + Node *arb; + + Node(int x) { + data = x; + next = NULL; + arb = NULL; + } +}; + + + + // } Driver Code Ends +class Solution +{ + public: + Node *copyList(Node *head) + { + Node *curr=head; + + while(curr!=NULL) + { + Node *nex=curr->next; + curr->next= new Node(curr->data); + curr->next->next=nex; + curr=nex; + } + for(curr=head;curr!=NULL;curr=curr->next->next) + { + curr->next->arb=(curr->arb !=NULL)?curr->arb->next : NULL; + } + Node *res=head->next; + for(curr=head;curr->next!=NULL;) + { + Node *temp=curr->next; + curr->next=curr->next->next; + curr=temp; + } + return res; + } + +}; + +// { Driver Code Starts. + + +void print(Node *root) { + Node *temp = root; + while (temp != NULL) { + int k; + if (temp->arb == NULL) + k = -1; + else + k = temp->arb->data; + cout << temp->data << " " << k << " "; + temp = temp->next; + } +} + + +void append(Node **head_ref, Node **tail_ref, int new_data) { + + Node *new_node = new Node(new_data); + if (*head_ref == NULL) { + *head_ref = new_node; + } else + (*tail_ref)->next = new_node; + *tail_ref = new_node; +} + +bool validation(Node *head, Node *res) { + + + Node *temp1 = head; + Node *temp2 = res; + + int len1 = 0, len2 = 0; + while (temp1 != NULL) { + len1++; + temp1 = temp1->next; + } + while (temp2 != NULL) { + len2++; + temp2 = temp2->next; + } + + /*if lengths not equal */ + + if (len1 != len2) return false; + + temp1 = head; + temp2 = res; + map a; + while (temp1 != NULL) { + + if(temp1==temp2) + return false; + + if (temp1->data != temp2->data) return false; + if (temp1->arb != NULL and temp2->arb != NULL) { + if (temp1->arb->data != temp2->arb->data) + return false; + } else if (temp1->arb != NULL and temp2->arb == NULL) + return false; + else if (temp1->arb == NULL and temp2->arb != NULL) + return false; + a[temp1]=temp2; + temp1 = temp1->next; + temp2 = temp2->next; + } + + + temp1 = head; + temp2 = res; + while (temp1 != NULL) { + + if (temp1->arb != NULL and temp2->arb != NULL) { + if (a[temp1->arb] != temp2->arb) return false; + } + temp1 = temp1->next; + temp2 = temp2->next; + } + return true; +} + + + +int main() { + + int T, i, n, l, k; + Node *generated_addr = NULL; + /*reading input stuff*/ + cin >> T; + while (T--) { + generated_addr = NULL; + struct Node *head = NULL, *tail = NULL; + struct Node *head2 = NULL, *tail2 = NULL; + cin >> n >> k; + for (i = 1; i <= n; i++) { + cin >> l; + append(&head, &tail, l); + append(&head2, &tail2, l); + } + for (int i = 0; i < k; i++) { + int a, b; + cin >> a >> b; + + Node *tempA = head; + Node *temp2A = head2; + int count = -1; + + while (tempA != NULL) { + count++; + if (count == a - 1) break; + tempA = tempA->next; + temp2A = temp2A->next; + } + Node *tempB = head; + Node *temp2B = head2; + count = -1; + + while (tempB != NULL) { + count++; + if (count == b - 1) break; + tempB = tempB->next; + temp2B = temp2B->next; + } + + // when both a is greater than N + if (a <= n){ + tempA->arb = tempB; + temp2A->arb = temp2B; + } + } + /*read finished*/ + + generated_addr = head; + Solution ob; + struct Node *res = ob.copyList(head); + if(validation(head2,res)&&validation(head,res)) + cout << validation(head2, res) << endl; + else + cout << 0 << endl; + } + return 0; \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp new file mode 100644 index 0000000..16461a4 --- /dev/null +++ b/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp @@ -0,0 +1,55 @@ +// Problem Statement - Given an array in which all numbers except two are repeated once. +// (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. + +/* Examples - +Input: = 2 +arr[] = {1, 2, 3, 2, 1, 4} +Output: +3 4 +Explanation: +3 and 4 occur exactly once. + +Input: +N = 1 +arr[] = {2, 1, 3, 2} +Output: +1 3 +Explanation: +1 3 occur exactly once. +*/ + +#include +using namespace std; + +int setBit(int n, int pos) { + return ((n & (1 << pos)) != 0); +} +void uniquenumber(int arr[], int n) { + int xorsum = 0; + for (int i = 0; i < n; i++) { + xorsum = xorsum ^ arr[i]; + } + int tempxor = xorsum; + int setbit = 0; + int pos = 0; + while (setbit != 1) { + setbit = xorsum & 1; + pos++; + xorsum = xorsum >> 1; + } + int newxor = 0; + for (int i = 0; i < n; i++) { + if (setBit(arr[i], pos - 1)) { + newxor = newxor ^ arr[i]; + } + } + cout< +using namespace std; + +int getBit(int n, int pos) { + return ((n & (1 << pos)) != 0); +} + +int setBit(int n, int pos) { + return (n | (1 << pos)); +} +int uniquenumber(int arr[], int n) { + int result = 0; + for (int i = 0; i < 64; i++) { + int sum = 0; + for (int j = 0; j < n; j++) { + if (getBit(arr[j], i)) { + sum++; + } + } + if (sum % 3 != 0) { + result = setBit(result, i); + } + } + return result; +} + +int main() { + int arr[] = {1,2,3,4,1,2,3,1,2,3}; + + cout< +using namespace std; + +int numberofones(int n) { + int count = 0; + while (n) { + n = n & (n - 1); + count++; + } + return count; +} + +int main() { + int n; + cin>>n; + + cout< +using namespace std; + +int copysetbits(int x, int y, int l, int r) { + if (1 < l || r > 32) { + return false; + } + + for (int i = l; i <= r; i++) { + int mask = 1 << (i - 1); + + if (y & mask) { + x = x | mask; + } + } + return x; +} + +int main () { + int x, y, l, r; + cin>>x>>y>>l>>r; + cout< +using namespace std; + +int countsetbitsutil(int x) { + if ( x <= 0) { + return 0; + } + return (x % 2 == 0 ? 0 : 1) + countsetbitsutil(x / 2); +} + +int numberofones(int n) { + int count = 0; + for (int i = 0; i <= n; i++) { + count += countsetbitsutil(i); + } + return count; +} + +int main() { + int n; + cin>>n; + + cout< +using namespace std; + +int divide2int(int n) { + if (n == 0) { + return 0; + } + + int x = n >> 1; + return x; +} + +int main() { + int n; + cin>>n; + cout< +using namespace std; + +int flipped(int a, int b) { + int ans = a ^ b; + int count = 0; + while (ans) { + ans = ans & (ans - 1); + count++; + } + return count; +} + +int main () { + int a,b; + cin>>a>>b; + + cout< + +using namespace std; +long long int count(int S[], int m, int n) { + + + + long long t[m+1][n+1]; + + for(int i=0;i>t; + while(t--){ + int n,m; + cin>>n>>m; + int arr[m]; + for(int i=0;i>arr[i]; + + long long ans=count(arr,m,n); + cout< +using namespace std; + + // } Driver Code Ends +class Solution{ + + public: + int minDifference(int arr[], int n) { + + + + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + bool dp[n + 1][sum + 1]; + + for (int i = 0; i <= n; i++) + dp[i][0] = true; + + for (int i = 1; i <= sum; i++) + dp[0][i] = false; + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= sum; j++) { + + + if (arr[i - 1] <= j) + dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i-1][j]; + else + dp[i][j] = dp[i - 1][j]; + } + } + + + + int mn=INT_MAX; + for(int z=0;z<(sum/2)+1;z++) + { + if(dp[n][z]==true) + mn=min(mn,sum-2*z); + } + return mn; + + + + } +}; + + +// { Driver Code Starts. +int main() +{ + + + int t; + cin >> t; + while (t--) + { + int n; + cin >> n; + + int a[n]; + for(int i = 0; i < n; i++) + cin >> a[i]; + + + + Solution ob; + cout << ob.minDifference(a, n) << "\n"; + + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java b/CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java new file mode 100644 index 0000000..4784527 --- /dev/null +++ b/CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java @@ -0,0 +1,40 @@ +import java.util.Scanner; +public class Equilibrium { + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + System.out.println("Enter the size of an array :"); + int N = sc.nextInt(); + long [] temp = new long[N]; + System.out.println("Enter the number: "); + for(int i =0 ; i duplicates(int arr[], int n) { + // code here + ArrayList ar=new ArrayList<>(); + for (int i = 0; i = arr.length * 2) { + ar.add(i); + } + } + if(ar.isEmpty()) + ar.add(-1); + return ar; + } + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.println("Enter length of array arr"); + int n=sc.nextInt(); + System.out.println("Enter an array"); + int arr[]=new int[n]; + for(int i=0;i ans=duplicates(arr,n); + for(Integer val:ans) + System.out.print(val+" "); + System.out.println(); + } +} \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java b/CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java new file mode 100644 index 0000000..fa7000f --- /dev/null +++ b/CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java @@ -0,0 +1,40 @@ +import java.util.*; +public class MaxSecondMax { + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + System.out.println("Enter the size: "); + int N = sc.nextInt(); + int [] TempArr = new int [N]; + for(int j =0 ; j< N ; j++){ + System.out.println("Enter the Number: "); + TempArr[j] = sc.nextInt(); + } + + System.out.println(Max(TempArr , N)); + sc.close(); + } + + public static ArrayList Max( int arr[] , int size) + { + int counter = 0; + int temp =-1; + for(int i = 0 ; icounter){ + counter = arr[i]; + } + } + + for(int i =0 ; i al = new ArrayList(); + al.add(counter); + al.add(temp); + + return al;//code here. + } +} \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Max and Second Max/question.md b/CompanywiseSolution/Amazon/Max and Second Max/question.md new file mode 100644 index 0000000..e72b414 --- /dev/null +++ b/CompanywiseSolution/Amazon/Max and Second Max/question.md @@ -0,0 +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. \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/check_for_BST/questions.txt b/CompanywiseSolution/Amazon/check_for_BST/questions.txt new file mode 100644 index 0000000..76ab97d --- /dev/null +++ b/CompanywiseSolution/Amazon/check_for_BST/questions.txt @@ -0,0 +1,48 @@ +Given the root of a binary tree. Check whether it is a BST or not. +Note: We are considering that BSTs can not contain duplicate Nodes. +A BST is defined as follows: + The left subtree of a node contains only nodes with keys less than the node's key. + The right subtree of a node contains only nodes with keys greater than the node's key. + Both the left and right subtrees must also be binary search trees. + +Example 1: + +Input: + 2 + / \ +1 3 +Output: 1 +Explanation: +The left subtree of root node contains node +with key lesser than the root node’s key and +the right subtree of root node contains node +with key greater than the root node’s key. +Hence, the tree is a BST. + +Example 2: + +Input: + 2 + \ + 7 + \ + 6 + \ + 5 + \ + 9 + \ + 2 + \ + 6 +Output: 0 +Explanation: +Since the node with value 7 has right subtree +nodes with keys less than 7, this is not a BST. +Your Task: +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. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(Height of the BST). + + diff --git a/CompanywiseSolution/Amazon/check_for_BST/solution.cpp b/CompanywiseSolution/Amazon/check_for_BST/solution.cpp new file mode 100644 index 0000000..c077ff2 --- /dev/null +++ b/CompanywiseSolution/Amazon/check_for_BST/solution.cpp @@ -0,0 +1,26 @@ +class Solution +{ + public: + //Function to check whether a Binary Tree is BST or not. + bool helper(Node* root, int min, int max){ + if (root == NULL){ + return true; + } + if (root->data < min ){ + return false; + } + if (root->data >= max){ + return false; + } + return helper(root->left, min, root->data) && helper(root->right, root->data, max); + + } + bool isBST(Node* root) + { + // Your code here + int min = -1000001; + int max = 1000001; + + return helper(root, min, max); + } +}; diff --git a/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Question.txt b/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Question.txt new file mode 100644 index 0000000..2421481 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Question.txt @@ -0,0 +1,57 @@ +Kadane’s Algorithm: + +Initialize: + max_so_far = INT_MIN + max_ending_here = 0 + +Loop for each element of the array + (a) max_ending_here = max_ending_here + a[i] + (b) if(max_so_far < max_ending_here) + max_so_far = max_ending_here + (c) if(max_ending_here < 0) + max_ending_here = 0 +return max_so_far + +Explanation: +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 + +Lets take the example: + {-2, -3, 4, -1, -2, 1, 5, -3} + + max_so_far = max_ending_here = 0 + + for i=0, a[0] = -2 + max_ending_here = max_ending_here + (-2) + Set max_ending_here = 0 because max_ending_here < 0 + + for i=1, a[1] = -3 + max_ending_here = max_ending_here + (-3) + Set max_ending_here = 0 because max_ending_here < 0 + + for i=2, a[2] = 4 + max_ending_here = max_ending_here + (4) + max_ending_here = 4 + max_so_far is updated to 4 because max_ending_here greater + than max_so_far which was 0 till now + + for i=3, a[3] = -1 + max_ending_here = max_ending_here + (-1) + max_ending_here = 3 + + for i=4, a[4] = -2 + max_ending_here = max_ending_here + (-2) + max_ending_here = 1 + + for i=5, a[5] = 1 + max_ending_here = max_ending_here + (1) + max_ending_here = 2 + + for i=6, a[6] = 5 + max_ending_here = max_ending_here + (5) + max_ending_here = 7 + max_so_far is updated to 7 because max_ending_here is + greater than max_so_far + + for i=7, a[7] = -3 + max_ending_here = max_ending_here + (-3) + max_ending_here = 4 diff --git a/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Solution.java.java b/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Solution.java.java new file mode 100644 index 0000000..364f8a4 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Solution.java.java @@ -0,0 +1,29 @@ +import java.io.*; +// Java program to print largest contiguous array sum +import java.util.*; + +class Kadane +{ + public static void main (String[] args) + { + int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} diff --git a/CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt new file mode 100644 index 0000000..7f7be13 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt @@ -0,0 +1,25 @@ +Given a string S. The task is to convert characters of string to lowercase. + +Example 1: + +Input: S = "ABCddE" +Output: "abcdde" +Explanation: A, B, C and E are converted to +a, b, c and E thus all uppercase characters +of the string converted to lowercase letter. +Example 2: + +Input: S = "LMNOppQQ" +Output: "lmnoppqq" +Explanation: L, M, N, O, and Q are +converted to l, m, n, o and q thus +all uppercase characters of the +string converted to lowercase letter. +Your Task: +You dont need to read input or print anything. Complete the function toLower() which takes S as input parameter and returns the converted string. + +Expected Time Complexity:O(n) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= |S| <= 1000 \ No newline at end of file diff --git a/CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java new file mode 100644 index 0000000..07c4828 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java @@ -0,0 +1,32 @@ +// Initial template for Java + +import java.util.*; +import java.io.*; + +class GFG { + public static void main(String args[]) throws IOException { + BufferedReader read = + new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter no of words you want to check"); + int t = Integer.parseInt(read.readLine()); + + while (t-- > 0) { + System.out.println("Enter Word to conver to lowercase"); + String S = read.readLine(); + Solution ob = new Solution(); + + System.out.println(ob.toLower(S)); + } + } +}// } Driver Code Ends + + +// User function template for Java + +class Solution { + static String toLower(String S) { + String S1=S.toLowerCase(); + return S1; + } + +} \ No newline at end of file diff --git a/CompanywiseSolution/README.md b/CompanywiseSolution/README.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/CompanywiseSolution/README.md @@ -0,0 +1 @@ + diff --git a/CompanywiseSolution/deshaw/question.txt b/CompanywiseSolution/deshaw/question.txt new file mode 100644 index 0000000..332de55 --- /dev/null +++ b/CompanywiseSolution/deshaw/question.txt @@ -0,0 +1,28 @@ +Search a number in a sorted rotated array. Basically an array is given +and its is rotated or pivoted from a certain index . Basically we have ro +tell that an element is present or not in that array + +sample input +input line 1- enter the number of elements +input line 2-enter the key needed to find +input line 3- enter all the elements to this + + +output line 1-basically print the index of the element if present +else print a -1 if not present + +example1- +input +9 +10 +5 6 7 8 9 10 1 2 3 + +output-5 + +example-2 +9 +15 +5 6 7 8 9 10 1 2 3 + +output- (-1) + diff --git a/CompanywiseSolution/deshaw/search_in_a_sortedarray.cpp b/CompanywiseSolution/deshaw/search_in_a_sortedarray.cpp new file mode 100644 index 0000000..85ff7c0 --- /dev/null +++ b/CompanywiseSolution/deshaw/search_in_a_sortedarray.cpp @@ -0,0 +1,127 @@ +#include +#include +#include +#include +#include +using namespace std; +#define pb push_back +#define fz(i,a,b) for(ll i=a; i=b; i--) +#define debug(x) cout << #x << " " << x << endl; +typedef long long int ll; +typedef long double lld; + +/*#define debug(x); +printf(x);*/ + +void init() +{ + #ifndef ONLINE_JUDGE + freopen("input.txt" , "r" ,stdin); + freopen("output.txt" , "w" ,stdout); + #endif + +} + +void debugger() +{ + #ifndef ONLINE_JUDGE + freopen("input.txt" , "r" ,stdin); + freopen("output.txt" , "w" ,stdout); + #endif + #ifdef debugger + #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; + #else + #define debugger(x); + #endif +} + + +const int MAXN = (int)((1e5) + 100); +int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);} +int max(int a, int b) {if (a > b) return a; else return b;} +int min(int a, int b) {if (a < b) return a; else return b;} + + +void precision(int a) +{ + cout << setprecision(a) << fixed; +} + + +//** pritishcf307 **// +//**------------------------------------------------------------------------------------------------------**// + + + +int main() +{ + init(); + +ll n; +cin >> n; +ll x; +cin >> x; +bool found=false; +vector v; +for(int i=0;i> a; + v.push_back(a); +} + +ll lo=0; +ll hi=n-1; +ll mid,ans; + +while(hi-lo >= 0) +{ + mid=(lo+hi)/2; + if(v[mid]==x) + { + found=true; + ans=mid; + break; + } + //left part is sorted + else if(v[lo] <= v[mid]) + { + if(x>=v[lo] && x<=v[mid]) + { + hi=mid-1; + } + else + { + lo=mid+1; + } + } + else + { + if(x>=v[mid] && x<=v[hi]) + { + lo=mid+1; + } + else + { + hi=mid-1; + } + } +} + if(found==true) + { + cout << ans << endl; + } + else + { + cout << -1 << endl; + } + return 0; +} + + + + + + + diff --git a/Competitive programming/.DS_Store b/Competitive programming/.DS_Store new file mode 100644 index 0000000..66d2ac5 Binary files /dev/null and b/Competitive programming/.DS_Store differ diff --git a/Competitive programming/C#/FindElementInArray.cs b/Competitive programming/C#/FindElementInArray.cs new file mode 100644 index 0000000..22c874e --- /dev/null +++ b/Competitive programming/C#/FindElementInArray.cs @@ -0,0 +1,31 @@ +# Question is how to find a element in an array + +using System; +using System.Linq; + + +public static class Extensions +{ + public static bool find(this T[] array, T target) { + return array.Contains(target); + } +} + +public class FindElement +{ + public static bool Find(int target, int[] array) + { + bool exists = array.find(target); + return exists; + } + + public static void Test() + { + int[] array = { 1, 2, 3, 4, 5 }; + + if(Find(4, array)) + { + Console.WriteLine("Found Element"); + } + } +} diff --git a/Competitive programming/C++/ADACRA.cpp b/Competitive programming/C++/ADACRA.cpp new file mode 100644 index 0000000..f3d1915 --- /dev/null +++ b/Competitive programming/C++/ADACRA.cpp @@ -0,0 +1,33 @@ +// The problem link is https://www.codechef.com/problems/ADACRA +#include +#include +using namespace std; + +int main() { + int t; + cin >> t; + while(t--){ + int count_u = 0, count_d = 0; + string S; + cin >> S; + for(int i = 1; i < S.length(); i++){ + if(S[i]!=S[i+1]){ + if(S[i]=='U'){ + count_u += 1; + } + else{ + count_d += 1; + } + } + } + if(S[0] == 'U'){ + count_u += 1; + } + else{ + count_d += 1; + } + int ans = min(count_d, count_u); + cout << ans << "\n"; + } + return 0; +} diff --git a/Competitive programming/C++/Arrays_Left_Rotation.cpp b/Competitive programming/C++/Arrays_Left_Rotation.cpp new file mode 100644 index 0000000..2bc0010 --- /dev/null +++ b/Competitive programming/C++/Arrays_Left_Rotation.cpp @@ -0,0 +1,33 @@ +#include +#include + +using namespace std; + +int main() +{ + int n,d,x; + cin>>n>>d; + vector a; + for(int i=0;i>x; + a.push_back(x); + } + + vector b; + // //int n = a.size(); + int k = d%n; + //b[0] = a[k]; + b.push_back(a[k]); + for(int i=k+1;i + +using namespace std; + +int stockBuySell(int arr[],int n) +{ + int max_profit =0; + int minSofar=arr[0]; + for(int i=0;i +using namespace std ; + +#define ff first +#define ss second +#define ull unsigned long long +#define mod 1000000007 +#define inf 1e18 +#define w(x) int x;cin>>x;while(x--) +#define f(x,y) for( x=0;x>a>>b; + s1=ceil((b-(a-1))/2)+ceil(((a-1)-a)/2); + s2=ceil((b-(a+1))/2)+ceil(((a+1)-a)/2); + // cout<<"i is "<b){ + x=s1; + } + else{ + x=s2; + } cout<https://codeforces.com/contest/1560/problem/B +//Who's opposite +#include +using namespace std; +int main(){ + int t; + cin>>t; + while(t--){ + int a,b,c; + cin>>a>>b>>c; + int s=2*(abs(a-b)); + if(a<=s && b<=s && c<=s){ + if((s/2+c)>s){ + cout< +using namespace std; + +int countStepsToOne(int n) +{ + int arr[n+1]; + for(int i = 0; i> n; + cout << countStepsToOne(n); +} \ No newline at end of file diff --git a/Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md b/Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md new file mode 100644 index 0000000..3f5a659 --- /dev/null +++ b/Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md @@ -0,0 +1,30 @@ +Code : Min Steps to 1 using DP + +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: +1.) Subtract 1 from it. (n = n - ­1) , +2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) , +3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ). +Input format : +The first and the only line of input contains an integer value, 'n'. +Output format : +Print the minimum number of steps. +Constraints : +1 <= n <= 10 ^ 6 +Time Limit: 1 sec +Sample Input 1 : +4 +Sample Output 1 : +2 +Explanation of Sample Output 1 : +For n = 4 +Step 1 : n = 4 / 2 = 2 +Step 2 : n = 2 / 2 = 1 +Sample Input 2 : +7 +Sample Output 2 : +3 +Explanation of Sample Output 2 : +For n = 7 +Step 1 : n = 7 ­- 1 = 6 +Step 2 : n = 6 / 3 = 2 +Step 3 : n = 2 / 2 = 1 \ No newline at end of file diff --git a/Competitive programming/C++/FLOW017.cpp b/Competitive programming/C++/FLOW017.cpp new file mode 100644 index 0000000..07cf667 --- /dev/null +++ b/Competitive programming/C++/FLOW017.cpp @@ -0,0 +1,21 @@ +// The problem link is https://www.codechef.com/problems/FLOW017 +#include +using namespace std; + +int main() { + long long int t, a, b, c; + cin >> t; + for(int i = 0; i < t; i++){ + cin >> a >> b >> c; + if(a < max(b,c) && a > min(b,c)){ + cout< min(a,c) && b < max(a,c)){ + cout< +using namespace std; + +int main() { + int n; + long double factorial = 1.0; + + cout << "Enter a positive integer: "; + cin >> n; + + if (n < 0) + cout << "Error! Factorial of a negative number doesn't exist."; + else { + for(int i = 1; i <= n; ++i) { + factorial *= i; + } + cout << "Factorial of " << n << " = " << factorial; + } + + return 0; +} diff --git a/Competitive programming/C++/FakeGCD.cpp b/Competitive programming/C++/FakeGCD.cpp new file mode 100644 index 0000000..f87ec4a --- /dev/null +++ b/Competitive programming/C++/FakeGCD.cpp @@ -0,0 +1,26 @@ +// This is the link to the problem : https://www.codechef.com/COOK133C/problems/FAKEGCD +// Below is my solution +#include +using namespace std; + +int main() { + int t; + cin >> t; + + while(t--) + { + int n; + cin >> n; + + int k=1; + + for(int i=0; i +#include +using namespace std; + +int main() { + int x; + float y,d; + cin>>x; + cin>>y; + d=x+0.50; + if(d>y||x%5!=0) + { + cout< +#include +#include + +using namespace std; + +int isOperand(char x) +{ + if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^' || x == '(' || x == ')') + { + return 0; + } + return 1; +} + +int outPrecedence(char x) +{ + if (x == '+' || x == '-') + { + return 1; + } + else if (x == '*' || x == '/') + { + return 3; + } + else if (x == '^') + { + return 6; + } + else if (x == '(') + { + return 7; + } + else if (x == ')') + { + return 0; + } + return -1; +} + +int inPrecedence(char x) +{ + if (x == '+' || x == '-') + { + return 2; + } + else if (x == '*' || x == '/') + { + return 4; + } + else if (x == '^') + { + return 5; + } + else if (x == '(') + { + return 0; + } + return -1; +} + +char *convert(char *infix) +{ + char *postfix = new char[strlen(infix) + 1]; + + stack stk; + + int i = 0; + int j = 0; + + while (infix[i] != '\0') + { + if (isOperand(infix[i])) + { + postfix[j++] = infix[i++]; + } + else + { + if (stk.empty() || outPrecedence(infix[i]) > inPrecedence(stk.top())) + { + stk.push(infix[i++]); + } + else if (outPrecedence(infix[i]) == inPrecedence(stk.top())) + { + stk.pop(); + } + else + { + postfix[j++] = stk.top(); + stk.pop(); + } + } + } + + while (!stk.empty() && stk.top() != ')') + { + postfix[j++] = stk.top(); + stk.pop(); + } + + postfix[j] = '\0'; + + return postfix; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + char infix[] = "((a+b)*c)-d^e^f"; + + cout << convert(infix) << endl; +} \ No newline at end of file diff --git a/Competitive programming/C++/Kindergarten_Adventures.cpp b/Competitive programming/C++/Kindergarten_Adventures.cpp new file mode 100644 index 0000000..835bd42 --- /dev/null +++ b/Competitive programming/C++/Kindergarten_Adventures.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +int main() { + int N; + cin >> N; + vector A(N); + for(int i = 0; i < N; i++) { + cin >> A[i]; + } + + int start = 0; + + vector D(N+1, 0); + for(int i = 0; i < N; i++) { + if(A[i] <= i) { + start++; + D[i-A[i]]--; + D[i]++; + } else { + D[i-A[i]+N]--; + D[i]++; + } + } + + int best = start; + int bi = 0; + int cur = start; + for(int i = 0; i < N; i++) { + if(cur > best) { + best = cur; + bi = i; + } + cur += D[i]; + } + + cout << (bi+1) << endl; +} \ No newline at end of file diff --git a/Competitive programming/C++/LazySegmentedTree.cpp b/Competitive programming/C++/LazySegmentedTree.cpp new file mode 100644 index 0000000..ca4fab1 --- /dev/null +++ b/Competitive programming/C++/LazySegmentedTree.cpp @@ -0,0 +1,80 @@ +#include + +using namespace std; + +#define inf 1e18 + + +int lazy[10000] = {0}; +void lazyUpdate(int tree[], int s, int e, int l, int r, int val , int index) { + if (lazy[index] != 0) { + tree[index] += lazy[index]; + if (e != s) { + lazy[2 * index] += lazy[index]; + lazy[2 * index + 1] += lazy[index]; + } + lazy[index] = 0; + } + + if (s > r or e < l) return; + + if (s >= l and e <= r) { + tree[index] += val; + if (e != s) { + lazy[2 * index] += val; + lazy[2 * index + 1] += val; + } + return; + } + + int mid = (s + e) / 2; + lazyUpdate(tree, s, mid, l, r, val, 2 * index); + lazyUpdate(tree, mid + 1, e, l, r, val, 2 * index + 1); + tree[index] = min(tree[2 * index], tree[2 * index + 1]); + return; +} + +int lazyQuery(int tree[], int s, int e, int l, int r, int index) { + if (lazy[index] != 0) { + tree[index] += lazy[index]; + if (e != s) { + lazy[2 * index] = lazy[index]; + lazy[2 * index + 1] = lazy[index]; + } + lazy[index] = 0; + } + + if (s > r or e < l) return inf; + if (s >= l and e <= r) return tree[index]; + + int mid = (s + e) / 2; + int left = lazyQuery(tree, s, mid, l, r, 2 * index); + int right = lazyQuery(tree, mid + 1, e, l, r, 2 * index + 1); + return min(left, right); + + +} + +void build(int a[], int tree[], int s, int e, int index) { + if (s == e) { + tree[index] = a[e]; + return; + } + int mid = (s + e) / 2; + build(a, tree, s, mid, 2 * index); + build(a, tree, mid + 1, e, 2 * index + 1); + tree[index] = min(tree[2 * index], tree[2 * index + 1]); + return; +} + + +int32_t main() +{ + //An example of implementing this code + // int a[] = {1, 3, 2, -5, 6, 4}; + // int n = sizeof(a) / sizeof(int); + // int tree[4 * n + 1]; + // build(a, tree, 0, n - 1, 1); + // lazyUpdate(tree, 0, n - 1, 0, 2, 10, 1); + // return 0; +} diff --git a/Competitive programming/C++/MajorityElementInarray b/Competitive programming/C++/MajorityElementInarray new file mode 100644 index 0000000..5465337 --- /dev/null +++ b/Competitive programming/C++/MajorityElementInarray @@ -0,0 +1,33 @@ +#include +using namespace std; + +void findMajority(int arr[], int size) +{ + unordered_map m; + for(int i = 0; i < size; i++) + m[arr[i]]++; + int count = 0; + for(auto i : m) + { + if(i.second > size / 2) + { + count =1; + cout << "Majority found :" << i.first< + +using namespace std; + +int maxSubArraySum(int arr[],int n) +{ + int maxSum =0 ; + int currSum=0; + for(int i=0;imaxSum) + { + maxSum=currSum; + } + if(currSum<0) + { + currSum=0; + } + + } + return maxSum; +} +int main() +{ + int arr[] = {5,-4,-2,6,-1}; + int n = sizeof(arr)/sizeof(arr[0]); + int maxsum = maxSubArraySum(arr, n); + cout << "Maximum subarray sum is " << maxsum; + + return 0; +} diff --git a/Competitive programming/C++/Move all zeroes to end b/Competitive programming/C++/Move all zeroes to end new file mode 100644 index 0000000..a73bda9 --- /dev/null +++ b/Competitive programming/C++/Move all zeroes to end @@ -0,0 +1,31 @@ + +#include +using namespace std; + + +void pushZerosToEnd(int arr[], int n) +{ + int count = 0; // Count of non-zero elements + + + for (int i = 0; i < n; i++) + if (arr[i] != 0) + arr[count++] = arr[i]; // here count is + // incremented + + + while (count < n) + arr[count++] = 0; +} + + +int main() +{ + int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; + int n = sizeof(arr) / sizeof(arr[0]); + pushZerosToEnd(arr, n); + cout << "Array after pushing all zeros to end of array :\n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} diff --git a/Competitive programming/C++/Move the elements.cpp b/Competitive programming/C++/Move the elements.cpp new file mode 100644 index 0000000..800cec0 --- /dev/null +++ b/Competitive programming/C++/Move the elements.cpp @@ -0,0 +1,33 @@ +/* +Sample Input + +10 +-6 7 13 10 -8 15 5 -9 2 -1 +Sample Output + +7 +13 +10 +15 +5 +2 +-6 +-8 +-9 +-1 +*/ + +void moveElements(int arr[], int n){ + int key,j; + for (int i = 0; i < n; i++) + { + key = arr[i]; + j = i-1; + while (j>=0 && arr[j]<0 && key>=0) + { + arr[j+1] = arr[j]; + j--; + } + arr[j+1] = key; + } +} diff --git a/Competitive programming/C++/Permutation Minimization by Deque.c b/Competitive programming/C++/Permutation Minimization by Deque.c new file mode 100644 index 0000000..40e6166 --- /dev/null +++ b/Competitive programming/C++/Permutation Minimization by Deque.c @@ -0,0 +1,50 @@ +//https://codeforces.com/contest/1579/problem/E1 + +#include +using namespace std; +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + deque v; + for(int i=0;i>x; + if(i==0) + v.push_back(x); + + int x1=v[0]; + int x2=v[v.size()-1]; + if(i!=0) + { + if(x==x1) + v.push_front(x); + else if (x==x2) + v.push_back(x); + if(xx2 && x>x1) + v.push_back(x); + else if(x>x1 && xx2 && x +#include +#include + +using namespace std; + +class Node +{ +public: + int data; + Node *next; +}; + +class Stack +{ +private: + Node *top; + +public: + Stack(); + ~Stack(); + void push(int x); + int pop(); + int peek(int index); + int isEmpty(); + int isFull(); + int stackTop(); +}; + +Stack::Stack() +{ + top = nullptr; +} + +Stack::~Stack() +{ + Node *p = top; + while (top) + { + top = top->next; + delete p; + p = top; + } +} + +void Stack::push(int x) +{ + Node *t = new Node; + if (t == nullptr) + { + cout << "Stack Overflow!" << endl; + } + else + { + t->data = x; + t->next = top; + top = t; + } +} + +int Stack::pop() +{ + Node *p; + int x = -1; + if (top == nullptr) + { + cout << "Stack Underflow!" << endl; + } + else + { + p = top; + x = p->data; + top = top->next; + delete p; + } + return x; +} + +int Stack::isFull() +{ + Node *t = new Node; + int r = t ? 1 : 0; + delete t; + return r; +} + +int Stack::isEmpty() +{ + return top ? 0 : 1; +} + +int Stack::stackTop() +{ + if (top) + { + return top->data; + } + return -1; +} + +int Stack::peek(int index) +{ + if (isEmpty()) + { + return -1; + } + else + { + Node *p = top; + + for (int i = 0; p != nullptr && i < index - 1; i++) + { + p = p->next; + } + + if (p != nullptr) + { + return p->data; + } + else + { + return -1; + } + } +} + +int isOperand(char x) +{ + if (x == '+' || x == '-' || x == '*' || x == '/') + { + return 0; + } + return 1; +} + +int operation(char op, int x, int y) +{ + if (op == '+') + { + return x + y; + } + else if (op == '-') + { + return x - y; + } + else if (op == '*') + { + return x * y; + } + else if (op == '/') + { + return x / y; + } +} + +int postfixEvaluate(char *postfix) +{ + stack stk; + int x; + int y; + int result; + for (int i = 0; postfix[i] != '\0'; i++) + { + if (isOperand(postfix[i])) + { + // int typecast would not work because of char so subtract '0' + stk.push(postfix[i] - '0'); + } + else + { + y = stk.top(); + stk.pop(); + x = stk.top(); + stk.pop(); + result = operation(postfix[i], x, y); + stk.push(result); + } + } + result = stk.top(); + stk.pop(); + return result; +} + +int Evaluate(char *postfix) +{ + Stack stk; + int x; + int y; + int result; + for (int i = 0; postfix[i] != '\0'; i++) + { + if (isOperand(postfix[i])) + { + // int typecast would not work because of char so subtract '0' + stk.push(postfix[i] - '0'); + } + else + { + y = stk.pop(); + x = stk.pop(); + result = operation(postfix[i], x, y); + stk.push(result); + } + } + result = stk.pop(); + return result; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + char postfix[] = "234*+82/-"; + cout << Evaluate(postfix) << endl; + cout << postfixEvaluate(postfix) << endl; + + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/Print Subsets of Array.cpp b/Competitive programming/C++/Print Subsets of Array.cpp new file mode 100644 index 0000000..09981d0 --- /dev/null +++ b/Competitive programming/C++/Print Subsets of Array.cpp @@ -0,0 +1,28 @@ +// +#include +using namespace std; +void printSubsetsOfArray(int input[], int size,int output[],int len) { + if(size==0){ + for(int i=0;i> length; + for(int i=0; i < length; i++) + cin >> input[i]; + printSubsetsOfArray(input, length); +} diff --git a/Competitive programming/C++/Print all Codes - String(C++)) b/Competitive programming/C++/Print all Codes - String(C++)) new file mode 100644 index 0000000..1478264 --- /dev/null +++ b/Competitive programming/C++/Print all Codes - String(C++)) @@ -0,0 +1,57 @@ +Question: Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. +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. + +Solution: + +#include +#include + +using namespace std; + +char itoc(int i){ //int to char + char c = 'a'+i-1; + return c; +} +int ctoi(char a){ //char to int + int i = a - '0'; + return i; +} + +void helper(string input,string output){ + if(input.length()==0){ + cout<1){ + + if(ctoi(input[0])*10+ctoi(input[1])>=10 &&ctoi(input[0])*10+ctoi(input[1])<=26){ + char c2 = itoc(ctoi(input[0])*10+ctoi(input[1])); + //output = output+c2; + helper(input.substr(2),output+c2); + //print(output); + } + } + +} +void printAllPossibleCodes(string input) { + /* + Given the input as a string, print all its possible combinations. You do not need to return anything. + */ + string output; + helper(input,output); +} + +int main(){ + string input; + cin >> input; + + printAllPossibleCodes(input); + return 0; +} diff --git a/Competitive programming/C++/Reverse_a_number.cpp b/Competitive programming/C++/Reverse_a_number.cpp new file mode 100644 index 0000000..33c5628 --- /dev/null +++ b/Competitive programming/C++/Reverse_a_number.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main() { + int n, reversedNumber = 0, remainder; + + cout << "Enter an integer: "; + cin >> n; + + while(n != 0) { + remainder = n%10; + reversedNumber = reversedNumber*10 + remainder; + n /= 10; + } + + cout << "Reversed Number = " << reversedNumber; + + return 0; +} diff --git a/Competitive programming/C++/Search an element in sorted and rotated array.cpp b/Competitive programming/C++/Search an element in sorted and rotated array.cpp new file mode 100644 index 0000000..03308a6 --- /dev/null +++ b/Competitive programming/C++/Search an element in sorted and rotated array.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +int Search(vector ,int ); + +int main(){ + + int t; + cin >> t; + + while(t--){ + int n; + cin >> n; + + vector vec(n); + + for(int i =0;i> vec[i]; + + int target; + cin >> target; + + cout << Search(vec,target) << "\n"; + + } +} + + +// vec : given vector of elements +// K : given value whose index we need to find +int Search(vector vec, int k) { + //code here - rahul + int low=0, mid; + int high=vec.size()-1; + while(low<=high) + { + mid=(low+high)/2; + if(vec[mid]==k) + return mid; + if(vec[low]<=vec[mid]) + { + if(k=vec[low]) + { high=mid-1; } + else + { low=mid+1; } + + } + else + { + if(k>vec[mid]&& k<=vec[high]) + { low=mid+1; } + else + { high=mid-1; } + } + + } + return -1; +} diff --git a/Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp b/Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp new file mode 100644 index 0000000..dfca2c6 --- /dev/null +++ b/Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +int main() { + int t,i,j,k;; + cin>>t; + while(t--) + { + int n,c=0; + cin>>n; + int A[n]; + for(i=1;i<=n;i++) + { + cin>>A[i]; + } + for(i=1;i<=n;i++) + { + if(i%2==1) + { + for(j=1;j<=n;j++) + { + if(A[j]>0) + { + if(A[j]%2==0) + { + c++; + A[j]=0; + break; + } + } + } + } + else if(i%2==0) + { + for(j=1;j<=n;j++) + { + if(A[j]>0) + { + if(A[j]%2==1) + { + c++; + A[j]=0; + break; + } + } + } + } + + } + cout< +using namespace std; + +bool subArrayExists(int arr[], int n) +{ + unordered_set sumSet; + + + int sum = 0; + for (int i = 0; i < n; i++) + { + sum += arr[i]; + + + if (sum == 0 + || sumSet.find(sum) + != sumSet.end()) + return true; + + sumSet.insert(sum); + } + return false; +} + +int main() +{ + int arr[] = { -3, 2, -1, -1, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + if (subArrayExists(arr, n)) + cout << "Found a subarray"; + else + cout << "No Such Sub Array "; + return 0; +} diff --git a/Competitive programming/C++/Symmetric_Tree.cpp b/Competitive programming/C++/Symmetric_Tree.cpp new file mode 100644 index 0000000..6f0484a --- /dev/null +++ b/Competitive programming/C++/Symmetric_Tree.cpp @@ -0,0 +1,22 @@ +// Link for Question-->https://leetcode.com/problems/symmetric-tree/ +class Solution { +public: + bool isSymmetric(TreeNode* root) { + return check(root->left,root->right); + } + bool check(TreeNode* r1,TreeNode* r2){ + if(r1==NULL && r2==NULL)// if left and root null + { + return true; + } + else if(r1==NULL || r2==NULL || r1->val!=r2->val) //one is not null + { + return false; + } + else{ + //comparing left subtree's left child with right subtree's + //right child AND comparing left subtree's right child with right subtree's left child + return check(r1->left,r2->right) && check(r1->right,r2->left); + } + } +}; \ No newline at end of file diff --git a/Competitive programming/C++/Tree.cpp b/Competitive programming/C++/Tree.cpp new file mode 100644 index 0000000..cc35fe9 --- /dev/null +++ b/Competitive programming/C++/Tree.cpp @@ -0,0 +1,130 @@ +#include +#include +#include "QueueCpp.h" + using namespace std; +class Tree +{ + Node *root; + +public: + Tree() { root = NULL; } + void CreateTree(); + void Preorder() { Preorder(root); } + void Preorder(Node *p); + void Postorder() { Postorder(root); } + void Postorder(Node *p); + void Inorder() { Inorder(root); } + void Inorder(Node *p); + void Levelorder() { Levelorder(root); } + void Levelorder(Node *p); + int Height() { return Height(root); } + int Height(Node *root); +}; +void Tree::CreateTree() +{ + Node *p, *t; + int x; + Queue q(100); + printf("Enter root value "); + scanf("%d", &x); + root = new Node; + root->data = x; + root->lchild = root->rchild = NULL; + q.enqueue(root); + while (!q.isEmpty()) + { + p = q.dequeue(); + printf("Enter left child of %d ", p->data); + scanf("%d", &x); + if (x != -1) + { + t = new Node; + t->data = x; + t->lchild = t->rchild = NULL; + p->lchild = t; + q.enqueue(t); + } + printf("eneter right child of %d ", p->data); + scanf("%d", &x); + if (x != -1) + { + t = new Node; + t->data = x; + t->lchild = t->rchild = NULL; + p->rchild = t; + q.enqueue(t); + } + } +} +void Tree::Preorder(struct Node *p) +{ + if (p) + { + printf("%d ", p->data); + Preorder(p->lchild); + Preorder(p->rchild); + } +} +void Tree::Inorder(struct Node *p) +{ + if (p) + { + Inorder(p->lchild); + printf("%d ", p->data); + Inorder(p->rchild); + } +} +void Tree::Postorder(struct Node *p) +{ + if (p) + { + Postorder(p->lchild); + Postorder(p->rchild); + printf("%d ", p->data); + } +} +void Tree::Levelorder(struct Node *root) +{ + Queue q(100); + printf("%d ", root->data); + q.enqueue(root); + while (!q.isEmpty(q)) + { + root = q.dequeue(); + if (root->lchild) + { + printf("%d ", root->lchild->data); + q.enqueue(root->lchild); + } + if (root->rchild) + { + printf("%d ", root->rchild->data); + q.enqueue(root->rchild); + } + } +} +int Tree::Height(struct Node *root) +{ + int x = 0, y = 0; + if (root == 0) + return 0; + x = Height(root->lchild); + y = Height(root->rchild); + if (x > y) + return x + 1; + else + return y + 1; +} +int main() +{ + Tree t; + t.CreateTree(); + cout << "Preorder "; + t.Preorder(); + cout << endl; + cout << "Inorder "; + t.Inorder(); + cout << endl + << endl; + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/Trie.cpp b/Competitive programming/C++/Trie.cpp new file mode 100644 index 0000000..23ea24e --- /dev/null +++ b/Competitive programming/C++/Trie.cpp @@ -0,0 +1,67 @@ +#include +using namespace std; + +struct trie{ + struct trie* child[26]; + bool is_end; + trie(){ + memset(child,0,sizeof(child)); + is_end=false; + } +}; + +struct trie* root; +//inserts a word to the trie +void insert(string s){ + struct trie* temp=root; + //traverses over each character + //if the character already exists then it simply iterates over + //otherwise creates a new node and inserts the character + for(char c: s){ + if(!temp->child[c-'a']) + temp->child[c-'a']=new trie; + temp=temp->child[c-'a']; + } + //sets the last letter's boolean value to true + temp->is_end=true; +} +//returns true if the word exists, false otherwise +bool check(string s){ + struct trie* temp=root; + //iterates over the character of the word + for(char c: s){ + //if at any point the char of the word being check is not found it return false + if(!temp->child[c-'a']) + return false; + temp=temp->child[c-'a']; + } + //returns the last letters boolean value + return temp->is_end; +} + +int main(){ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + root=new trie; + int n; + cout << "Input the number of words in the List" << endl; + cin >> n; + string word; + cout<<"Enter the words"<> word ; + insert(word); + } + cout << "Enter the number of words you want to check exist in the List" << endl; + int m; + cin >> m; + //the words to be checked + for(int i=0; i> word ; + if(check(word)) + cout<< "This word exist in the list" < + +using namespace std; + + +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + + + +int main() +{ + int n=0, *a, i,c=0,tsum=0,j,sum=0; + cin>>n; + a=new int[n]; + for(i=0;i>a[i]; + tsum+=a[i]; + } + + insertionSort(a, n); + + for(i=n-1;i>=0;i--) + { + sum=0; + c++; + for(j=n-1;j>=i;j--) + { + sum+=a[j]; + } + if((2*sum)>tsum) + { + cout< +using namespace std; + + + // } Driver Code Ends +class Solution{ + public: + //arr1,arr2 : the arrays + // n, m: size of arrays + //Function to return a list containing the union of the two arrays. + vector findUnion(int arr1[], int arr2[], int n, int m) + { + //Your code here - rahul + //return vector with correct order of elements + vector vec; + int arr3[n+m]; + for(int i=0 ; i> T; + + while(T--){ + + + + int N, M; + cin >>N >> M; + + int arr1[N]; + int arr2[M]; + + for(int i = 0;i> arr1[i]; + } + + for(int i = 0;i> arr2[i]; + } + Solution ob; + vector ans = ob.findUnion(arr1,arr2, N, M); + for(int i: ans)cout< +#include +#include + +using namespace std; + +int main() +{ + long long l, *a, max1=0; + int n,i; + cin>>n>>l; + a=new long long[n]; + for(i=0;i>a[i]; + } + sort(a, a+n); + for(i=0;i +using namespace std; + +struct student +{ + char name[50]; + int roll; + float marks; +}; + +int main() +{ + student s; + cout << "Enter information," << endl; + cout << "Enter name: "; + cin >> s.name; + cout << "Enter roll number: "; + cin >> s.roll; + cout << "Enter marks: "; + cin >> s.marks; + + cout << "\nDisplaying Information," << endl; + cout << "Name: " << s.name << endl; + cout << "Roll: " << s.roll << endl; + cout << "Marks: " << s.marks << endl; + return 0; +} diff --git a/Competitive programming/C++/decimal_to_binary.cpp b/Competitive programming/C++/decimal_to_binary.cpp new file mode 100644 index 0000000..53e7f9d --- /dev/null +++ b/Competitive programming/C++/decimal_to_binary.cpp @@ -0,0 +1,23 @@ +#include +#include + +using namespace std; + +int main() +{ + int n; + cin>>n; + vector v; + int rem; + while(n>0){ + rem=n%2; + v.push_back(rem); + n=n/2; + } + reverse(v.begin(), v.end()); + for(int i=0;i +#include +#include +#include + +using namespace std; + +int isBalanced(char *exp) +{ + + // Create map + map mapping; + mapping['}'] = '{'; + mapping[')'] = '('; + mapping[']'] = '['; + + // Create map iterator + map::iterator itr; + + // Create stack + stack stk; + + for (int i = 0; i < strlen(exp); i++) + { + if (exp[i] == '{' || exp[i] == '[' || exp[i] == '(') + { + stk.push(exp[i]); + } + else if (exp[i] == '}' || exp[i] == ']' || exp[i] == ')') + { + if (stk.empty()) + { + return false; + } + else + { + char temp = stk.top(); + itr = mapping.find(exp[i]); + if (temp == itr->second) + { // itr->first is key, itr->second is value + stk.pop(); + } + else + { + return false; + } + } + } + } + return stk.empty() ? true : false; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + char A[] = "{([a+b]*[c-d*g])/e}"; + cout << isBalanced(A) << endl; + + char B[] = "{([a+b]}*[c-d])/e}"; + cout << isBalanced(B) << endl; + + char C[] = "{([{a+b]*[c-d])/e}"; + cout << isBalanced(C) << endl; + + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/generate_pattern.cpp b/Competitive programming/C++/generate_pattern.cpp new file mode 100644 index 0000000..0d6c9f7 --- /dev/null +++ b/Competitive programming/C++/generate_pattern.cpp @@ -0,0 +1,23 @@ +// C++ code to demonstrate star pattern +#include +using namespace std; + +void pypart(int n) +{ + for (int i = n; i > 0; i--) { + + for (int j = 0; j < i; j++) { + + cout << "* "; + } + + cout << endl; + } +} + +int main() +{ + int n = 5; + pypart(n); + return 0; +} diff --git a/Competitive programming/C++/inverted_pattern.cpp b/Competitive programming/C++/inverted_pattern.cpp new file mode 100644 index 0000000..4accca4 --- /dev/null +++ b/Competitive programming/C++/inverted_pattern.cpp @@ -0,0 +1,23 @@ +// C++ code to demonstrate star pattern +#include +using namespace std; + +void pypart(int n) +{ + for (int i = n; i > 0; i--) { + + for (int j = 0; j < i; j++) { + + cout << "* "; + } + + cout << endl; + } +} + +int main() +{ + int n = 5; + pypart(n); + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/majority_element.cpp b/Competitive programming/C++/majority_element.cpp new file mode 100644 index 0000000..8d2a3c7 --- /dev/null +++ b/Competitive programming/C++/majority_element.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +int main(){ + +int n; +cin>>n; +int arr[n]; +for(int i=0;i>arr[i]; +} +sort(arr,arr+n); +int count; +vector v; +for(int i=0;i +typedef long long int ll; +using namespace std; + +double findMedianSortedArrays(vector& nums1, vector& nums2) { + int n1 = nums1.size(); + int n2 = nums2.size(); + + if (n2 < n1) return findMedianSortedArrays(nums2, nums1); + + int lo = 0; + int hi = n1; + + while (lo<=hi) { + int partitionX = (lo+hi)/2; + int partitionY = (n1+n2+1)/2 - partitionX; + + int maxLeftX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1]; + int minRightX = (partitionX == n1) ? INT_MAX : nums1[partitionX]; + + int maxLeftY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1]; + int minRightY = (partitionY == n2) ? INT_MAX : nums2[partitionY]; + + if (maxLeftX <= minRightY and maxLeftY <= minRightX) { // Correct Partition + if ((n1 + n2) % 2 == 0) // Even + return double(max(maxLeftX, maxLeftY) + min(minRightX, minRightY))/2; + else + return double(max(maxLeftX, maxLeftY)); + } + else if (maxLeftX > minRightY) hi = partitionX - 1; + else lo = partitionX + 1; + } + return -1; +} + +int main() { + + int n1, n2; + cin >> n1 >> n2; + + vector nums1(n1), nums2(n2); + + for (int i = 0; i < n1; i++) { + cin >> nums1[i]; + } + for (int i = 0; i < n2; i++) { + cin >> nums2[i]; + } + + cout << "Median = " << findMedianSortedArrays(nums1, nums2); + + return 0; +} diff --git a/Competitive programming/C++/parenthesismatching.cpp b/Competitive programming/C++/parenthesismatching.cpp new file mode 100644 index 0000000..86cff9f --- /dev/null +++ b/Competitive programming/C++/parenthesismatching.cpp @@ -0,0 +1,164 @@ +#include +#include +using namespace std; + +class Stack +{ +private: + int size; + int top; + char *S; + +public: + Stack(int size); + ~Stack(); + void push(char x); + char pop(); + char peek(int index); + int isFull(); + int isEmpty(); + void display(); + char stackTop(); +}; + +Stack::Stack(int size) +{ + this->size = size; + top = -1; + S = new char[size]; +} + +Stack::~Stack() +{ + delete[] S; +} + +void Stack::push(char x) +{ + if (isFull()) + { + cout << "Stack Overflow!" << endl; + } + else + { + top++; + S[top] = x; + } +} + +char Stack::pop() +{ + char x = 1; + if (isEmpty()) + { + cout << "Stack Underflow!" << endl; + } + else + { + x = S[top]; + top--; + } + return x; +} + +char Stack::peek(int index) +{ + char x = -1; + if (top - index + 1 < 0 || top - index + 1 == size) + { + cout << "Invalid position!" << endl; + } + else + { + x = S[top - index + 1]; + } + return x; +} + +int Stack::isFull() +{ + if (top == size - 1) + { + return 1; + } + return 0; +} + +int Stack::isEmpty() +{ + if (top == -1) + { + return 1; + } + return 0; +} + +void Stack::display() +{ + for (int i = top; i >= 0; i--) + { + cout << S[i] << " | " << flush; + } + cout << endl; +} + +char Stack::stackTop() +{ + if (isEmpty()) + { + return -1; + } + return S[top]; +} + +bool isBalanced(char *exp) +{ + + // Create a stack + Stack stk((int)strlen(exp)); + + // Process expression + for (int i = 0; i < strlen(exp); i++) + { + + // ( found: Push to stack + if (exp[i] == '(') + { + stk.push(exp[i]); + + // ( found + } + else if (exp[i] == ')') + { + + // ) and stack is empty: Unbalanced expression + if (stk.isEmpty()) + { + return false; + + // ) and stack is not empty + } + else + { + stk.pop(); + } + } + } + + // If stack is empty then balanced else unbalanced + return stk.isEmpty() ? true : false; +} + +int main() +{ + + char E[] = "((a+b)*(c-d))"; + cout << isBalanced(E) << endl; + + char F[] = "((a+b)*(c-d)))"; + cout << isBalanced(F) << endl; + + char G[] = "(((a+b)*(c-d))"; + cout << isBalanced(G) << endl; + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/stackLinkedList.cpp b/Competitive programming/C++/stackLinkedList.cpp new file mode 100644 index 0000000..f5a054a --- /dev/null +++ b/Competitive programming/C++/stackLinkedList.cpp @@ -0,0 +1,167 @@ +#include +using namespace std; + +class Node +{ +public: + int data; + Node *next; +}; + +class Stack +{ +private: + Node *top; + +public: + Stack(); + ~Stack(); + void push(int x); + void Display(); + int pop(); + int peek(int index); + int isEmpty(); + int isFull(); + int stackTop(); +}; + +Stack::Stack() +{ + top = nullptr; +} + +Stack::~Stack() +{ + Node *p = top; + while (top) + { + top = top->next; + delete p; + p = top; + } +} + +void Stack::push(int x) +{ + Node *t = new Node; + if (t == nullptr) + { + cout << "Stack Overflow!" << endl; + } + else + { + t->data = x; + t->next = top; + top = t; + } +} + +int Stack::pop() +{ + Node *p; + int x = -1; + if (top == NULL) + { + cout << "Stack Underflow!" << endl; + } + else + { + p = top; + x = p->data; + top = top->next; + delete p; + } + return x; +} + +void Stack::Display() +{ + Node *p = top; + while(p!=NULL) + { + cout<data<<" "; + p=p->next; + } + cout<<"\n"; +} + +int Stack::isFull() +{ + Node *t = new Node; + int r = t ? 1 : 0; + delete t; + return r; +} + +int Stack::isEmpty() +{ + return top ? 0 : 1; +} + +int Stack::stackTop() +{ + if (top) + { + return top->data; + } + return -1; +} + +int Stack::peek(int index) +{ + if (isEmpty()) + { + return -1; + } + else + { + Node *p = top; + + for (int i = 0; p != nullptr && i < index - 1; i++) + { + p = p->next; + } + + if (p != nullptr) + { + return p->data; + } + else + { + return -1; + } + } +} + +int main() +{ + + int A[] = {1, 3, 5, 7, 9}; + + Stack stk; + + // Populate stack + for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) + { + stk.push(A[i]); + } + + cout << "Stack peek at 3rd: " << stk.peek(3) << endl; + cout << "Stack peek at 10th: " << stk.peek(10) << endl; + cout << "Stack top: " << stk.stackTop() << endl; + cout << "Stack full: " << stk.isFull() << endl; + cout << "Stack empty: " << stk.isEmpty() << endl; + + // Pop out elements from stack + cout << "Popped: " << flush; + for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) + { + cout << stk.pop() << ", " << flush; + } + cout << endl; + + // Underflow + cout << stk.pop() << endl; + + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/triplet sum to a given value b/Competitive programming/C++/triplet sum to a given value new file mode 100644 index 0000000..82fee8f --- /dev/null +++ b/Competitive programming/C++/triplet sum to a given value @@ -0,0 +1,41 @@ + +#include +using namespace std; + + +bool find3Numbers(int A[], int arr_size, int sum) +{ + + for (int i = 0; i < arr_size - 2; i++) + { + + + unordered_set s; + int curr_sum = sum - A[i]; + for (int j = i + 1; j < arr_size; j++) + { + if (s.find(curr_sum - A[j]) != s.end()) + { + printf("Triplet is %d, %d, %d", A[i], + A[j], curr_sum - A[j]); + return true; + } + s.insert(A[j]); + } + } + + + return false; +} + + +int main() +{ + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = sizeof(A) / sizeof(A[0]); + + find3Numbers(A, arr_size, sum); + + return 0; +} diff --git a/Competitive programming/C/ArmstrongNumber.c b/Competitive programming/C/ArmstrongNumber.c new file mode 100644 index 0000000..a3c2d76 --- /dev/null +++ b/Competitive programming/C/ArmstrongNumber.c @@ -0,0 +1,19 @@ +#include + int main() +{ +int n,r,sum=0,temp; +printf("enter the number="); +scanf("%d",&n); +temp=n; +while(n>0) +{ +r=n%10; +sum=sum+(r*r*r); +n=n/10; +} +if(temp==sum) +printf("armstrong number "); +else +printf("not armstrong number"); +return 0; +} diff --git a/Competitive programming/C/Find Remainder.c b/Competitive programming/C/Find Remainder.c new file mode 100644 index 0000000..204009b --- /dev/null +++ b/Competitive programming/C/Find Remainder.c @@ -0,0 +1,18 @@ +#include + +int main() +{ + int T; + scanf("%d", &T); + while (T--) + { + + int a, b; + scanf("%d %d", &a, &b); + + int ans =a%b ; + printf("%d\n", ans); + } + + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C/Matrix multiplication.c b/Competitive programming/C/Matrix multiplication.c new file mode 100644 index 0000000..239b28a --- /dev/null +++ b/Competitive programming/C/Matrix multiplication.c @@ -0,0 +1,60 @@ +#include + +void merge(int Array[],int iterator1,int j1,int iterator2,int j2) +{ + int TemporaryArray[50]; //array used for merging + int i,j,k; + i=iterator1; //beginning of the first list + j=iterator2; //beginning of the second list + k=0; + + while(i<=j1 && j<=j2) //while elements in both lists + { + if(Array[i] + +void merge(int Array[],int iterator1,int j1,int iterator2,int j2) +{ + int TemporaryArray[50]; //array used for merging + int i,j,k; + i=iterator1; //beginning of the first list + j=iterator2; //beginning of the second list + k=0; + + while(i<=j1 && j<=j2) //while elements in both lists + { + if(Array[i] +#define SIZE 6 + +void enQueue(int); +void deQueue(); +void display(); + +int items[SIZE], front = -1, rear = -1; + +int main() { + //deQueue is not possible on empty queue + deQueue(); + + //enQueue 5 elements + enQueue(1); + enQueue(2); + enQueue(3); + enQueue(4); + enQueue(5); + enQueue(6); + + // 7th element can't be added to because the queue is full + enQueue(7); + enQueue(8); + + display(); + + //deQueue removes element entered first i.e. 1 + deQueue(); + + //Now we have just 5 elements + display(); + + return 0; +} + +void enQueue(int value) { + if (rear == SIZE - 1) + printf("\nQueue is Full!!"); + else { + if (front == -1) + front = 0; + rear++; + items[rear] = value; + printf("\nInserted -> %d", value); + } +} + +void deQueue() { + if (front == -1) + printf("\nQueue is Empty!!"); + else { + printf("\nDeleted : %d", items[front]); + front++; + if (front > rear) + front = rear = -1; + } +} + +void display() { + if (rear == -1) + printf("\nQueue is Empty!!!"); + else { + int i; + printf("\nQueue elements are:\n"); + for (i = front; i <= rear; i++) + printf("%d ", items[i]); + } + printf("\n"); +} \ No newline at end of file diff --git a/Competitive programming/C/Reflection.c b/Competitive programming/C/Reflection.c new file mode 100644 index 0000000..d511b06 --- /dev/null +++ b/Competitive programming/C/Reflection.c @@ -0,0 +1,93 @@ +#include +#include +#include +#include +void main() +{ +int poly[30],a[9][3],b[3][3],c[9][3],poly2[30]; +int x,y,p,i,j,k,xc,yc; +int gd=DETECT,gm; +clrscr(); +initgraph(&gd,&gm,"c:\\turboc3\\bgi"); +xc=getmaxx()/2; +yc=getmaxy()/2; +printf("\n Enter number of points : "); +scanf("%d",&p); +j=0; +for(i=0;i=max) + { + printf("Not Possible"); + return 0; + } + for(i=0; i=a) + { + printf("yes, its possible"); + return 0; + } + printf("%d",n[loc]); +} + +----------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +/* + +Output :- + +Enter how many numbers:- +5 +Enter integers:- +4 +Enter integers:- +9 +Enter integers:- +7 +Enter integers:- +15 +Enter integers:- +22 +Enter the location:- +2 +7 + +*/ diff --git a/Competitive programming/C/Stacks.c b/Competitive programming/C/Stacks.c new file mode 100644 index 0000000..eb95685 --- /dev/null +++ b/Competitive programming/C/Stacks.c @@ -0,0 +1,87 @@ +#include +#include + +#define MAX 10 + +int count = 0; + +// Creating a stack +struct stack { + int items[MAX]; + int top; +}; +typedef struct stack st; + +void createEmptyStack(st* s) { + s->top = -1; +} + +// Check if the stack is full +int isfull(st* s) { + if (s->top == MAX - 1) + return 1; + else + return 0; +} + +// Check if the stack is empty +int isempty(st* s) { + if (s->top == -1) + return 1; + else + return 0; +} + +// adding elements in the stack +void push(st* s, int newitem) { + if (isfull(s)) { + printf("STACK FULL"); + } + else { + s->top++; + s->items[s->top] = newitem; + } + count++; +} + +// Remove element from stack +void pop(st* s) { + if (isempty(s)) { + printf("\n STACK EMPTY \n"); + } + else { + printf("Item popped= %d", s->items[s->top]); + s->top--; + } + count--; + printf("\n"); +} + +// Print elements of stack +void printStack(st* s) { + printf("Stack: "); + for (int i = 0; i < count; i++) { + printf("%d ", s->items[i]); + } + printf("\n"); +} + +int main() { + int ch; + st* s = (st*)malloc(sizeof(st)); + + createEmptyStack(s); + + push(s, 1); + push(s, 2); + push(s, 3); + push(s, 4); + push(s, 5); + + printStack(s); + + pop(s); + + printf("\nAfter popping out top element\n"); + printStack(s); +} diff --git a/Competitive programming/C/matrix-addition.c b/Competitive programming/C/matrix-addition.c new file mode 100644 index 0000000..6d3b748 --- /dev/null +++ b/Competitive programming/C/matrix-addition.c @@ -0,0 +1,40 @@ +#include +int main() { + int r, c, a[100][100], b[100][100], sum[100][100], i, j; + printf("Enter the number of rows (between 1 and 100): "); + scanf("%d", &r); + printf("Enter the number of columns (between 1 and 100): "); + scanf("%d", &c); + + printf("\nEnter elements of 1st matrix:\n"); + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + printf("Enter element a%d%d: ", i + 1, j + 1); + scanf("%d", &a[i][j]); + } + + printf("Enter elements of 2nd matrix:\n"); + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + printf("Enter element b%d%d: ", i + 1, j + 1); + scanf("%d", &b[i][j]); + } + + + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + sum[i][j] = a[i][j] + b[i][j]; + } + + + printf("\nSum of two matrices: \n"); + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + printf("%d ", sum[i][j]); + if (j == c - 1) { + printf("\n\n"); + } + } + + return 0; +} diff --git a/Competitive programming/JAVA/0001spiral_traversal_2d.java b/Competitive programming/JAVA/0001spiral_traversal_2d.java new file mode 100644 index 0000000..2c20bb7 --- /dev/null +++ b/Competitive programming/JAVA/0001spiral_traversal_2d.java @@ -0,0 +1,55 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class SpiralTraversalOf2DArray { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("Enter number of rows"); + int row = scanner.nextInt(); + System.out.println("Enter number of column"); + int column = scanner.nextInt(); + int[][] matrix = new int[row][column]; + System.out.println("Enter the elements of 2X2 matrix"); + for (int i = 0; i < row; i++) { + System.out.println("Enter "+ column +" elements for " + i +" row"); + for (int j = 0; j < column; j++) { + matrix[i][j] = scanner.nextInt(); + } + } + List traversalList = spiralTraversal(matrix); + printTraversal(traversalList); + } + public static List spiralTraversal(int matrix[][]){ + List ans = new ArrayList(); + if(matrix.length == 0){ + return ans; + } + int row = matrix.length, column = matrix[0].length; + boolean[][] seen = new boolean[row][column]; + int[] dr = {0, 1, 0, -1}; + int[] dc = {1, 0, -1, 0}; + int r=0, c=0, di=0, cr=0, cc=0; + for (int i = 0; i < row * column; i++) { + ans.add(matrix[r][c]); + seen[r][c] = true; + cr = r + dr[di]; + cc = c + dc[di]; + if(0<=cr && cr list){ + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i)+ ((i1<=>2 +Example 2: +--------- +Input: + 10 + / \ + 20 30 + / \ + 40 60 +Output: +40 20 60 10 30 +30 10 60 20 40 +Explanation: DLL would be 40<=>20<=>60<=>10<=>30. +Your Task: You don't have to take input. Complete the function bToDLL() that takes root node of the tree as a parameter +and returns the head of DLL . The driver code prints the DLL both ways. +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(H). +Note: H is the height of the tree and this space is used implicitly for recursion stack. +*/ + +// Link --> https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1 + +// Code: +class Solution +{ + Node head; + Node bToDLL(Node root) + { + if(root == null) + return null; + + bToDLL(root.right); + root.right = head; + + if(head != null) + head.left = root; + + head = root; + bToDLL(root.left); + + return head; + } +} \ No newline at end of file diff --git a/Competitive programming/JAVA/Counting Sort.java b/Competitive programming/JAVA/Counting Sort.java new file mode 100644 index 0000000..8a0f512 --- /dev/null +++ b/Competitive programming/JAVA/Counting Sort.java @@ -0,0 +1,43 @@ + +class CountingSort { + void sort(char arr[]) + { + int n = arr.length; + + + char output[] = new char[n]; + + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + + for (int i = 0; i < n; ++i) + ++count[arr[i]]; + + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + + for (int i = n - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'D','E','M','O','I','C','N'}; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} + diff --git a/Competitive programming/JAVA/Longest_Harmonious_Subsequence.java b/Competitive programming/JAVA/Longest_Harmonious_Subsequence.java new file mode 100644 index 0000000..776c3b4 --- /dev/null +++ b/Competitive programming/JAVA/Longest_Harmonious_Subsequence.java @@ -0,0 +1,45 @@ + +/* +leetcode-Longest Harmonious Subsequence +Problem Statement: +----------------- +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. +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. + +Example 1: +Input: nums = [1,3,2,2,5,2,3,7] +Output: 5 +Explanation: The longest harmonious subsequence is [3,2,2,2,3]. + +Example 2: +Input: nums = [1,2,3,4] +Output: 2 +*/ +// Link -->https://leetcode.com/problems/longest-harmonious-subsequence/ + + + + + +// Code: + +class Solution { + public int findLHS(int[] nums) { + int rst = 0; + Map map = new HashMap<>(); + + // put the number and its occurence in the map + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + + // Traverse the map to get the longest harmonious subsequence + for (int key : map.keySet()) { + if (map.containsKey(key + 1)) { + rst = Math.max(rst, map.get(key) + map.get(key + 1)); + } + } + return rst; + } +} + diff --git a/Competitive programming/JAVA/MergeSort.java b/Competitive programming/JAVA/MergeSort.java new file mode 100644 index 0000000..2586db6 --- /dev/null +++ b/Competitive programming/JAVA/MergeSort.java @@ -0,0 +1,104 @@ +/* Java program for Merge Sort */ +class MergeSort +{ + // Merges two subarrays of arr[]. + // First subarray is arr[l..m] + // Second subarray is arr[m+1..r] + void merge(int arr[], int l, int m, int r) + { + // Find sizes of two subarrays to be merged + int n1 = m - l + 1; + int n2 = r - m; + + /* Create temp arrays */ + int L[] = new int [n1]; + int R[] = new int [n2]; + + /*Copy data to temp arrays*/ + for (int i=0; i (rItem).priority) { + newNode.next = null; + (rItem).next = newNode; + newNode.prev = (rItem).next; + rItem = newNode; + } // Handle other cases + else { + + // Find position where we need to + // insert. + Node start = (fItem).next; + while (start.priority > p) { + start = start.next; + } + (start.prev).next = newNode; + newNode.next = start.prev; + newNode.prev = (start.prev).next; + start.prev = newNode.next; + } + } + head = fItem; + rear = rItem; + } + + // Return the value at rear + static int peek(Node fItem) { + return fItem.data; + } + + static boolean isEmpty(Node fItem) { + return (fItem == null); + } + + // Removes the element with the + // least priority value form the list + static int pop(Node fItem, Node rItem) { + Node temp = fItem; + int res = temp.data; + (fItem) = (fItem).next; + if (fItem == null) { + fItem = null; + } + + head = fItem; + rear = rItem; + return res; + } +} diff --git a/Competitive programming/JAVA/Recursive_Bubble_Sort.java b/Competitive programming/JAVA/Recursive_Bubble_Sort.java new file mode 100644 index 0000000..d6e0d9b --- /dev/null +++ b/Competitive programming/JAVA/Recursive_Bubble_Sort.java @@ -0,0 +1,35 @@ + + +import java.util.Arrays; + +public class DEMONIC +{ + + static void bubbleSort(int arr[], int n) + { + if (n == 1) + return; + + for (int i=0; i arr[i+1]) + { + + int temp = arr[i]; + arr[i] = arr[i+1]; + arr[i+1] = temp; + } + + bubbleSort(arr, n-1); + } + + + public static void main(String[] args) + { + int arr[] = {64, 34, 25, 12, 22, 11, 90}; + + bubbleSort(arr, arr.length); + + System.out.println("Sorted array : "); + System.out.println(Arrays.toString(arr)); + } +} diff --git a/Competitive programming/JAVA/Split_Array_Largest_Sum.java b/Competitive programming/JAVA/Split_Array_Largest_Sum.java new file mode 100644 index 0000000..ce95148 --- /dev/null +++ b/Competitive programming/JAVA/Split_Array_Largest_Sum.java @@ -0,0 +1,38 @@ +//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. +//Write an algorithm to minimize the largest sum among these m subarrays. + + +//Solution :- +class Solution { + public int splitArray(int[] nums, int m) { + // Max ans = split 1 + //Min ans = split to the length + int start =0; + int end =0; + for(int i =0;imid){ + sum= num; + pices++; + } + else{ + sum+=num; + } + } + if(pices>m){ + start=mid+1; + }else + end= mid; + } + return end; + } +} diff --git a/Competitive programming/JAVA/longest_rep_sub_sequence.java b/Competitive programming/JAVA/longest_rep_sub_sequence.java new file mode 100644 index 0000000..83b5b71 --- /dev/null +++ b/Competitive programming/JAVA/longest_rep_sub_sequence.java @@ -0,0 +1,23 @@ +import java.io.*; +import java.util.*; + +class Main { + static int LongestRepSubSeq(String str) { + int n = str.length(); + int[][] dp = new int[n + 1][n + 1]; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + if (str.charAt(i - 1) == str.charAt(j - 1) && i != j) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); + } + } + return dp[n][n]; + } + + public static void main(String[] args) { + String str = "HHHHHHaaaacccckTTToberFFFeest"; + System.out.println("The length of the largest subsequence that repeats itself is : " + LongestRepSubSeq(str)); + } +} diff --git a/Competitive programming/PYTHON/.DS_Store b/Competitive programming/PYTHON/.DS_Store new file mode 100644 index 0000000..02188fd Binary files /dev/null and b/Competitive programming/PYTHON/.DS_Store differ diff --git a/Competitive programming/PYTHON/FAKESWAP.py b/Competitive programming/PYTHON/FAKESWAP.py new file mode 100644 index 0000000..7ef2527 --- /dev/null +++ b/Competitive programming/PYTHON/FAKESWAP.py @@ -0,0 +1,19 @@ +# The link to the problem is : https://www.codechef.com/COOK133C/problems/FAKESWAP +# Below is my solution +for i in range(int(input())): + a=int(input()) + b=input() + c=input() + d=e=0 + if b==c: + print("YES") + else: + for i in range(a): + if c[i]=='1': + d+=1 + else: + e+=1 + if d>0 and e>0: + print("YES") + else: + print("NO") diff --git a/Competitive programming/PYTHON/Fibonacci.py b/Competitive programming/PYTHON/Fibonacci.py new file mode 100644 index 0000000..3827c59 --- /dev/null +++ b/Competitive programming/PYTHON/Fibonacci.py @@ -0,0 +1,30 @@ +# -- Case-1 -->> Using Function +# This is a program to find fibonacci series using simple function +def fib(n): + if n < 1: # Fibonacci is not defined for negative numbers + return None + if n < 3: # The first two elements of fibonacci are 1 + return 1 + elem1 = elem2 = 1 + sum = 0 + for i in range(3, n+1): + sum = elem1+elem2 + elem1, elem2 = elem2, sum + # First element becomes becomes second element + # Second element becomes the sum of previous two elements + + return sum + + +#--Main--# +for i in range(1, 10): + print(i, " -->> ", fib(i)) + + +# -- Case-2 -->> Using Recursive Function +def fib_rec(n): + if n < 0: + return None + if n < 3: + return 1 + return fib(n-1)+fib(n-2) diff --git a/Competitive programming/PYTHON/Find an Element in an array.py b/Competitive programming/PYTHON/Find an Element in an array.py new file mode 100644 index 0000000..5d2a2d1 --- /dev/null +++ b/Competitive programming/PYTHON/Find an Element in an array.py @@ -0,0 +1,5 @@ +# Question is how to find a element in an array + +from array import* +my_array = array('i',[10001,1001,1122,15423]) +print(my_array.index(1122) diff --git a/Competitive programming/PYTHON/Frequent_WORD.py b/Competitive programming/PYTHON/Frequent_WORD.py new file mode 100644 index 0000000..3393bd0 --- /dev/null +++ b/Competitive programming/PYTHON/Frequent_WORD.py @@ -0,0 +1,40 @@ +# # Here we will find the maximum frequent word in the dataset +# # We will use the concept of dictionary. +# inp = list(input("Enter").split()) +# d = {} +# for x in inp: +# d[x] = 0 +# for x in inp: +# d[x] = d[x]+1 + +# max = 0 +# ans = '' +# for x in inp: +# if(d[x] > max): +# max = d[x] +# ans = x +# print(d) +# print(max) +# print("Max Repeating word = ", ans.upper()) +def f(str): + new = {} + freq = {} + str = list(str.lower().split(' ')) + for i in str: + if i not in new: + new[i] = 0 + new[i] += 1 + else: + new[i] += 1 + for i in sorted(list(new.values())): + freq[i] = [] + for x in freq: + for word in new: + if new[word] == x: + freq[x] += [word] + print(str, end='\n\n\n') + print(new) + print(freq) + + +f('My name is Lalit Kumar. My house is in #### %4^ 8') diff --git a/Competitive programming/PYTHON/N_Queen.py b/Competitive programming/PYTHON/N_Queen.py new file mode 100644 index 0000000..9f8381d --- /dev/null +++ b/Competitive programming/PYTHON/N_Queen.py @@ -0,0 +1,34 @@ +count = 0 + + +def solution(n): + board = [0] + visited = [False] * (n + 1) + queen(n, board, visited) + print(count) + + +def check(board, x): + for i in range(1, len(board)): + if abs(i - len(board)) == abs(board[i] - x): + return False + return True + + +def queen(n, board, visited): + global count + if len(board) == n + 1: + count += 1 + else: + for i in range(1, n + 1): + if not visited[i]: + if not check(board, i): + continue + board.append(i) + visited[i] = True + queen(n, board, visited) + visited[i] = False + board.pop() + +printf("how many?") +solution(int(input())) diff --git a/Competitive programming/PYTHON/SUDOKU.py b/Competitive programming/PYTHON/SUDOKU.py new file mode 100644 index 0000000..e578423 --- /dev/null +++ b/Competitive programming/PYTHON/SUDOKU.py @@ -0,0 +1,52 @@ +# A function that checks whether a list passed as an argument contains +# nine digits from '1' to '9'. +def checkset(digs): + return sorted(list(digs)) == [chr(x + ord('0')) for x in range(1, 10)] + + +# A list of rows representing the sudoku. +rows = [ ] +for r in range(9): + ok = False + while not ok: + row = input("Enter row #" + str(r + 1) + ": ") + ok = len(row) == 9 or row.isdigit() + if not ok: + print("Incorrect row data - 9 digits required") + rows.append(row) + +ok = True + +# Check if all rows are good. +for r in range(9): + if not checkset(rows[r]): + ok = False + break + +# Check if all columns are good. +if ok: + for c in range(9): + col = [] + for r in range(9): + col.append(rows[r][c]) + if not checkset(col): + ok = False + break + +# Check if all sub-squares (3x3) are good. +if ok: + for r in range(0, 9, 3): + for c in range(0, 9, 3): + sqr = '' + # Make a string containing all digits from a sub-square. + for i in range(3): + sqr += rows[r+i][c:c+3] + if not checkset(list(sqr)): + ok = False + break + +# Print the final verdict. +if ok: + print("Yes") +else: + print("No") diff --git a/Competitive programming/PYTHON/Special Numbers/Auto_Bio.py b/Competitive programming/PYTHON/Special Numbers/Auto_Bio.py new file mode 100644 index 0000000..d4601f2 --- /dev/null +++ b/Competitive programming/PYTHON/Special Numbers/Auto_Bio.py @@ -0,0 +1,60 @@ +# Autobiographical numbers within range 0 to N +#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. +#For example, 1210 has 1 zero, 2 ones, 1 two and 0 threes. + +from math import pow + +def isAutoBio(N): + +#Converting number to string for simpler execution + Str = str(N) + + for i in range(0, len(Str)): + +#Extracting character at each index and converting back to integer + index = int(Str[i]) + + c = 0 #counter variable for counting 0's,1's, and so on + + for j in range(0, len(Str)): + + num = int(Str[j]) + + # Check if equal to the index, if true then increment count + if num == i: + + #An Autobiographical number + c += 1 + + # Return false if counter and index not equal + if c != index: + + return False + + return True + +# Function to print autobiographical number + +def findAutoBios(n): + + + flag= 0 + + #print("********AUTOBIOGRAPHICAL NUMBERS IN THIS RANGE 0 TO ",n) + + for i in range(0,n+1): + + #Passing every number from 0 to n+1 to check for Autobiographical number + + if isAutoBio(i): + flag = 1 + print i,"is an autobiographical number\n" + + +# Driver Code + +if __name__ == "__main__": + + N = input("Please enter the max range\n") + + findAutoBios(N) \ No newline at end of file diff --git a/Competitive programming/PYTHON/Tic-Tac-Toe.py b/Competitive programming/PYTHON/Tic-Tac-Toe.py new file mode 100644 index 0000000..37f46f4 --- /dev/null +++ b/Competitive programming/PYTHON/Tic-Tac-Toe.py @@ -0,0 +1,138 @@ +''' +Your task is to write a simple program which pretends to play tic-tac-toe with the user. +To make it all easier for you, we've decided to simplify the game. Here are our assumptions: +-->>The computer (i.e., your program) should play the game using 'X's; +-->>The user (e.g., you) should play the game using 'O's; +-->>The first move belongs to the computer - it always puts its first 'X' in the middle of the board; +-->>All the squares are numbered row by row starting with 1 (see the example session below for reference) +-->>The user inputs their move by entering the number of the square they choose - the number must be valid, + i.e., it must be an integer, it must be greater than 0 and less than 10, and it cannot point to a field which is already occupied; +-->>The program checks if the game is over - there are four possible verdicts: + the game should continue, or the game ends with a tie, your win, or the computer's win; +-->>The computer responds with its move and the check is repeated; +-->>Don't implement any form of artificial intelligence - a random field choice made by the computer is good enough for the game. +''' +# def display_board(board): +# # The function accepts one parameter containing the board's current status +# # and prints it out to the console. + + +# def enter_move(board): +# # The function accepts the board current status, asks the user about their move, +# # checks the input and updates the board according to the user's decision. + + +# def make_list_of_free_fields(board): +# # The function browses the board and builds a list of all the free squares; +# # the list consists of tuples, while each tuple is a pair of row and column numbers. + + +# def victory_for(board, sign): +# # The function analyzes the board status in order to check if +# # the player using 'O's or 'X's has won the game + + +# def draw_move(board): +# The function draws the computer's move and updates the board. + +from random import randrange + + +def display_board(board): + print("+-------" * 3, "+", sep="") + for row in range(3): + print("| " * 3, "|", sep="") + for col in range(3): + print("| " + str(board[row][col]) + " ", end="") + print("|") + print("| " * 3, "|", sep="") + print("+-------" * 3, "+", sep="") + + +def enter_move(board): + ok = False # fake assumption - we need it to enter the loop + while not ok: + move = input("Enter your move: ") + # is user's input valid? + ok = len(move) == 1 and move >= '1' and move <= '9' + if not ok: + # no, it isn't - do the input again + print("Bad move - repeat your input!") + continue + move = int(move) - 1 # cell's number from 0 to 8 + row = move // 3 # cell's row + col = move % 3 # cell's column + sign = board[row][col] # check the selected square + ok = sign not in ['O', 'X'] + if not ok: # it's occupied - to the input again + print("Field already occupied - repeat your input!") + continue + board[row][col] = 'O' # set '0' at the selected square + + +def make_list_of_free_fields(board): + free = [] # the list is empty initially + for row in range(3): # iterate through rows + for col in range(3): # iterate through columns + if board[row][col] not in ['O', 'X']: # is the cell free? + # yes, it is - append new tuple to the list + free.append((row, col)) + return free + + +def victory_for(board, sgn): + if sgn == "X": # are we looking for X? + who = 'me' # yes - it's computer's side + elif sgn == "O": # ... or for O? + who = 'you' # yes - it's our side + else: + who = None # we should not fall here! + cross1 = cross2 = True # for diagonals + for rc in range(3): + if board[rc][0] == sgn and board[rc][1] == sgn and board[rc][2] == sgn: # check row rc + return who + if board[0][rc] == sgn and board[1][rc] == sgn and board[2][rc] == sgn: # check column rc + return who + if board[rc][rc] != sgn: # check 1st diagonal + cross1 = False + if board[2 - rc][2 - rc] != sgn: # check 2nd diagonal + cross2 = False + if cross1 or cross2: + return who + return None + + +def draw_move(board): + free = make_list_of_free_fields(board) # make a list of free fields + cnt = len(free) + if cnt > 0: # if the list is not empty, choose a place for 'X' and set it + this = randrange(cnt) + row, col = free[this] + board[row][col] = 'X' + + +board = [[3 * j + i + 1 for i in range(3)] + for j in range(3)] # make an empty board +board[1][1] = 'X' # set first 'X' in the middle +free = make_list_of_free_fields(board) +human_turn = True # which turn is it now? +while len(free): + display_board(board) + if human_turn: + enter_move(board) + victor = victory_for(board, 'O') + else: + draw_move(board) + victor = victory_for(board, 'X') + if victor != None: + break + human_turn = not human_turn + free = make_list_of_free_fields(board) + +display_board(board) +if victor == 'you': + print("You won!") +elif victor == 'me': + print("I won") +else: + print("Tie!") diff --git a/Competitive programming/PYTHON/knight_moves.py b/Competitive programming/PYTHON/knight_moves.py new file mode 100644 index 0000000..e8cb8a1 --- /dev/null +++ b/Competitive programming/PYTHON/knight_moves.py @@ -0,0 +1,38 @@ + + +# input +#The input begins with the number n of scenarios on a single line by itself. +# 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 +# output +# 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. +import sys +from collections import deque + + +def solution(): + move = [[2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2], [1, -2], [2, -1]] + IC = int(sys.stdin.readline()) + for _ in range(IC): + row = int(sys.stdin.readline()) + arr = [[0 for _ in range(row)] for _ in range(row)] + sy, sx = list(map(int, sys.stdin.readline().split())) + dy, dx = list(map(int, sys.stdin.readline().split())) + queue = deque() + queue.append((sy, sx)) + while queue: + cy, cx = queue.popleft() + if dx == cx and dy == cy: + print(arr[dy][dx]) + break + for i in range(8): + my = cy + move[i][0] + mx = cx + move[i][1] + if not (0 <= my and 0 <= mx and my < row and mx < row): + continue + if arr[my][mx]: + continue + arr[my][mx] = arr[cy][cx] + 1 + queue.append((my, mx)) + + +solution() diff --git a/Competitive programming/PYTHON/maxprofit.py b/Competitive programming/PYTHON/maxprofit.py new file mode 100644 index 0000000..d85c6e0 --- /dev/null +++ b/Competitive programming/PYTHON/maxprofit.py @@ -0,0 +1,35 @@ +liStocks = [100, 180, 260, 310, 40, 535, 695] + +#find local minima +def findMin(liStocks): + for i, val in enumerate(liStocks[:-1]): + if val < liStocks[i+1]: + return i, val + return -1, -1 + +#find local maxima +def findMax(liStocks): + for i, val in enumerate(liStocks[:-1]): + if val > liStocks[i+1]: + return i, val + return i+1, liStocks[-1] + + + +def buySellStock(): + index=0 + while index < len(liStocks): + i, val = findMin(liStocks[index:]) + if i > -1: + index=i+index + print("bye stock on day ", index+1, val) + else: + break + + i, val = findMax(liStocks[index:]) + index=i+index + print("sell stock on day ", index+1, val) + + +if __name__ == "__main__": + buySellStock() diff --git a/README.md b/README.md index ebc9e1b..11a9f86 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ + # hacktoberfest2021_CP +![image](https://user-images.githubusercontent.com/56961626/135728682-586fe6e3-7fe0-4ae7-b4df-6d5278f53688.png) + You can contribute here! ## Basics of Git and GitHub