├── 800 Codeforces Solutions ├── 110A_Nearly_Lucky_Number.cpp ├── 112A_Petya_and_Strings.cpp ├── 116A_Tram.cpp ├── 136A_Presents.cpp ├── 144A_Arrival_of_the_General.cpp ├── 148A_Insomnia_Cure.cpp ├── 158A_Next_Round.cpp ├── 1624A_Plus_One_On_The_Subset.cpp ├── 200B_Drinks.cpp ├── 228A_Is_your_horseshoe_on_the_other_hoof.cpp ├── 231A_Team.cpp ├── 236A_Boy_or_Girl.cpp ├── 262A_Roma_LuckyNumbers.cpp ├── 262B_Roma_and_Changing_Signs.cpp ├── 263A_Beautiful_Matrix.cpp ├── 266A_Stones_on_the_Table.cpp ├── 266B_Queue_at_the_School.cpp ├── 268A_Games.cpp ├── 271A_Beautiful_Year.cpp ├── 281A_Word_Capitalization.cpp ├── 41A_Translation.cpp ├── 4A_Watermelon.cpp ├── 50A_Domino_Piling.cpp ├── 59A_Word.cpp ├── 61A_Ultra_Fast_Mathematician.cpp ├── 71A_Way_Too_Long_Words.cpp ├── 749A_Bachgold_Problem.cpp └── 796A. Cirno's Perfect Bitmasks Classroom.cpp ├── Algorithm ├── BellmanFord.cpp ├── Heapsort.cpp ├── KMP.cpp ├── Knuth'sOptimization.cpp ├── Median-of-2-sorted-arrays.cpp ├── Moore's algorithm.cpp ├── SlidingWindow.cpp ├── Slidingwindow.cpp ├── Smallest number given threshold ├── TwoPointer.cpp ├── bst_traversal.c ├── counting_sort.py ├── dutch_national_flag.cpp └── matrixchainmultiplication.py ├── Binary Search ├── AggresiveCows.cpp ├── Binary_Search.cpp ├── Count_of_an_Element_SortedArray.cpp ├── First_And_Last_Occurence_of_Element.cpp ├── median_of_two_sorted_arrays.cpp └── read.md ├── Codechef Beginner ├── Another Card game Solution.cpp ├── Chef Wars - Return of the Jedi.cpp ├── Chef and Linear Chess.cpp └── Making a Meal.cpp ├── Dynamic Programming ├── 0_1_Knapsack.cpp ├── CherryPickup-II.cpp ├── Equal_sum_partition.cpp ├── LongestCommonSubsequence.cpp ├── Number of Dice Rolls With Target Sum ├── Subset Sum Problem.cpp ├── Trapping Rain Water.cpp ├── Ugly-Number-II.cpp ├── distinct_subsequences.cpp ├── dungeon_game.cpp ├── edit_distance.cpp ├── longest_pallindromic_substring.cpp ├── maximum_product_subarray.cpp ├── minimum_subset_sum_difference.cpp └── wildcard_matching.cpp ├── Easy problems ├── Move_Zeroes.py ├── Reverse Linked List ├── Sort_an_array_Recursion.cpp ├── only_repeated_element.cpp ├── reverseString.cpp └── sum_of_natural_numbers.cpp ├── GFG Solutions ├── Area_of_triangle.C ├── C++ │ ├── 3sum.cpp │ ├── AbsoluteDifference1.cpp │ ├── AdditionOfSubmatrix.cpp │ ├── Missing number in array.cpp │ └── ReverseLLinkthorder.cpp ├── DeleteMiddleOfLinkedList_adiksha20.cpp ├── Implementation of Atoi (GFG Solution).cpp ├── Intersection point in Y shaped Linked Lists.cpp ├── Level Order Traversal.cpp ├── MaximumPathSumBetweenTwoLeafNode.java ├── Parenthesis Checker.cpp ├── Python │ ├── 12-hour-clock-addition.py │ └── Anushumans_Favourite_Number.py ├── Rotate_Matrix_By_90Degree.cpp ├── SubsetSumProblem.cpp ├── count_all_possible_paths_from_top_left_to_bottom_right.cpp ├── search_in_rotated_sorted_array.cpp └── sieveoferoth.cpp ├── Greedy └── CarFuelling.cpp ├── JavaSolution └── bookAllocation.java ├── KadanesAlgorithm.cpp ├── LICENSE ├── Length_of_longest_substring_without_repeating_char.cpp ├── README.md ├── Segment Tree ├── basic.cpp └── readme.md ├── Sorting Algorithms ├── Bubble Sort Algo.c ├── BubbleSort.cpp ├── Bucket Sort.c ├── Counting Sort.c ├── Heap Sort.c ├── Insertion Sort.c ├── InsertionSort.cpp ├── Merge Sort.c ├── MergeSort.cpp ├── Quick Sort.c ├── Radix Sort.c ├── Selection Sort.c ├── SelectionSort.cpp ├── bubble_sort.py ├── cycleSort.java ├── mergesort.py └── selectionsort.py ├── binary-search-approaches ├── bst_traversal.c ├── house_robber.cpp └── leetcode problems ├── build_array_from_permutation.cpp ├── check_distances_btw_same_letters.cpp ├── divide_string_into_k_groups.cpp ├── find_target_indices_after_sorting_array.cpp ├── first_pallidrome.cpp ├── gcd.cpp ├── maximum_population_year.cpp ├── rings_and_rods.cpp ├── roatate_array.cpp ├── sort_odd_even_indices.cpp ├── two_furthest_house_same_color.cpp └── wildcard_matching.cpp /800 Codeforces Solutions/110A_Nearly_Lucky_Number.cpp: -------------------------------------------------------------------------------- 1 | //code by Nikhil Nagrale 2 | //nikhilnagrale2 on EveryPlatform else nknagrale 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | long long n; 8 | cin>>n; 9 | long long count=0; 10 | while(n!=0){ 11 | int x=n%10; 12 | n/=10; 13 | if(x==4 || x==7){ 14 | count++; 15 | } 16 | } 17 | if(count==0) { 18 | cout<<"NO"< 4 | using namespace std; 5 | 6 | int main(){ 7 | string a,b; 8 | cin>>a>>b; 9 | for(auto &c: a) c=tolower(c); 10 | transform(b.begin(),b.end(),b.begin(),::tolower); 11 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | int total=0; 10 | int min=0; 11 | while(n--){ 12 | int x; 13 | cin>>x; 14 | total-=x; 15 | cin>>x; 16 | total+=x; 17 | if(total>min) 18 | min=total; 19 | } 20 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | vector v; 10 | for(int i=0;i>temp; 13 | v.push_back(temp); 14 | } 15 | int a[n]; 16 | int num=1; 17 | for(int x:v){ 18 | a[x-1]=num; 19 | num++; 20 | } 21 | for(int x:a) 22 | cout< 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | int maxindex=0; 11 | int minindex=0; 12 | int maxvalue=INT_MIN; 13 | int minvalue=INT_MAX; 14 | for (int i = 0; i < n; i++) 15 | { 16 | int temp; 17 | cin >> temp; 18 | if(temp>maxvalue){ 19 | maxindex=i; 20 | maxvalue=temp; 21 | } 22 | if(temp<=minvalue){ 23 | minindex=i; 24 | minvalue=temp; 25 | } 26 | } 27 | 28 | int ans=(maxindex)+(n-minindex-1); 29 | if(minindex 4 | using namespace std; 5 | 6 | int main(){ 7 | int a[4],d; 8 | cin>>a[0]>>a[1]>>a[2]>>a[3]>>d; 9 | int j; 10 | set s; 11 | for(int i=0;i<4;i++){ 12 | j=1; 13 | while(a[i]*j<=d){ 14 | if(a[i]*j<=d) s.insert(a[i]*j); 15 | j++; 16 | } 17 | } 18 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n,k; 8 | cin>>n>>k; 9 | vector a; 10 | for(int i=0;i>temp; 13 | a.push_back(temp); 14 | } 15 | int c=a[k-1]; 16 | int count=0; 17 | for(int x:a){ 18 | if(x>=c && x>0) count++; 19 | } 20 | cout< 5 | #define ll long long int 6 | #define pb push_back 7 | #define mp make_pair 8 | using namespace std; 9 | int main(){ 10 | ll t; 11 | cin>>t; 12 | while(t--){ 13 | ll n; 14 | cin>>n; 15 | ll a[n],i,j; 16 | ll sus=0; 17 | for(i=0;i>a[i]; 19 | } 20 | for(i=0;in){ 22 | a[i]/=2; 23 | } 24 | } 25 | sort(a,a+n); 26 | mapm; 27 | for(i=0;i0){ 33 | if(m[a[i]]==0){ 34 | m[a[i]]++; 35 | break;} 36 | else{ 37 | a[i]/=2; 38 | } 39 | 40 | } 41 | if(a[i]==0){ 42 | sus=1; 43 | break; 44 | } 45 | } 46 | } 47 | for(auto it=m.begin();it!=m.end();it++){ 48 | if(it->second==0){ 49 | sus=1; 50 | break; 51 | } 52 | } 53 | if(sus==0){ 54 | cout<<"YES"< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | double a[n]; 10 | double ans=0; 11 | for(int i=0;i>a[i]; 13 | ans+=a[i]; 14 | } 15 | cout< 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | set s; 9 | int temp; 10 | int t = 4; 11 | while (t--) 12 | { 13 | cin >> temp; 14 | s.insert(temp); 15 | } 16 | cout<<4-s.size()< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | int count=0; 10 | while(n--){ 11 | int x,y,z; 12 | cin>>x>>y>>z; 13 | if((x+y+z)>=2) count++; 14 | } 15 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | string s; 8 | cin>>s; 9 | set a; 10 | for(char x:s) a.insert(x); 11 | if(a.size()%2==0) cout<<"CHAT WITH HER!"< 10 | using namespace std; 11 | #define ll long long 12 | #define FAST1 ios_base::sync_with_stdio(false); 13 | #define FAST2 cin.tie(NULL); 14 | int n, k, ans, num; 15 | string s; 16 | int main(){ 17 | FAST1; 18 | FAST2; 19 | 20 | cin >> n >> k; 21 | for (int i = 0; i < n; i++){ 22 | cin >> s; 23 | for (int j = 0; j < s.size(); j++){ 24 | if (s[j] == '7' || s[j] == '4'){ 25 | num ++; 26 | } 27 | } 28 | if (num <= k){ 29 | ans++; 30 | } 31 | num = 0; 32 | } 33 | cout << ans << endl; 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /800 Codeforces Solutions/262B_Roma_and_Changing_Signs.cpp: -------------------------------------------------------------------------------- 1 | // Problem: B. Roma and Changing Signs 2 | // Contest: Codeforces - Codeforces Round #160 (Div. 2) 3 | // URL: https://codeforces.com/contest/262/problem/B 4 | // Memory Limit: 256 MB 5 | // Time Limit: 2000 ms 6 | // 7 | // Powered by CP Editor (https://cpeditor.org) 8 | 9 | #include 10 | using namespace std; 11 | #define ll long long 12 | #define FAST1 ios_base::sync_with_stdio(false); 13 | #define FAST2 cin.tie(NULL); 14 | 15 | 16 | int main(){ 17 | FAST1; 18 | FAST2; 19 | int n;int k; 20 | cin>>n>>k; 21 | int arr[n]; 22 | for(int i=0;i>arr[i]; 24 | 25 | int mn =INT_MAX; 26 | int sm=0; 27 | for(int i=0;i0) 31 | arr[i] *= -1,k--; 32 | sm+=arr[i]; 33 | } 34 | if(k>0 && k%2==1) 35 | sm -= 2 * mn; 36 | 37 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | int a[6][6]; 8 | int n,x,y; 9 | for(int i=1;i<=5;i++){ 10 | for(int j=1;j<=5;j++){ 11 | cin>>n; 12 | if(n){ 13 | x=i; 14 | y=j; 15 | } 16 | } 17 | } 18 | cout<<(abs(3-x)+abs(3-y))< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | string s; 10 | cin>>s; 11 | if(!n){ cout<<0< 4 | using namespace std; 5 | 6 | int main() { 7 | int n,t; 8 | cin>>n>>t; 9 | string a; 10 | cin>>a; 11 | while(t--){ 12 | for(int i=0;i 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | vector> v; 11 | for (int i = 0; i < n; i++) 12 | { 13 | int a, b; 14 | cin >> a >> b; 15 | v.push_back({a, b}); 16 | } 17 | int ans = 0; 18 | for (int i = 0; i < n; i++) 19 | { 20 | for (int j = 0; j < n; j++) 21 | { 22 | if (i != j && v[i].first == v[j].second) 23 | ans++; 24 | } 25 | } 26 | cout << ans << endl; 27 | return 0; 28 | } 29 | 30 | //O(n+m) solution is also possible -------------------------------------------------------------------------------- /800 Codeforces Solutions/271A_Beautiful_Year.cpp: -------------------------------------------------------------------------------- 1 | //code by Nikhil Nagrale 2 | //nikhilnagrale2 on EveryPlatform else nknagrale 3 | #include 4 | using namespace std; 5 | 6 | bool areDistinct(int n) 7 | { 8 | map dis; 9 | int digit; 10 | while (n) 11 | { 12 | digit = n % 10; 13 | if (dis[digit]) 14 | { 15 | return false; 16 | } 17 | dis[digit] = 1; 18 | n /= 10; 19 | } 20 | return true; 21 | } 22 | int main() 23 | { 24 | int n; 25 | cin >> n; 26 | while (++n) 27 | { 28 | if (areDistinct(n)) 29 | { 30 | cout << n << endl; 31 | break; 32 | } 33 | } 34 | return 0; 35 | } -------------------------------------------------------------------------------- /800 Codeforces Solutions/281A_Word_Capitalization.cpp: -------------------------------------------------------------------------------- 1 | //code by Nikhil Nagrale 2 | //nikhilnagrale2 on EveryPlatform else nknagrale 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | string s; 8 | cin>>s; 9 | s[0]=toupper(s[0]); 10 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | string a,b; 8 | cin>>a>>b; 9 | for(int i=0;i 4 | using namespace std; 5 | 6 | int main(){ 7 | int w; 8 | cin>>w; 9 | if(w%2==0 && w>2) cout<<"YES"< 4 | using namespace std; 5 | 6 | int main(){ 7 | int m,n; 8 | cin>>m>>n; 9 | cout<<(n*m)/2< 4 | using namespace std; 5 | 6 | int main(){ 7 | string s; 8 | cin>>s; 9 | int u=0,l=0; 10 | for(auto x:s){ 11 | if(isupper(x)) u++; 12 | else l++; 13 | } 14 | if(u>l){ 15 | transform(s.begin(),s.end(),s.begin(),::toupper); 16 | }else transform(s.begin(),s.end(),s.begin(),::tolower); 17 | cout< 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string a, b; 9 | cin >> a >> b; 10 | string v = ""; 11 | for (int i = 0; i < a.length(); i++) 12 | { 13 | if (a[i] == b[i]) 14 | v += "0"; 15 | else 16 | v += "1"; 17 | } 18 | cout << v << endl; 19 | return 0; 20 | } -------------------------------------------------------------------------------- /800 Codeforces Solutions/71A_Way_Too_Long_Words.cpp: -------------------------------------------------------------------------------- 1 | //code by Nikhil Nagrale 2 | //nikhilnagrale2 on EveryPlatform else nknagrale 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | while(n--){ 10 | string s; 11 | cin>>s; 12 | if(s.length()>10){ 13 | string ans; 14 | ans.push_back(s.front()); 15 | ans+=to_string(s.length()-2); 16 | ans+=s.back(); 17 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cin>>n; 9 | cout<3){ 11 | cout<<2<<" "; 12 | n-=2; 13 | } 14 | cout< 5 | using namespace std; 6 | #define ll long long int 7 | #define intt int 8 | #define sz(x) x.size() 9 | #define pb push_back 10 | #define pb2 pop_back 11 | #define ff first 12 | #define ss second 13 | #define lb lower_bound 14 | #define ub upper_bound 15 | #define bend(x) x.begin(), x.end() 16 | #define vi vector 17 | #define mapp map 18 | #define sett set 19 | #define ve vector 20 | #define un_m unordered_map 21 | #define f(i, a, b) for (i = a; i < b; i++) 22 | #define f2(i, a) for (auto i = a.begin(); i != a.end(); i++) 23 | #define maxxx INT32_MAX 24 | #define mp make_pair 25 | #define in(t) scanf("%lld",&t) 26 | #define out(t) printf("%lld",t) 27 | #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) 28 | #define PQ priority_queue 29 | #define ts(s) to_string(s) 30 | 31 | const unsigned int mod = 1000000007; 32 | string yes = "YES", no = "NO"; 33 | bool isPowerOfTwo (ll x) 34 | { 35 | 36 | return x && (!(x&(x-1))); 37 | } 38 | 39 | void sol() { 40 | ll n{},d{},ds{},x{},k{},i{},j{},tt{},w=-1,t{},y{},cnt{},ans{},m,sum{}; 41 | string s=""; 42 | cin>>n; 43 | if(isPowerOfTwo(n) && n!=1) 44 | { 45 | cout<> tc; 61 | for (int i = 1; i <= tc; i++) { 62 | sol(); 63 | cout << endl; 64 | } 65 | 66 | return 0; 67 | } -------------------------------------------------------------------------------- /Algorithm/BellmanFord.cpp: -------------------------------------------------------------------------------- 1 | /* Priyanka Gupta 2 | Bellman ford graph traversal algo 3 | 4 | input 5 | // 8 5 6 | // 0 1 -1 7 | // 0 2 4 8 | // 1 2 3 9 | // 3 2 5 10 | // 4 3 -3 11 | // 1 4 2 12 | // 1 3 2 13 | // 3 1 1 14 | 15 | */ 16 | 17 | 18 | 19 | #include 20 | using namespace std; 21 | class Edge{ 22 | public: 23 | int src; 24 | int dest; 25 | int weight; 26 | 27 | }; 28 | class Graph{ 29 | int e, v; 30 | Edge*edges; 31 | public: 32 | Graph(int e,int v){ 33 | this->e=e; 34 | this->v=v; 35 | edges=new Edge [e]; 36 | } 37 | void addEdge(int u, int v,int w,int c){ 38 | edges[c].src=u; 39 | edges[c].dest=v; 40 | edges[c].weight=w; 41 | } 42 | 43 | void bellmanford(int src){ 44 | vectordistance(v); 45 | for(int i=0;i>e>>v; 91 | Graph g(e,v); 92 | int src,dest,wt; 93 | for(int i=0;i>src>>dest>>wt; 95 | g.addEdge(src,dest,wt,i); 96 | } 97 | g.bellmanford(0); 98 | } 99 | 100 | -------------------------------------------------------------------------------- /Algorithm/Heapsort.cpp: -------------------------------------------------------------------------------- 1 | //solution by priyanka Gupta 2 | // Heapsort 3 | //used for sorting ---inplace algo 4 | // time complexity O(nlogn) 5 | 6 | #include 7 | using namespace std; 8 | 9 | //optimized function 10 | void downheapify(vector&a,int parentidx,int len){ 11 | 12 | int idx=parentidx,lchild=2*parentidx+1,rchild=2*parentidx+2; 13 | 14 | if(lchild < len && a[lchild]>a[idx]){ 15 | idx=lchild; 16 | } 17 | if(rchild < len && a[rchild]>a[idx]){ 18 | idx=rchild; 19 | } 20 | 21 | if(idx==parentidx)return; 22 | 23 | else{ 24 | swap(a[idx],a[parentidx]); 25 | downheapify(a,idx,len); 26 | } 27 | 28 | 29 | } 30 | 31 | //using heapsort to sort the vector inplace 32 | void heapsort(vector&heap,int n){ 33 | 34 | for(int i=n-1;i>0;i--){ 35 | swap(heap[0],heap[i]); 36 | downheapify(heap,0,i); 37 | } 38 | 39 | } 40 | 41 | //to form heap initially 42 | void buildheap(vector&heap,int n){ 43 | for(int i=n/2-1;i>=0;i--){ 44 | //using downheapify to build heap 45 | downheapify(heap,i,n); 46 | } 47 | } 48 | 49 | int main(){ 50 | 51 | int n; 52 | cin>>n; 53 | vectorheap(n); 54 | for(int i=0;i>heap[i]; 56 | } 57 | 58 | 59 | buildheap(heap,n); 60 | heapsort(heap,n); 61 | 62 | for(int i=0;i 2 | using namespace std; 3 | 4 | // lps is of pattern 5 | // O(n+m) tIME AND o(m) SPACE 6 | void fill_LPS(const string &pattern, vector &lps) 7 | { 8 | int m = pattern.size(); 9 | // lenght of longest proper prefix suffix 10 | lps[0] = 0; // as proper prefix of string length is 0 11 | int i = 1; // starting from first 12 | int len = 0; // in, starting len = 0 13 | // len is previous length of matching 14 | while (i < m) 15 | { 16 | // if next char matches with len 17 | if (pattern[i] == pattern[len]) 18 | { 19 | len++; 20 | lps[i] = len; 21 | i++; 22 | } 23 | else 24 | { 25 | if (len == 0) 26 | { 27 | 28 | lps[i] = 0; 29 | i++; 30 | } 31 | else 32 | { // recusively search for next len 33 | len = lps[len - 1]; 34 | } 35 | } 36 | } 37 | } 38 | 39 | void KMP(const string &text, const string &pattern) 40 | { 41 | int n = text.size(); 42 | int m = pattern.size(); 43 | 44 | vector lps(m, 0); 45 | fill_LPS(pattern, lps); 46 | int i = 0, j = 0; 47 | while (i < n) 48 | { 49 | // if match then move forward 50 | if (pattern[j] == text[i]) 51 | { 52 | i++; 53 | j++; 54 | } 55 | // if after match , it is covers entire lenght of pat. 56 | if (j == m) 57 | { 58 | cout << (i - j) << " "; 59 | j = lps[j - 1]; //FIND THE NEXT TO MATCH 60 | } 61 | // if not match 62 | else if (i < n and pattern[j] != text[i]) 63 | { 64 | // if first charcater not matching 65 | if (j == 0) 66 | { 67 | i++; 68 | } 69 | // search recursively 70 | else 71 | { 72 | j = lps[j - 1]; 73 | } 74 | } 75 | } 76 | } 77 | 78 | 79 | int main() 80 | { 81 | string text; 82 | cin >> text; 83 | string pat; 84 | cin >> pat; 85 | KMP(text, pat); 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /Algorithm/Knuth'sOptimization.cpp: -------------------------------------------------------------------------------- 1 | int solve() { 2 | int N; 3 | ... // read N and input 4 | int dp[N][N], opt[N][N]; 5 | 6 | auto C = [&](int i, int j) { 7 | ... // Implement cost function C. 8 | }; 9 | 10 | for (int i = 0; i < N; i++) { 11 | opt[i][i] = i; 12 | ... // Initialize dp[i][i] according to the problem 13 | } 14 | 15 | for (int i = N-2; i >= 0; i--) { 16 | for (int j = i+1; j < N; j++) { 17 | int mn = INT_MAX; 18 | int cost = C(i, j); 19 | for (int k = opt[i][j-1]; k <= min(j-1, opt[i+1][j]); k++) { 20 | if (mn >= dp[i][k] + dp[k+1][j] + cost) { 21 | opt[i][j] = k; 22 | mn = dp[i][k] + dp[k+1][j] + cost; 23 | } 24 | } 25 | dp[i][j] = mn; 26 | } 27 | } 28 | 29 | cout << dp[0][N-1] << endl; 30 | } 31 | -------------------------------------------------------------------------------- /Algorithm/Median-of-2-sorted-arrays.cpp: -------------------------------------------------------------------------------- 1 | // naive approach 1 : merge both the array and sort it and then u can easily canculate median 2 | // TC : O(N+M)log(N+M) SC : O(N+M) 3 | 4 | // Approach 2 : merge both array in sorted order using Two pointers and then we can get our answer 5 | // TC : O(N+M) SC : O(N+M) 6 | 7 | // Approach 3 : while merging both the array using 2 pointers , we can store middle and middle-1 element 8 | // TC : O(N+M) SC : O(1) 9 | 10 | // Approach 4 : We try to partition the arrays such that the left elements of median <= right elments of 11 | // median 12 | // Ex : {7,12,14,15} ,{1,2,3,4,9,11} -> [1,2,3,4,7 | 9,11,12,14,15] 13 | 14 | // we do this by applying binary search on smaller array 15 | 16 | // TC : O(log(min(n,m))) SC : O(1) 17 | 18 | class Solution { 19 | public: 20 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 21 | 22 | if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2,nums1) ; 23 | int n = nums1.size() ; 24 | int m = nums2.size() ; 25 | 26 | 27 | // so i need to do partition so ,that means i need to pick some elements from num1 and rem from nums2. 28 | 29 | int s = 0 ; // minimum elements i can pick from nums1(smaller array) || u can say minimum cut u can do. 30 | int e = n ; // maximum elements i can pick from nums1 || maxmum cut u can do. 31 | 32 | while(s<=e) { 33 | 34 | int mid = s + (e-s)/2 ; 35 | 36 | int cut1 = mid ; 37 | int cut2 = (n+m+1)/2-cut1 ; 38 | 39 | int l1 = cut1==0 ? INT_MIN : nums1[cut1-1] ; 40 | int l2 = cut2==0 ? INT_MIN : nums2[cut2-1] ; 41 | 42 | int r1 = cut1==n ? INT_MAX : nums1[cut1] ; 43 | int r2 = cut2==m ? INT_MAX : nums2[cut2] ; 44 | 45 | // obv l1 < r1 and l2 < r2 so need to check it 46 | 47 | if(l1<=r2 and l2<=r1) { 48 | 49 | if((n+m)&1) return max(l1,l2) ; 50 | else { 51 | double ans = (max(l1,l2) + min(r1,r2))/2.0 ; 52 | return ans ; 53 | } 54 | } 55 | else if(l1 > r2) e = mid-1 ; 56 | else s = mid+1 ; 57 | 58 | } 59 | 60 | return 0.0 ; 61 | 62 | 63 | 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /Algorithm/Moore's algorithm.cpp: -------------------------------------------------------------------------------- 1 | //*************MOORE'S ALGORITHM************* 2 | //Solution by Atharva kulkarni 3 | 4 | //Question : find the majority element in an array with an occurence of more than n/2 times(given such element always exists) 5 | //question link : https://leetcode.com/problems/majority-element/ 6 | 7 | //DESCRIPTION : The crucks of this (moore's) algorithm is if an element is occuring more than (n/2) times i.e. it is occuring in majority we reduce count 8 | //of such element even if the count gets equal to zero at start it will be positive at the end . For better understanding do some dry runs. 9 | 10 | //Time complexities: O(n) 11 | 12 | //IP1 : 3 2 3 13 | //OP1 : 3(count=2) 14 | 15 | //IP2 : 7 7 5 7 5 1 5 7 5 5 7 7 5 5 5 5 16 | //OP2 : 5(count=9) 17 | 18 | #include 19 | using namespace std; 20 | int main() { 21 | int n; 22 | cin >> n; 23 | int nums[n]; 24 | for (int i = 0; i < n; i++) cin >> nums[i]; 25 | int count = 0; 26 | int element = 0; 27 | for (int i = 0; i < n; i++) { 28 | if (count == 0) element = nums[i]; 29 | if (element == nums[i]) count++; 30 | else count--; 31 | } 32 | cout << element; 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Algorithm/SlidingWindow.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sliding Window Technique 3 | Problem : Find maximum sum of subarray if size k 4 | TimeComplexity = O(N) 5 | */ 6 | #include 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | int a[]={-8,4,3,-2,-3,4,8,21,-6,15,8,0}; 12 | int k=4; 13 | int curSum=0,maxSum=0; 14 | for(int i=0;i 14 | using namespace std; 15 | int lengthOfLongestSubstring(string s) { 16 | unordered_map mp; 17 | int i=0,j=0; 18 | int maxm=0; 19 | while(j>t; 53 | cout<<"The length of longest substring is : "<&arr,int n , int div) 5 | { 6 | int sum=0; 7 | for(int i=0;i& arr, int threshold) { 21 | 22 | /* 23 | 24 | we need to find smallest divisor such that sum of arr divided 25 | by divisor is just less than threshold 26 | => pattern to observe 27 | arr = [ 1 , 2 , 5 , 9 ] 28 | the max elem of the arr which when divided gives= 1+1+1+1=4 29 | so 4 is surely one of the ans. 30 | and the min div can be one which when divided gives = 1+2+5+9=17 31 | which is actually sum of the array 32 | 33 | so our ans lies in b/w 1 to max elem of arr 34 | 35 | why binary search: 36 | when divided by 1 : 17 37 | when divided by 2 : 10 (1+1+3+5) 38 | when divided by 3 : 7 (1+1+2+3) 39 | ..... 40 | when divided by 9 : 4 (1+1+1+1) 41 | 42 | we can see a pattern of monotonic decreasing function 43 | this type of question comes under binary search on answer 44 | 45 | 46 | */ 47 | 48 | 49 | int low=1,high=*max_element(arr.begin(), arr.end()); 50 | int ans=high; 51 | 52 | while(low<=high) 53 | { 54 | int mid = low+(high-low)/2; 55 | // mid is giving <=threshold 56 | // but we are looking for even smaller number , hence do 57 | // a search on the left 58 | if(sumafterdivision(arr,arr.size(),mid)<=threshold) 59 | { 60 | ans=mid; 61 | high=mid-1; 62 | } 63 | else 64 | { 65 | low=mid+1; 66 | } 67 | 68 | } 69 | return ans; 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /Algorithm/TwoPointer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Two pointer algorithm 3 | Problem : find wether a given number can be represented as sum of pair of elemnts in the given array 4 | TimeComplexity = O(NlogN) 5 | */ 6 | #include 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | int a[]={-8,4,3,-2,-3,4,-6,8,21,15,8,0}; 12 | int targetSum=19; 13 | 14 | sort(a,a+12); 15 | int i=0,j=11; 16 | bool flag=false; 17 | while(itargetSum) 25 | { 26 | j--; 27 | } 28 | else if(a[i]+a[j] 2 | # include 3 | # include 4 | 5 | typedef struct BST { 6 | int data; 7 | struct BST *lchild, *rchild; 8 | } node; 9 | 10 | void insert(node *, node *); 11 | void inorder(node *); 12 | void preorder(node *); 13 | void postorder(node *); 14 | node *search(node *, int, node **); 15 | 16 | void main() { 17 | int choice; 18 | char ans = 'N'; 19 | int key; 20 | node *new_node, *root, *tmp, *parent; 21 | node *get_node(); 22 | root = NULL; 23 | 24 | 25 | printf("\nProgram For Binary Search Tree "); 26 | do { 27 | printf("\n1.Create"); 28 | printf("\n2.Search"); 29 | printf("\n3.Recursive Traversals"); 30 | printf("\n4.Exit"); 31 | printf("\nEnter your choice :"); 32 | scanf("%d", &choice); 33 | 34 | switch (choice) { 35 | case 1: 36 | do { 37 | new_node = get_node(); 38 | printf("\nEnter The Element "); 39 | scanf("%d", &new_node->data); 40 | 41 | if (root == NULL) /* Tree is not Created */ 42 | root = new_node; 43 | else 44 | insert(root, new_node); 45 | 46 | printf("\nWant To enter More Elements?(y/n)"); 47 | ans = getch(); 48 | } while (ans == 'y'); 49 | break; 50 | 51 | case 2: 52 | printf("\nEnter Element to be searched :"); 53 | scanf("%d", &key); 54 | 55 | tmp = search(root, key, &parent); 56 | printf("\nParent of node %d is %d", tmp->data, parent->data); 57 | break; 58 | 59 | case 3: 60 | if (root == NULL) 61 | printf("Tree Is Not Created"); 62 | else { 63 | printf("\nThe Inorder display : "); 64 | inorder(root); 65 | printf("\nThe Preorder display : "); 66 | preorder(root); 67 | printf("\nThe Postorder display : "); 68 | postorder(root); 69 | } 70 | break; 71 | } 72 | } while (choice != 4); 73 | } 74 | /* 75 | Get new Node 76 | */ 77 | node *get_node() { 78 | node *temp; 79 | temp = (node *) malloc(sizeof(node)); 80 | temp->lchild = NULL; 81 | temp->rchild = NULL; 82 | return temp; 83 | } 84 | /* 85 | This function is for creating a binary search tree 86 | */ 87 | void insert(node *root, node *new_node) { 88 | if (new_node->data < root->data) { 89 | if (root->lchild == NULL) 90 | root->lchild = new_node; 91 | else 92 | insert(root->lchild, new_node); 93 | } 94 | 95 | if (new_node->data > root->data) { 96 | if (root->rchild == NULL) 97 | root->rchild = new_node; 98 | else 99 | insert(root->rchild, new_node); 100 | } 101 | } 102 | /* 103 | This function is for searching the node from 104 | binary Search Tree 105 | */ 106 | node *search(node *root, int key, node **parent) { 107 | node *temp; 108 | temp = root; 109 | while (temp != NULL) { 110 | if (temp->data == key) { 111 | printf("\nThe %d Element is Present", temp->data); 112 | return temp; 113 | } 114 | *parent = temp; 115 | 116 | if (temp->data > key) 117 | temp = temp->lchild; 118 | else 119 | temp = temp->rchild; 120 | } 121 | return NULL; 122 | } 123 | /* 124 | This function displays the tree in inorder fashion 125 | */ 126 | void inorder(node *temp) { 127 | if (temp != NULL) { 128 | inorder(temp->lchild); 129 | printf("%d", temp->data); 130 | inorder(temp->rchild); 131 | } 132 | } 133 | /* 134 | This function displays the tree in preorder fashion 135 | */ 136 | void preorder(node *temp) { 137 | if (temp != NULL) { 138 | printf("%d", temp->data); 139 | preorder(temp->lchild); 140 | preorder(temp->rchild); 141 | } 142 | } 143 | 144 | /* 145 | This function displays the tree in postorder fashion 146 | */ 147 | void postorder(node *temp) { 148 | if (temp != NULL) { 149 | postorder(temp->lchild); 150 | postorder(temp->rchild); 151 | printf("%d", temp->data); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /Algorithm/counting_sort.py: -------------------------------------------------------------------------------- 1 | # inspired from https://www.geeksforgeeks.org/counting-sort/ 2 | 3 | def counting_sort(arr): 4 | # The output character array that will have sorted arr 5 | output = [0 for i in range(len(arr))] 6 | 7 | # Create a count array to store count of inidividul items 8 | count = [0 for i in range(256)] 9 | 10 | # For storing the resulting answer 11 | ans = [0 for _ in arr] 12 | 13 | # Store count of each element 14 | for i in arr: 15 | count[i] += 1 16 | 17 | # Change count[i] so that count[i] now contains actual 18 | # position of this element in output array 19 | for i in range(256): 20 | count[i] += count[i - 1] 21 | 22 | # Build the output element array 23 | for i in range(len(arr)): 24 | output[count[arr[i]] - 1] = arr[i] 25 | count[arr[i]] -= 1 26 | 27 | # Copy the output array to arr, so that arr now 28 | # contains sorted elements 29 | for i in range(len(arr)): 30 | ans[i] = output[i] 31 | return ans 32 | 33 | 34 | # create array and call counting_sort function 35 | arr = [10, 9, 1, 12, 6, 5, 7] 36 | ans = counting_sort(arr) 37 | print("Sorted character array is: " + str(ans)) 38 | -------------------------------------------------------------------------------- /Algorithm/dutch_national_flag.cpp: -------------------------------------------------------------------------------- 1 | //Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // Function to sort the input array, 9 | // the array is assumed 10 | // to have values in {0, 1, 2} 11 | class Solution 12 | { 13 | public: 14 | void sort012(int a[], int n) 15 | { 16 | 17 | int low = 0; 18 | int high = n-1; 19 | int mid = 0; 20 | 21 | while(mid<=high){ 22 | switch(a[mid]){ 23 | case 0:{ 24 | swap(a[low], a[mid]); 25 | low++; 26 | mid++; 27 | break; 28 | } 29 | case 1:{ 30 | mid++; 31 | break; 32 | } 33 | case 2:{ 34 | swap(a[mid], a[high]); 35 | high--; 36 | break; 37 | } 38 | } 39 | } 40 | } 41 | 42 | }; 43 | 44 | 45 | int main() 46 | { 47 | int T; 48 | cin>>T; 49 | while(T--) 50 | { 51 | int N; 52 | cin>>N; 53 | int A[N]; 54 | for(int i=0;i>A[i]; 56 | Solution ob; 57 | ob.sort012(A,N); 58 | for(int i=0;i= 0: 19 | return m[start][end] 20 | 21 | if start == end: 22 | q = 0 23 | else: 24 | q = float('inf') 25 | for k in range(start, end): 26 | temp = matrix_product_helper(p, start, k, m, s) \ 27 | + matrix_product_helper(p, k + 1, end, m, s) \ 28 | + p[start - 1]*p[k]*p[end] 29 | if q > temp: 30 | q = temp 31 | s[start][end] = k 32 | 33 | m[start][end] = q 34 | return q 35 | 36 | 37 | def print_parenthesization(s, start, end): 38 | 39 | if start == end: 40 | print('A[{}]'.format(start), end='') 41 | return 42 | 43 | k = s[start][end] 44 | 45 | print('(', end='') 46 | print_parenthesization(s, start, k) 47 | print_parenthesization(s, k + 1, end) 48 | print(')', end='') 49 | 50 | 51 | n = int(input('Enter number of matrices: ')) 52 | p = [] 53 | for i in range(n): 54 | temp = int(input('Enter number of rows in matrix {}: '.format(i + 1))) 55 | p.append(temp) 56 | temp = int(input('Enter number of columns in matrix {}: '.format(n))) 57 | p.append(temp) 58 | 59 | m, s = matrix_product(p) 60 | print('The number of scalar multiplications needed:', m[1][n]) 61 | print('Optimal parenthesization: ', end='') 62 | print_parenthesization(s, 1, n) 63 | -------------------------------------------------------------------------------- /Binary Search/AggresiveCows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | Optimal Algo approach- 6 | Logic: 7 | We need to define a isPossible() function that checks if a distance x is possible between each of the cows. 8 | We can use a greedy approach here by placing cows at the leftmost possible stalls such that they are at 9 | least x distance away from the last-placed cow. 10 | We need to sort the given array/list so once we have our sorted array to do the greedy task then we can 11 | apply the Binary Search algorithm on the sorted input, and use our function isPossible( ) to find the 12 | largest distance possible. 13 | 14 | The time complexity of this approach is O(nlogn) but otherwise bruteforce would be having very high time 15 | complexity. 16 | */ 17 | 18 | bool isPossible(vector &stalls, int minDist, int k) 19 | { 20 | int cows=1; 21 | int lastCowPosition=stalls[0]; 22 | for(int i=1;i=minDist) 25 | { 26 | cows++; 27 | lastCowPosition=stalls[i]; 28 | if(cows>=k) return true; 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | int aggressiveCows(vector &stalls, int k) 35 | { 36 | int n=stalls.size(); 37 | sort(stalls.begin(),stalls.end()); 38 | int low=1,high=stalls[n-1]-stalls[0]; 39 | int res; 40 | while(low<=high) 41 | { 42 | int mid=(low+high)/2; 43 | if(isPossible(stalls,mid,k)) 44 | { 45 | res=mid; 46 | low=mid+1; 47 | } 48 | else high=mid-1; 49 | } 50 | return res; 51 | } 52 | 53 | 54 | 55 | int main(){ 56 | int n; 57 | cin >> n; 58 | 59 | vector stalls(n); 60 | for(int i=0;i> stalls[i]; 61 | 62 | int k; 63 | cin >> k; 64 | 65 | int ans=aggressiveCows(stalls,k); 66 | 67 | cout << ans << endl; 68 | return 0; 69 | } -------------------------------------------------------------------------------- /Binary Search/Binary_Search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums which is sorted in ascending order, and an integer target, 3 | write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. 4 | You must write an algorithm with O(log n) runtime complexity. 5 | */ 6 | 7 | 8 | int search(vector& nums, int target) { 9 | int low = 0, high = nums.size()-1; 10 | 11 | while(low<=high) 12 | { 13 | // same as mid = (low+high)/2, below one is to avoid overflow 14 | int mid = low+(high-low)/2; 15 | 16 | if(nums[mid] == target) 17 | return mid; 18 | else if(nums[mid] > target) 19 | high = mid - 1; 20 | else 21 | low = mid + 1; 22 | } 23 | 24 | return -1; 25 | } 26 | }; -------------------------------------------------------------------------------- /Binary Search/Count_of_an_Element_SortedArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. 3 | Expected time complexity is O(Logn) 4 | */ 5 | 6 | /* 7 | Approach: 8 | This problem is same as finding first and last occurrences of x in sorted array. 9 | It's just that they have framed the problem in a different way. 10 | */ 11 | 12 | 13 | /* 14 | Examples: 15 | Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 1 16 | Output: 2 [1 occurs at index 0 and index 1 => 1-0+1 = 2] 17 | 18 | Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 4 19 | Output: -1 // 4 doesn't occur in arr[] 20 | */ 21 | 22 | 23 | int binarySearch(vector& nums, int target, bool flag) 24 | { 25 | int low = 0; 26 | int high = nums.size()-1; 27 | 28 | int ansIndex = -1; 29 | while(low <= high) 30 | { 31 | int mid = low + (high-low)/2; 32 | 33 | if(nums[mid] == target) 34 | { 35 | ansIndex = mid; 36 | if(flag == 0) 37 | high = mid - 1; 38 | else 39 | low = mid + 1; 40 | } 41 | else if(nums[mid] > target) 42 | high = mid - 1; 43 | else 44 | low = mid + 1; 45 | } 46 | 47 | return ansIndex; 48 | } 49 | 50 | 51 | int countOccurrences(vector arr, int target) 52 | { 53 | int first = binarySearch(arr, target, 0); 54 | int last = binarySearch(arr, target, 1); 55 | 56 | if(first == -1 || last == -1) 57 | return -1; 58 | else 59 | return last - first + 1; 60 | 61 | } 62 | -------------------------------------------------------------------------------- /Binary Search/First_And_Last_Occurence_of_Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. 3 | If target is not found in the array, return [-1, -1]. 4 | You must write an algorithm with O(log n) runtime complexity. 5 | */ 6 | 7 | /* 8 | Approach: 9 | 1. Find the first occurence of the target element using binary search 10 | Once u find the element then move the high pointer to mid - 1 as we finding the first occurence there might be a chance that there 11 | is another occurence of the element before the current occurence 12 | 13 | 2. Find the last occurence of the target element using binary search 14 | Once u find the element then move the low pointer to mid + 1 as we finding the last occurence there might be a chance that there 15 | is another occurence of the element after the current occurence 16 | */ 17 | 18 | // You can find this question on Leetcode:(34) 19 | 20 | class Solution { 21 | public: 22 | 23 | int binarySearch(vector& nums, int target, bool flag) 24 | { 25 | int low = 0; 26 | int high = nums.size()-1; 27 | 28 | int ansIndex = -1; 29 | while(low <= high) 30 | { 31 | int mid = low + (high-low)/2; 32 | 33 | if(nums[mid] == target) 34 | { 35 | ansIndex = mid; 36 | if(flag == 0) 37 | high = mid - 1; 38 | else 39 | low = mid + 1; 40 | } 41 | else if(nums[mid] > target) 42 | high = mid - 1; 43 | else 44 | low = mid + 1; 45 | } 46 | 47 | return ansIndex; 48 | } 49 | 50 | 51 | 52 | vector searchRange(vector& nums, int target) { 53 | vector ans(2, -1); 54 | ans[0] = binarySearch(nums, target, 0); // flag = 0 for first occurence 55 | ans[1] = binarySearch(nums, target, 1); // flag = 1 for last occurence 56 | return ans; 57 | } 58 | }; -------------------------------------------------------------------------------- /Binary Search/median_of_two_sorted_arrays.cpp: -------------------------------------------------------------------------------- 1 | //Given two sorted arrays array1 and array2 of size m and n respectively. 2 | //Find the median of the two sorted arrays. 3 | 4 | #include 5 | using namespace std; 6 | double MedianOfArrays(vector& array1, vector& array2); 7 | 8 | 9 | class Solution{ 10 | public: 11 | double MedianOfArrays(vector& nums1, vector& nums2) 12 | { 13 | if(nums2.size()right2){ 34 | high = cut1-1; 35 | }else{ 36 | low = cut1+1; 37 | } 38 | 39 | } 40 | return 0.0; 41 | 42 | } 43 | }; 44 | 45 | 46 | int main() 47 | { 48 | int t; 49 | cin>>t; 50 | while(t--) 51 | { 52 | int m,n; 53 | cin>>m; 54 | vector array1(m); 55 | for (int i = 0; i < m; ++i){ 56 | cin>>array1[i]; 57 | } 58 | cin>>n; 59 | vector array2(n); 60 | for (int i = 0; i < n; ++i){ 61 | cin>>array2[i]; 62 | } 63 | Solution ob; 64 | cout< it basically means searching in an sequential fashion. [TC -> O(N)] 16 | 2) Binary Search -> It can only be applied on sorted data.It divides the given data into two parts in each iteration and based on condition reduces the data sized to half of its original size and neglecting the half data.This is what it makes this algorithm so efficient 17 | [TC -> log(N)]. 18 | 19 | 20 | 21 | HOW TO GET MOST OUT OF THIS REPO : Follow this repo from first question to last.As some questions are build from previous question approach 22 | and some are the same question just framed differently. 23 | 24 | -------------------------------------------------------------------------------- /Codechef Beginner/Another Card game Solution.cpp: -------------------------------------------------------------------------------- 1 | //August Long Challenge 2020 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int i,j; 10 | int t; 11 | //taking test input 12 | cin>>t; 13 | while(t--) 14 | { 15 | int ans; 16 | int n,k; 17 | cin>>n>>k; 18 | int count = (n == 0) ? 1 : (log10(n) + 1); 19 | int count1 = (k == 0) ? 1 : (log10(k) + 1); 20 | if((n-k>0 && n-k<9 )||( k-n>0 && k-n<9) ) 21 | { 22 | ans=1; 23 | cout<=9) 27 | { 28 | ans=1; 29 | if(k%9==0) 30 | cout<=9) 36 | { 37 | ans=0; 38 | 39 | if(n%9==0 ) 40 | cout< 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | {//input 8 | long long int i,j; 9 | long long int h,p; 10 | long long int t; 11 | //input of test case 12 | cin>>t; 13 | while (t--) 14 | { 15 | cin>>h>>p; 16 | //checking if h is greater than 2 time p & printing "1" if false and "0" if true . 17 | if(h>2*p) 18 | { 19 | cout<<"0"< 3 | using namespace std; 4 | #define ll long long int 5 | int main() { 6 | //taking input// 7 | ll t; 8 | cin>>t; 9 | while(t--) 10 | { 11 | //taking inputs 12 | ll n,chefP,mi=INT_MAX,ans; 13 | cin>>n>>chefP; 14 | ll p[n]; 15 | for(int i=0;i>p[i]; 18 | //checking every instance of array and comparing it with chefP number 19 | if(p[i]<=chefP) 20 | { 21 | //checking if if the number is divisible by the value in array p. 22 | if(chefP%p[i]==0) 23 | { 24 | ll k=chefP/p[i]; 25 | //finding k 26 | if(k 11 | using namespace std; 12 | 13 | int main() { 14 | int t; 15 | cin>>t; //Number of test cases 16 | while(t--) 17 | { 18 | int n,i; 19 | string s,s_t=""; 20 | cin>>n; // Number of ingredients 21 | for(i=0;i>s; //Name of ingredients 24 | s_t+=s; //Concate all the ingredients in am empty string 25 | } 26 | unordered_mapm; 27 | for(i=0;i 2 | using namespace std; 3 | 4 | int max(int a, int b) 5 | { 6 | return (a > b) ? a : b; 7 | } 8 | 9 | 10 | int knapsack(int W, int wt[], int val[], int n) 11 | { 12 | int i, j; 13 | 14 | //create table with size n+1 and W+1 15 | int t[n + 1][W + 1]; 16 | 17 | // Build table t[][] in bottom up manner 18 | //initialize 1st row and column 19 | for (i = 0; i <= n; i++) { 20 | for (j = 0; j <= W; j++) { 21 | // initialize 1st row and column with 0 rest with -1 22 | if (i == 0 || j == 0){ 23 | t[i][j] = 0; 24 | }else{ 25 | t[i][j] = -1; 26 | } 27 | } 28 | } 29 | 30 | //for understanding 31 | cout< Try Out All Possible Paths -> Recursion 17 | 18 | // this is a case of fixed starting point and variable ending point. 19 | 20 | // Now one can say, lets first find the max cherries picked by robot1 by recursion and then similarly 21 | // find the totalcherris picked up by robot2 and then add both and return the ans 22 | 23 | // but in this case if u will observe , u can see there are possibilites that one or more than one cells 24 | // can be common in both their paths and as we know A/q , cell in the path should be counted one time only. 25 | 26 | // so again you have to traverse the grid and have to remove the common ones 27 | // it will be quite tedious and as well as long . so We will not do that. 28 | 29 | // so What we will do bro ? 30 | // for both robots , we will traverse simulataneuously. 31 | 32 | // Lets Get Started ! 33 | 34 | // step 1 ) express in terms of indexes 35 | // f(i1,j1,i2,j2) 36 | // but as we are traversing simultaneously , i1==i2 37 | // therefore we will reduce it to f(i,j1,j2) 38 | 39 | // now lets think about base cases , Think of base cases like (1) Destination Base Case , (2) Out Of Bound Case 40 | 41 | // write out of bound case before destination case as it will ocurr before the last row . 42 | 43 | // step 2 ) Explore all paths 44 | 45 | // Think of any instant , you will see for each option of robot A , robot B has Three Options 46 | // i.e total ways = 3 *3 = 9 ways . so we will try out all those rest will be done by recursion 47 | // also remember the consider the cases of being in the same cell and different cell 48 | 49 | // step 3 ) return the maximum 50 | 51 | //////////////////////////////////////////////////////// 52 | 53 | // as we know recursion gives exponential time complexity so we will have to reduce it 54 | 55 | // so if there are overlapping subproblems we can apply memoization 56 | 57 | // for that lets think of the dp array , think about its size 58 | // for its size think about possibles values of parameters present in your dp (in our case f(i,j1,j2)) 59 | // possible values of i -> 0 to n-1 i.e N values , j1 -> 0 to m-1 i.e M values , j2 -> 0 to m-1 i.e M values. 60 | 61 | // so our array will be : dp[N][M][M] of NMM 62 | 63 | // res u Know what to do . 64 | 65 | // memoization : TC : O(NMM)9 66 | // SC : O(NM*M)(dp array) + O(N)(stack space) 67 | 68 | 69 | 70 | 71 | 72 | class Solution { 73 | public: 74 | int MaxCherry(int i,int j1, int j2 ,int n,int m, vector& grid, vector> &dp) { 75 | 76 | // base case 77 | if(j1<0 || j1 >= m || j2 < 0 || j2 >= m) return -1e8 ; 78 | 79 | if(i==n-1) 80 | { 81 | 82 | if(j1==j2) return grid[i][j1] ; 83 | else return grid[i][j1] + grid[i][j2] ; 84 | } 85 | if(dp[i][j1][j2] != -1) return dp[i][j1][j2] ; 86 | 87 | // Try Out All Possible Paths 88 | int maxi = INT_MIN ; 89 | 90 | for(int dj1 = -1 ;dj1 <= 1 ;dj1++) { 91 | for(int dj2 = -1 ;dj2 <= 1 ;dj2++) { 92 | 93 | int sum = 0 ; 94 | 95 | // both robot are in same cell 96 | if(j1==j2) sum += grid[i][j1] ; 97 | 98 | // both are in different cell 99 | else sum += grid[i][j1] + grid[i][j2] ; 100 | 101 | sum += MaxCherry(i+1,j1+dj1,j2+dj2,n,m,grid,dp) ; 102 | 103 | maxi = max(maxi,sum) ; 104 | } 105 | } 106 | 107 | // return the maximum 108 | return dp[i][j1][j2] = maxi ; 109 | 110 | 111 | } 112 | 113 | 114 | int cherryPickup(vector>& grid) { 115 | 116 | int n = grid.size() ; 117 | int m = grid[0].size() ; 118 | vector< vector< vector > > dp(n , vector< vector > (m, vector (m,-1) ) ); 119 | return MaxCherry(0,0,m-1,n,m,grid,dp) ; 120 | 121 | } 122 | }; 123 | -------------------------------------------------------------------------------- /Dynamic Programming/Equal_sum_partition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int max(int a, int b) 5 | { 6 | return (a > b) ? a : b; 7 | } 8 | 9 | 10 | int equal_sum_partition(int arr[], int n) 11 | { 12 | int i, j,sum=0; 13 | //sum whole array 14 | for (int i = 0; i < n; ++i) 15 | { 16 | sum=sum+arr[i]; 17 | } 18 | 19 | //if sum is odd partiton not possible 20 | if (sum%2!=0) 21 | { 22 | cout<<"Ans= Partiton not possible"< 2 | using namespace std; 3 | 4 | int max(int a, int b) 5 | { 6 | return (a > b) ? a : b; 7 | } 8 | 9 | void LCS(string X, string Y, int m, int n){ 10 | //create table 11 | int t[m+1][n+1]; 12 | 13 | //initialize table. 1st row and columns with 0 rest with -1 14 | for (int i = 0; i < m+1; ++i) 15 | { 16 | for (int j = 0; j < n+1; ++j){ 17 | if(i==0 || j==0){ 18 | t[i][j]=0; 19 | } 20 | else{ 21 | t[i][j]=-1; 22 | } 23 | } 24 | } 25 | 26 | 27 | cout<<"Before DP"< 2 | using namespace std; 3 | 4 | int subset_sum(int arr[], int sum, int n) 5 | { 6 | int i, j; 7 | bool t[n + 1][sum + 1]; 8 | 9 | for (int i = 0; i < n+1; i++) 10 | t[i][0] = true; 11 | 12 | // If sum is not 0 and set is empty, 13 | // then answer is false 14 | for (int i = 1; i < sum+1; i++) 15 | t[0][i] = false; 16 | //for understanding 17 | cout<& height) { 4 | int size = height.size(); 5 | vectormxl(size); 6 | vectormxr(size); 7 | vectorwater(size); 8 | int sum=0; 9 | if(size==0) 10 | return 0; 11 | mxl[0]=height[0]; 12 | for(int i=1; i=0; i--) 17 | mxr[i]=max(mxr[i+1], height[i]); 18 | 19 | for(int i=0; idp(n) ; 56 | 57 | dp[0] = 1 ; 58 | 59 | int pt1 = 0 ; 60 | int pt2 = 0 ; 61 | int pt3 = 0 ; 62 | 63 | for(int i=1 ;i>& dp) { 4 | int n = dp.size(); 5 | int m = dp[0].size(); 6 | for(int i = n-1; i >= 0; i--){ 7 | for(int j = m-1; j >= 0; j--){ 8 | if(i == n-1 && j == m-1) { 9 | dp[i][j] = min(0,dp[i][j]); 10 | } 11 | else if(i == n-1) 12 | dp[i][j] = min(0,dp[i][j+1] + dp[i][j]); 13 | 14 | else if(j == m-1) 15 | dp[i][j] = min(0,dp[i+1][j] + dp[i][j]); 16 | 17 | else 18 | dp[i][j] = min(0,dp[i][j] + max(dp[i][j+1], dp[i+1][j])); 19 | } 20 | } 21 | return abs(dp[0][0]) + 1; 22 | 23 | } 24 | }; -------------------------------------------------------------------------------- /Dynamic Programming/edit_distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string s, string t) { 4 | int n=s.length(),m=t.length(); 5 | int dp[n+1][m+1]; 6 | memset(dp,0,sizeof(dp)); 7 | 8 | for(int i=0;i<=n;i++) 9 | { 10 | for(int j=0;j<=m;j++) 11 | { 12 | if(i==0) 13 | dp[i][j]=j; 14 | else if(j==0) 15 | dp[i][j]=i; 16 | else if(s[i-1]==t[j-1]) 17 | dp[i][j]=dp[i-1][j-1]; 18 | else 19 | dp[i][j]=1+min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])); 20 | } 21 | } 22 | return dp[n][m]; 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /Dynamic Programming/longest_pallindromic_substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void printSubStr( 4 | string str, int low, int high,string &s) 5 | { 6 | for (int i = low; i <= high; ++i) 7 | s+=str[i]; 8 | } 9 | string longestPalindrome(string str) { 10 | int n = str.size(); 11 | 12 | bool table[n][n]; 13 | 14 | memset(table, 0, sizeof(table)); 15 | string s; 16 | // All substrings of length 1 17 | // are palindromes 18 | int maxLength = 1; 19 | 20 | for (int i = 0; i < n; ++i) 21 | table[i][i] = true; 22 | 23 | // check for sub-string of length 2. 24 | int start = 0; 25 | for (int i = 0; i < n - 1; ++i) { 26 | if (str[i] == str[i + 1]) { 27 | table[i][i + 1] = true; 28 | start = i; 29 | maxLength = 2; 30 | } 31 | } 32 | 33 | // Check for lengths greater than 2. 34 | // k is length of substring 35 | for (int k = 3; k <= n; ++k) { 36 | // Fix the starting index 37 | for (int i = 0; i < n - k + 1; ++i) { 38 | // Get the ending index of substring from 39 | // starting index i and length k 40 | int j = i + k - 1; 41 | 42 | // checking for sub-string from ith index to 43 | // jth index iff str[i+1] to str[j-1] is a 44 | // palindrome 45 | if (table[i + 1][j - 1] && str[i] == str[j]) { 46 | table[i][j] = true; 47 | 48 | if (k > maxLength) { 49 | start = i; 50 | maxLength = k; 51 | } 52 | } 53 | } 54 | } 55 | 56 | //cout << "Longest palindrome substring is: "; 57 | printSubStr(str, start, start + maxLength - 1,s); 58 | 59 | // return length of LPS 60 | return s; 61 | } 62 | 63 | }; -------------------------------------------------------------------------------- /Dynamic Programming/maximum_product_subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int minm=nums[0],maxm=nums[0],n=nums.size(),maxp=nums[0]; 5 | for(int i=1;i 2 | #include 3 | using namespace std; 4 | 5 | 6 | void min_subset_sum_diff(int arr[], int n) 7 | { 8 | int sum=0; 9 | for (int i = 0; i < n; ++i) 10 | { 11 | sum=sum+arr[i]; 12 | } 13 | int i, j; 14 | int t[n + 1][(sum/2)+1]; 15 | 16 | for (int i = 0; i <= n; i++) 17 | t[i][0] = true; 18 | 19 | // If sum is not 0 and set is empty, 20 | // then answer is false 21 | for (int i = 1; i < (sum/2)+1; i++) 22 | t[0][i] = false; 23 | //for understanding 24 | for (i = 1; i <= n; i++) { 25 | for (j = 1; j < (sum/2)+1; j++) { 26 | t[i][j]=0; 27 | } 28 | } 29 | 30 | cout<<"Before DP"<=0; --i) 66 | { 67 | if(t[n][i]==1){ 68 | diff=sum-2*i; 69 | break; 70 | } 71 | } 72 | 73 | cout<<"Minimum Difference of 2 subsets sum =" < 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | int data; 7 | node*next; 8 | 9 | node(int data ){ 10 | this->data=data; 11 | next=NULL; 12 | } 13 | }; 14 | 15 | node*takeinput(){ 16 | 17 | int data; 18 | cin>>data; 19 | node*head=NULL; 20 | node*tail=NULL; 21 | while(data!=-1){ 22 | node*newnode=new node(data); 23 | if(head==NULL){ 24 | head=newnode; 25 | tail=newnode; 26 | } 27 | else{ 28 | tail->next=newnode; 29 | tail=newnode; 30 | } 31 | cin>>data; 32 | } 33 | return head; 34 | } 35 | 36 | node*reverse(node*head){ 37 | 38 | if(head==NULL || head->next==NULL){ 39 | return head; 40 | } 41 | 42 | node*smallans=reverse(head->next); 43 | node*tail=head->next; 44 | tail->next=head; 45 | head->next=NULL; 46 | 47 | return smallans; 48 | } 49 | 50 | void print(node*head){ 51 | while(head!=NULL){ 52 | cout<data<<" "; 53 | head=head->next; 54 | } 55 | } 56 | int main() { 57 | 58 | node*head=takeinput(); 59 | head=reverse(head); 60 | print(head); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Easy problems/Sort_an_array_Recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector insert(vector & nums,int key){ 5 | if(nums.size()==0 || nums[nums.size()-1]<= key){ 6 | nums.push_back(key); 7 | return nums; 8 | } 9 | int val = nums[nums.size()- 1]; 10 | nums.pop_back(); 11 | nums = insert(nums,key); 12 | nums.push_back(val); 13 | return nums; 14 | } 15 | 16 | vector sort(vector & nums){ 17 | if(nums.size()==0) 18 | return nums; 19 | int lastnum = nums[nums.size()-1]; 20 | nums.pop_back(); 21 | nums = sort(nums); 22 | return nums = insert(nums,lastnum); 23 | } 24 | int main(){ 25 | int size; 26 | cin >> size; 27 | vector nums; 28 | for(int i=0; i> x; 31 | nums.push_back(x); 32 | } 33 | 34 | nums = sort(nums); 35 | for(int i=0; i 5 | using namespace std; 6 | 7 | int findOnlyRepeated(int a[] , int size) 8 | { 9 | int count[10000]; 10 | memset(count , 0 , sizeof(count)); 11 | 12 | for(int i=0 ; i < size ; i++) 13 | { 14 | count[a[i]] += 1; 15 | } 16 | 17 | int ans; 18 | for(int i=0 ; i < 10000 ; i++) 19 | { 20 | if(count[i] == 2) 21 | { 22 | ans = i; 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | 29 | int main() 30 | { 31 | int a[] = { 3 , 4 , 12 , 25 , 4 , 10 }; 32 | 33 | int ans = findOnlyRepeated(a , 6); 34 | 35 | cout< 2 | using namespace std; 3 | 4 | void reverse(string& str,int i,int j) 5 | { 6 | cout<<"call recieved for"<j) 9 | return ; 10 | 11 | swap(str[i],str[j]); 12 | i++; 13 | j--; 14 | 15 | //reversive call 16 | reverse(str,i,j); 17 | 18 | } 19 | 20 | int main() 21 | { 22 | string name = "abcde"; 23 | cout< 2 | using namespace std; 3 | int sumofnatural(int n){ 4 | if(n==1){ 5 | return 1; 6 | } 7 | return n + sumofnatural(n-1); 8 | } 9 | int main(){ 10 | int m;cin>>m; 11 | cout< 21 | #include 22 | int main() { 23 | int t; 24 | scanf("%d",&t); 25 | while(t>0){ 26 | double a,b,c,p,area; 27 | scanf("%lf %lf %lf",&a,&b,&c); 28 | p=(a+b+c)/2; 29 | area=sqrt(p*(p-a)*(p-b)*(p-c)); 30 | printf("%lf\n",(area>=0?area:0.000000)); 31 | t--; 32 | } 33 | return 0; 34 | } -------------------------------------------------------------------------------- /GFG Solutions/C++/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& arr) { 4 | bool found = false; 5 | vector vect; 6 | vector> ans; 7 | // sort array elements 8 | sort(arr.begin(), arr.end()); 9 | int n=arr.size(); 10 | int i=0; 11 | while(il && arr[r]==high)r--; 32 | 33 | } 34 | 35 | // If sum of three elements is less 36 | // than zero then increment in left 37 | else if (x + arr[l] + arr[r] < 0) 38 | { 39 | while(ll && arr[r]==high)r--; 46 | } 47 | } 48 | while(i 2 | #include 3 | 4 | using namespace std; 5 | 6 | bool condition(int num){ 7 | string s = to_string(num); 8 | 9 | for(int i = 1; i < s.size(); i++){ 10 | if(abs(s[i]-s[i-1]) != 1){ 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | 18 | int main() 19 | { 20 | //code 21 | int test; 22 | cin >> test; 23 | 24 | while(test--){ 25 | int n, k, count = 0; 26 | cin >> n >> k; 27 | 28 | vector temp(n); 29 | 30 | for(int i = 0; i < n; i++){ 31 | cin >> temp[i]; 32 | } 33 | 34 | for(int i = 0; i < n; i++){ 35 | if(temp[i] < k && condition(temp[i])){ 36 | count++; 37 | cout << temp[i] << " "; 38 | } 39 | } 40 | 41 | if(!count){ 42 | cout << "-1"; 43 | } 44 | 45 | cout << endl; 46 | } 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /GFG Solutions/C++/AdditionOfSubmatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int test; 8 | cin >> test; 9 | 10 | while(test){ 11 | int r, c, ans = 0, r1, c1, r2, c2; 12 | cin >> r >> c; 13 | 14 | vector > temp(r, vector(c)); 15 | 16 | for(int i = 0; i < r; i++){ 17 | for(int j = 0; j < c; j++){ 18 | cin >> temp[i][j]; 19 | } 20 | } 21 | 22 | cin >> r1 >> c1 >> r2 >> c2; 23 | 24 | for(int i = r1-1; i < r2; i++){ 25 | for(int j = c1-1; j < c2; j++){ 26 | ans = ans + temp[i][j]; 27 | } 28 | } 29 | 30 | cout << ans << endl; 31 | 32 | test--; 33 | } 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /GFG Solutions/C++/Missing number in array.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public: 4 | int MissingNumber(vector& array, int n) { 5 | // Your code goes here 6 | int i, total; 7 | total = (n) * (n+1 ) / 2; 8 | for (i = 0; i < n-1; i++) 9 | { 10 | total -= array[i]; 11 | } 12 | return total; 13 | 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /GFG Solutions/C++/ReverseLLinkthorder.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /////// IMPLEMENTATION OF LINKED LIST //////////////////////////// 7 | class node 8 | { 9 | public: 10 | int data; 11 | node *next; /// pointer of node is to be formed 12 | 13 | // constructor function 14 | node(int data) 15 | { 16 | this->data = data; 17 | this->next = NULL; 18 | } 19 | }; 20 | 21 | // INSERTION AT HEAD 22 | void insertAthead(node *&head, int d) 23 | { 24 | // new node created 25 | node *temp = new node(d); 26 | temp->next = head; 27 | head = temp; 28 | } 29 | 30 | // INSERTION AT TAIL OR END:::: 31 | void insertAttail(node *&tail, int d) 32 | { 33 | node *temp = new node(d); 34 | tail->next = temp; 35 | tail = temp; 36 | } 37 | 38 | ///// INSERTION AT GIVEN INDEXXX ::::::::::::::::: 39 | void insertAtpostion(node *tail, node *&head, int position, int d) 40 | { 41 | if (position == 1) 42 | { 43 | insertAthead(head, d); 44 | return; 45 | } 46 | node *temp = head; 47 | int cnt = 1; 48 | while (cnt < position - 1) 49 | { 50 | temp = temp->next; 51 | cnt++; 52 | } 53 | // creating node for d 54 | node *nodetoinsert = new node(d); 55 | nodetoinsert->next = temp->next; 56 | temp->next = nodetoinsert; 57 | cout << "head = " << head->data << endl; 58 | cout << "Tail = " << head->data << endl; 59 | } 60 | 61 | //// REVERSE LL IN KTH GRP //// 62 | 63 | /// here we are using recursion to solve this 64 | node *reverseKthGRP(node *&head, int k) 65 | { 66 | // base casee 67 | if (head == NULL) 68 | { 69 | return NULL; 70 | } 71 | // step 1 : reverse the first k nodes of ll 72 | node *next = NULL; 73 | node *curr = head; 74 | node *prev = NULL; 75 | int count = 0; 76 | while (curr != NULL && count < k) 77 | { 78 | next = curr->next; 79 | curr->next = prev; 80 | prev = curr; 81 | curr = next; 82 | count++; 83 | } 84 | 85 | // STEP 2 : RECURSION DEKLEGA AB 86 | if (next != NULL) 87 | { 88 | head->next = reverseKthGRP(next, k); 89 | } 90 | /// STEP 3 : RETURN HEAD OF REVERSED LL 91 | return prev; 92 | } 93 | 94 | // print node 95 | void print(node *&head) 96 | { 97 | node *temp = head; 98 | while (temp != NULL) 99 | { 100 | cout << temp->data << " "; 101 | temp = temp->next; 102 | } 103 | cout << endl; 104 | } 105 | 106 | int main() 107 | { 108 | 109 | node *node1 = new node(60); // new node node 1 110 | 111 | // head pointed to node1 112 | node *head = node1; 113 | // tail pointed to node1 114 | // for single node posityion of tail and head is same 115 | node *tail = node1; 116 | 117 | // This and -> is used because it stores the address of data and next node 118 | 119 | // insertion prosecss at head : 120 | insertAthead(head, 50); 121 | 122 | insertAthead(head, 40); 123 | insertAthead(head, 30); 124 | insertAthead(head, 20); 125 | insertAthead(head, 10); 126 | print(head); 127 | 128 | /// Kth revers 129 | int k; 130 | cout << "Kth ORDER : "; 131 | cin >> k; 132 | head = reverseKthGRP(head, k); 133 | 134 | cout << "\nReversed Linked list \n"; 135 | print(head); 136 | 137 | return 0; 138 | } -------------------------------------------------------------------------------- /GFG Solutions/DeleteMiddleOfLinkedList_adiksha20.cpp: -------------------------------------------------------------------------------- 1 | // C program to find n'th Node in linked list 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | /* Link list Node */ 8 | struct Node { 9 | int data; 10 | struct Node *next; 11 | 12 | Node(int x) { 13 | data = x; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | void append(struct Node **head_ref, struct Node **tail_ref, int new_data) { 19 | struct Node *new_node = new Node(new_data); 20 | new_node->next = NULL; 21 | 22 | if (*head_ref == NULL) 23 | *head_ref = new_node; 24 | else 25 | (*tail_ref)->next = new_node; 26 | *tail_ref = new_node; 27 | } 28 | 29 | /* Function to get the middle of the linked list*/ 30 | struct Node *deleteMid(struct Node *head); 31 | 32 | void printList(Node *head) { 33 | while (head != NULL) { 34 | cout << head->data << " "; 35 | head = head->next; 36 | } 37 | cout << "\n"; 38 | } 39 | 40 | /* Driver program to test above function*/ 41 | int main() { 42 | int T, i, n, l; 43 | 44 | cin >> T; 45 | 46 | while (T--) { 47 | struct Node *head = NULL, *tail = NULL; 48 | 49 | cin >> n; 50 | for (i = 1; i <= n; i++) { 51 | cin >> l; 52 | append(&head, &tail, l); 53 | } 54 | 55 | head = deleteMid(head); 56 | printList(head); 57 | } 58 | return 0; 59 | } 60 | // } Driver Code Ends 61 | /* Link list Node 62 | /* Link list Node 63 | struct Node 64 | { 65 | int data; 66 | struct Node* next; 67 | 68 | Node(int x){ 69 | data = x; 70 | next = NULL; 71 | } 72 | }; 73 | */ 74 | 75 | // Deletes middle of linked list and returns head of the modified list 76 | Node* deleteMid(Node* head) { 77 | Node *p=head; 78 | int count=-1; 79 | int pos; 80 | Node *q=head; 81 | Node *r=NULL; 82 | 83 | // Counting the length of the linked list 84 | while(p) 85 | { 86 | count++; 87 | p=p->next; 88 | } 89 | 90 | // Finding the middle element 91 | if(count%2==0) 92 | { 93 | pos=count/2; 94 | 95 | } 96 | else 97 | { 98 | pos=count/2; 99 | pos=pos+1; 100 | } 101 | 102 | // Deleting the middle element 103 | for(int i=0;i<=count;i++) 104 | { 105 | if(i==pos) 106 | { 107 | r->next=q->next; 108 | q=r->next; 109 | 110 | } 111 | else 112 | { 113 | r=q; 114 | q=q->next; 115 | } 116 | } 117 | return head; 118 | // Your Code Here 119 | } 120 | -------------------------------------------------------------------------------- /GFG Solutions/Implementation of Atoi (GFG Solution).cpp: -------------------------------------------------------------------------------- 1 | /* Problem Implement Atoi 2 | from GFG Practice 3 | Time Complexity: O(|S|), |S|= length of string S. 4 | Space Complexity: O(1) 5 | */ 6 | 7 | int atoi(string str) 8 | { 9 | int num=0, index=0, flag=1; 10 | if(str[0]=='-') 11 | { 12 | index = 1; 13 | flag = -1; 14 | } 15 | for(;str[index];index++) 16 | { 17 | if(isdigit(str[index])) 18 | { 19 | num = (num * 10) + (str[index]-'0'); 20 | } 21 | else{ 22 | return -1; 23 | } 24 | } 25 | return num*flag; 26 | } -------------------------------------------------------------------------------- /GFG Solutions/Intersection point in Y shaped Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | /* Link list Node */ 8 | struct Node 9 | { 10 | int data; 11 | struct Node *next; 12 | Node(int x) 13 | { 14 | data = x; 15 | next = NULL; 16 | } 17 | }; 18 | 19 | int intersectPoint(struct Node* head1, struct Node* head2); 20 | 21 | Node* inputList(int size) 22 | { 23 | if(size==0) return NULL; 24 | 25 | int val; 26 | cin>> val; 27 | 28 | Node *head = new Node(val); 29 | Node *tail = head; 30 | 31 | for(int i=0; i>val; 34 | tail->next = new Node(val); 35 | tail = tail->next; 36 | } 37 | 38 | return head; 39 | } 40 | 41 | /* Driver program to test above function*/ 42 | int main() 43 | { 44 | int T,n1,n2,n3; 45 | 46 | cin>>T; 47 | while(T--) 48 | { 49 | cin>>n1>>n2>>n3; 50 | 51 | Node* head1 = inputList(n1); 52 | Node* head2 = inputList(n2); 53 | Node* common = inputList(n3); 54 | 55 | Node* temp = head1; 56 | while(temp!=NULL && temp->next != NULL) 57 | temp = temp->next; 58 | if(temp!=NULL) temp->next = common; 59 | 60 | temp = head2; 61 | while(temp!=NULL && temp->next != NULL) 62 | temp = temp->next; 63 | if(temp!=NULL) temp->next = common; 64 | 65 | cout << intersectPoint(head1, head2) << endl; 66 | } 67 | return 0; 68 | } 69 | 70 | // } Driver Code Ends 71 | 72 | 73 | /* Linked List Node 74 | struct Node { 75 | int data; 76 | struct Node *next; 77 | Node(int x) { 78 | data = x; 79 | next = NULL; 80 | } 81 | }; */ 82 | 83 | //Function to find intersection point in Y shaped Linked Lists. 84 | int intersectPoint(Node* head1, Node* head2) 85 | { 86 | // Your Code Here 87 | Node* t1=head1; 88 | Node* t2=head2; 89 | while(t1 && t2){ 90 | if(t1==t2) 91 | return t1->data; 92 | 93 | else{ 94 | t1=t1->next; 95 | t2=t2->next; 96 | if(t1==NULL) 97 | t1=head2; 98 | else if(t2==NULL) 99 | t2=head1; 100 | } 101 | } 102 | return -1; 103 | } 104 | 105 | -------------------------------------------------------------------------------- /GFG Solutions/Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem- Level Order Traversal(BFS) 3 | Platform- GFG 4 | Author - Adarsh 5 | */ 6 | vector levelOrder(Node* node) 7 | { 8 | queue q; 9 | vector v; 10 | q.push(node); 11 | while(!q.empty()) 12 | { 13 | Node *cur=q.front(); 14 | q.pop(); 15 | v.push_back(cur->data); 16 | if(cur->left!=NULL) 17 | { 18 | q.push(cur->left); 19 | } 20 | if(cur->right!=NULL) 21 | { 22 | q.push(cur->right); 23 | } 24 | 25 | } 26 | return v; 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /GFG Solutions/MaximumPathSumBetweenTwoLeafNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. 4 | 5 | 6 | Example 1: 7 | 8 | Input : 9 | 3 10 | / \ 11 | 4 5 12 | / \ 13 | -10 4 14 | 15 | Output: 16 16 | 17 | Explanation : 18 | Maximum Sum lies between leaf node 4 and 5. 19 | 4 + 4 + 3 + 5 = 16. 20 | 21 | Example 2: 22 | 23 | Input : 24 | -15 25 | / \ 26 | 5 6 27 | / \ / \ 28 | -8 1 3 9 29 | / \ \ 30 | 2 -3 0 31 | / \ 32 | 4 -1 33 | / 34 | 10 35 | 36 | Output : 27 37 | 38 | Explanation: 39 | The maximum possible sum from one leaf node 40 | to another is (3 + 6 + 9 + 0 + -1 + 10 = 27) 41 | 42 | Your Task: 43 | You dont need to read input or print anything. Complete the function maxPathSum() which takes root node as input parameter and returns the maximum sum between 2 leaf nodes. 44 | 45 | 46 | Expected Time Complexity: O(N) 47 | Expected Auxiliary Space: O(Height of Tree) 48 | 49 | 50 | Constraints: 51 | 1 ≤ N ≤ 10^4 52 | 53 | */ 54 | 55 | 56 | class Tree 57 | { 58 | static int maxLL; 59 | 60 | int maxPathSum(Node root) 61 | { 62 | maxLL=Integer.MIN_VALUE; 63 | int res = maxPathSumLL(root); 64 | return maxLL; 65 | } 66 | 67 | int maxPathSumLL(Node root){ 68 | if(root == null) return Integer.MIN_VALUE; 69 | 70 | if(root.left == null && root.right == null) return root.data; 71 | 72 | int left = maxPathSumLL(root.left); 73 | int right = maxPathSumLL(root.right); 74 | 75 | if(root.left != null && root.right != null){ 76 | maxLL = Math.max(maxLL,left+right+root.data); 77 | //System.out.println(maxLL + " " + left + " " + right + " " + root.data); 78 | 79 | } 80 | // System.out.println(left + " " + right + " " + root.data); 81 | return Math.max(left,right)+root.data; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /GFG Solutions/Parenthesis Checker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem - Parenthesis Checker 3 | Platform- GFG 4 | Time Complexity-O(N) 5 | Author Adarsh 6 | */ 7 | 8 | bool ispar(string x) 9 | { 10 | stack s; 11 | s.push('x'); 12 | for(int i=0;i0: 41 | num = int(input()) 42 | print("YES" if (num%5==0) else "NO") 43 | t-=1 44 | -------------------------------------------------------------------------------- /GFG Solutions/Rotate_Matrix_By_90Degree.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | class Solution 8 | { 9 | public: 10 | //Function to rotate matrix anticlockwise by 90 degrees. 11 | void rotateby90(vector >& matrix, int n) 12 | { 13 | // code here 14 | //int row=matrix.size(); 15 | for(int i=0;i>t; 34 | 35 | while(t--) 36 | { 37 | int n; 38 | cin>>n; 39 | vector > matrix(n); 40 | 41 | for(int i=0; i>matrix[i][j]; 47 | } 48 | } 49 | 50 | Solution ob; 51 | ob.rotateby90(matrix, n); 52 | for (int i = 0; i < n; ++i) 53 | for (int j = 0; j < n; ++j) 54 | cout< 8 | using namespace std; 9 | 10 | 11 | bool back(int sum,int arr[],int n,int start){ 12 | if(sum==0){ 13 | return true; 14 | } 15 | if(sum<0)return false; 16 | 17 | for(int i=start;i>t; 44 | while(t--){ 45 | int N; 46 | cin>>N; 47 | int arr[N]; 48 | for(int i = 0;i < N;i++) 49 | cin>>arr[i]; 50 | 51 | Solution ob; 52 | if(ob.equalPartition(N, arr)) 53 | cout<<"YES\n"; 54 | else 55 | cout<<"NO\n"; 56 | } 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /GFG Solutions/count_all_possible_paths_from_top_left_to_bottom_right.cpp: -------------------------------------------------------------------------------- 1 | 2 | //The task is to count all the possible paths from top left 3 | // to bottom right of a m X n matrix with the constraints 4 | // that from each cell you can either move only to right or down. 5 | 6 | #include 7 | using namespace std; 8 | 9 | 10 | #define ll long long 11 | const int md = 1e9 + 7; 12 | class Solution { 13 | public: 14 | long long int numberOfPaths(int m, int n){ 15 | 16 | vectorprev(n,1), curr(n); 17 | curr[0] = 1; 18 | for(int i = 1; i < m; i++){ 19 | for(int j = 1; j < n; j++){ 20 | curr[j] = (curr[j - 1] + prev[j])%md; 21 | } 22 | prev = curr; 23 | } 24 | return prev[n - 1]; 25 | 26 | } 27 | }; 28 | 29 | 30 | 31 | int main() { 32 | int t; 33 | cin >> t; 34 | while (t--) { 35 | int n, m; 36 | cin >> m >> n; 37 | Solution ob; 38 | cout<& nums, int target) { 4 | 5 | int n=nums.size(); 6 | int start=0; 7 | int end=n-1; 8 | int mid; 9 | while(start<=end){ 10 | mid=(start+end)>>1; 11 | 12 | // when target is found 13 | if(nums[mid]==target){ 14 | return mid; 15 | } 16 | 17 | // if left part is montonically increasing 18 | else if(nums[start]<=nums[mid]){ 19 | // if target lies in the sorted part 20 | if(target>=nums[start] && target<=nums[mid]){ 21 | end=mid; 22 | } 23 | else{ 24 | start=mid+1; 25 | } 26 | } 27 | // if right part is montonically increasing 28 | else if(nums[mid]<=nums[end]){ 29 | // if target lies in the sorted part 30 | if(target>=nums[mid] && target<=nums[end]){ 31 | start=mid; 32 | } 33 | else{ 34 | end=mid-1; 35 | } 36 | } 37 | } 38 | // if target is not present then return -1 39 | return -1; 40 | 41 | } 42 | }; -------------------------------------------------------------------------------- /GFG Solutions/sieveoferoth.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void primesieve(int n){ 6 | int arr[n] = {0}; 7 | for(int i=2; i<=n; i++){ 8 | if(arr[i]==0){ 9 | for(int j=i*i; j<=n;j+=i){ 10 | arr[j] = 1; 11 | 12 | } 13 | } 14 | } 15 | for(int i=2; i<=n; i++){ 16 | if(arr[i]== 0 ){ 17 | cout << i << endl; 18 | } 19 | } 20 | } 21 | 22 | // void primesieve(int n ){ 23 | // int prime[n] = {0} ; 24 | // int i , j ; 25 | // for (i = 2; i <= n; i++) 26 | // { if (prime[i] == 0) 27 | // { 28 | // for(j = i*i ; j<= n ; j+=i){ 29 | // prime[j] = 1; 30 | // } 31 | // } 32 | // } 33 | 34 | // for ( i = 2; i <= n; i++) 35 | // { 36 | // if (prime[i] == 0) 37 | // { 38 | // cout<>n; 49 | cout<<" ALL PRIME NUMBERS ARE : "; 50 | primesieve(n); 51 | return 0 ; 52 | } -------------------------------------------------------------------------------- /Greedy/CarFuelling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int total_distance,mileage,n;// 7 | cin>>total_distance>>mileage>>n; //n representing number of gas stations. 8 | vectora(n); 9 | int i; 10 | for(i=0;i>a[i]; 12 | a.insert(a.begin(),0); //starting from 0 13 | a.push_back(total_distance); //destination is the total_distance 14 | 15 | i=0; 16 | int ans=0; 17 | while (a[i]+mileage mid){ 22 | sum= num; 23 | distributeStu++; 24 | } 25 | else { 26 | sum+= num; 27 | } 28 | } 29 | 30 | if(distributeStu>actualStu){ 31 | start= mid+1; 32 | }else { 33 | end= mid; 34 | } 35 | } 36 | return end; 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /KadanesAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kadane's Algorithm for maximum subarray sum 3 | Time Complexity= O(n) 4 | Author: Adarsh 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int arr[]={-1,0,5,6,-2,8,3,-5,-1,0,6,-2,-8,3,-5}; 13 | 14 | int maxSum=arr[0],currentSum=0; 15 | 16 | for(int i=0;i<15;i++) 17 | { 18 | if(currentSum+arr[i]>0) 19 | { 20 | currentSum+=arr[i]; //Keeps tack of sum of current subarray 21 | } 22 | else{ 23 | currentSum=0; 24 | } 25 | maxSum=max(maxSum,currentSum); //Update maximum sum 26 | 27 | } 28 | cout< Initialize current sum variable as 0(if all elements are less than zero, then 34 | maximum sum will be of empty subarray ). 35 | => Now while sum of subarray is grater then zero keep adding the elements and after each iteration 36 | update value of maxSum variable, this will provide you final answer. 37 | */ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Milind Gupta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Length_of_longest_substring_without_repeating_char.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Firstly I will check wether element is first occur or it is occured befor already 3 | Then if it is occured first time then i will stor it in map and change max2 accordingly 4 | else if is occured earlier then i will remove it from map and increase my second pointer and after that i will that element again as my first pointer remians same in this case 5 | */ 6 | int lengthOfLongestSubstring(string s) { 7 | int i=0,j=0; 8 | unordered_mapmp; 9 | int max2=0; 10 | while(i 2 | using namespace std; 3 | 4 | void buildTree(vector &nums, vector &tree, int si, int ei, int idx) 5 | { 6 | if (si == ei) 7 | { 8 | tree[idx] = nums[si]; 9 | return; 10 | } 11 | 12 | int mid = si + ((ei - si) / 2); 13 | 14 | buildTree(nums, tree, si, mid, (2 * idx) + 1); 15 | buildTree(nums, tree, mid + 1, ei, (2 * idx) + 2); 16 | tree[idx] = tree[(2 * idx) + 1] + tree[(2 * idx) + 2]; 17 | } 18 | 19 | void buildTree(vector &nums, vector &tree) 20 | { 21 | int n = nums.size(); 22 | buildTree(nums, tree, 0, n - 1, 0); 23 | } 24 | 25 | int getSum(vector &tree, int L, int R, int si, int ei, int idx) 26 | { 27 | if (ei < L || si > R) 28 | { 29 | return 0; 30 | } 31 | 32 | if (L <= si && R >= ei) 33 | { 34 | return tree[idx]; 35 | } 36 | 37 | int mid = si + ((ei - si) / 2); 38 | 39 | return getSum(tree, L, R, si, mid, (2 * idx) + 1) + getSum(tree, L, R, mid + 1, ei, (2 * idx) + 2); 40 | } 41 | 42 | int getSum(vector &nums, vector &tree, int L, int R) 43 | { 44 | return getSum(tree, L, R, 0, nums.size() - 1, 0); 45 | } 46 | 47 | void update(vector &tree, int si, int ei, int idx, int index, int val) 48 | { 49 | if (si > index || ei < index) 50 | { 51 | return; 52 | } 53 | tree[idx] += val; 54 | if (si < ei) 55 | { 56 | int mid = si + ((ei - si) / 2); 57 | update(tree, si, mid, (2 * idx) + 1, index, val); 58 | update(tree, mid + 1, ei, (2 * idx) + 2, index, val); 59 | } 60 | } 61 | 62 | void update(vector &nums, vector &tree, int index, int val) 63 | { 64 | update(tree, 0, tree.size() - 1, 0, index, val - nums[index]); 65 | nums[index] = val; 66 | } 67 | 68 | int main() 69 | { 70 | #ifndef ONLINE_JUDGE 71 | freopen("E:/Code/DSA/input.txt", "r", stdin); 72 | freopen("E:/Code/DSA/output.txt", "w", stdout); 73 | #endif 74 | int n; 75 | cin >> n; 76 | vector nums(n); 77 | for (int i = 0; i < n; i++) 78 | { 79 | cin >> nums[i]; 80 | } 81 | vector tree(4 * n); 82 | buildTree(nums, tree); 83 | cout << getSum(nums, tree, 0, 1) << endl; 84 | cout << getSum(nums, tree, 0, 0) << endl; 85 | cout << getSum(nums, tree, 0, 2) << endl; 86 | cout << getSum(nums, tree, 0, 3) << endl; 87 | cout << getSum(nums, tree, 1, 3) << endl; 88 | cout << getSum(nums, tree, 2, 3) << endl; 89 | cout << getSum(nums, tree, 3, 3) << endl; 90 | cout << getSum(nums, tree, 1, 2) << endl; 91 | cout << getSum(nums, tree, 2, 2) << endl; 92 | update(nums, tree, 1, 25); 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /Segment Tree/readme.md: -------------------------------------------------------------------------------- 1 | **Segment Tree In CPP** 2 | -------------------------------------------------------------------------------- /Sorting Algorithms/Bubble Sort Algo.c: -------------------------------------------------------------------------------- 1 | void bubble_sort( int A[ ], int n ) { 2 | int temp; 3 | for(int k = 0; k< n-1; k++) { 4 | // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations 5 | 6 | for(int i = 0; i < n-k-1; i++) { 7 | if(A[ i ] > A[ i+1] ) { 8 | // here swapping of positions is being done. 9 | temp = A[ i ]; 10 | A[ i ] = A[ i+1 ]; 11 | A[ i + 1] = temp; 12 | } 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Sorting Algorithms/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | // Optimized implementation of Bubble sort 2 | #include 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | // An optimized version of Bubble Sort 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | bool swapped; 16 | for (i = 0; i < n-1; i++) 17 | { 18 | swapped = false; 19 | for (j = 0; j < n-i-1; j++) 20 | { 21 | if (arr[j] > arr[j+1]) 22 | { 23 | swap(&arr[j], &arr[j+1]); 24 | swapped = true; 25 | } 26 | } 27 | 28 | // IF no two elements were swapped by inner loop, then break 29 | if (swapped == false) 30 | break; 31 | } 32 | } 33 | 34 | /* Function to print an array */ 35 | void printArray(int arr[], int size) 36 | { 37 | int i; 38 | for (i=0; i < size; i++) 39 | printf("%d ", arr[i]); 40 | printf("n"); 41 | } 42 | 43 | // Driver program to test above functions 44 | int main() 45 | { 46 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 47 | int n = sizeof(arr)/sizeof(arr[0]); 48 | bubbleSort(arr, n); 49 | printf("Sorted array: \n"); 50 | printArray(arr, n); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Sorting Algorithms/Bucket Sort.c: -------------------------------------------------------------------------------- 1 | void bucketSort(float[] a,int n) 2 | { 3 | for(each floating integer 'x' in n) 4 | { 5 | insert x into bucket[n*x]; 6 | } 7 | for(each bucket) 8 | { 9 | sort(bucket); 10 | } 11 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Counting Sort.c: -------------------------------------------------------------------------------- 1 | void counting_sort(int A[], int Aux[], int sortedA[], int N) { 2 | 3 | // First, find the maximum value in A[] 4 | int K = 0; 5 | for(int i=0; i= 2 ; i-- ) 8 | { 9 | swap|(Arr[ 1 ], Arr[ i ]); 10 | heap_size = heap_size - 1; 11 | max_heapify(Arr, 1, heap_size); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Sorting Algorithms/Insertion Sort.c: -------------------------------------------------------------------------------- 1 | void insertion_sort ( int A[ ] , int n) 2 | { 3 | for( int i = 0 ;i < n ; i++ ) { 4 | /*storing current element whose left side is checked for its 5 | correct position .*/ 6 | 7 | int temp = A[ i ]; 8 | int j = i; 9 | 10 | /* check whether the adjacent element in left side is greater or 11 | less than the current element. */ 12 | 13 | while( j > 0 && temp < A[ j -1]) { 14 | 15 | // moving the left side element to one position forward. 16 | A[ j ] = A[ j-1]; 17 | j= j - 1; 18 | 19 | } 20 | // moving current element to its correct position. 21 | A[ j ] = temp; 22 | } 23 | } -------------------------------------------------------------------------------- /Sorting Algorithms/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | #include 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Sorting Algorithms/Merge Sort.c: -------------------------------------------------------------------------------- 1 | void merge(int A[ ] , int start, int mid, int end) { 2 | //stores the starting position of both parts in temporary variables. 3 | int p = start ,q = mid+1; 4 | 5 | int Arr[end-start+1] , k=0; 6 | 7 | for(int i = start ;i <= end ;i++) { 8 | if(p > mid) //checks if first part comes to an end or not . 9 | Arr[ k++ ] = A[ q++] ; 10 | 11 | else if ( q > end) //checks if second part comes to an end or not 12 | Arr[ k++ ] = A[ p++ ]; 13 | 14 | else if( A[ p ] < A[ q ]) //checks which part has smaller element. 15 | Arr[ k++ ] = A[ p++ ]; 16 | 17 | else 18 | Arr[ k++ ] = A[ q++]; 19 | } 20 | for (int p=0 ; p< k ;p ++) { 21 | /* Now the real array has elements in sorted manner including both 22 | parts.*/ 23 | A[ start++ ] = Arr[ p ] ; 24 | } 25 | } -------------------------------------------------------------------------------- /Sorting Algorithms/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | // Merges two subarrays of arr[]. 6 | // First subarray is arr[l..m] 7 | // Second subarray is arr[m+1..r] 8 | void merge(int arr[], int l, int m, int r) 9 | { 10 | int i, j, k; 11 | int n1 = m - l + 1; 12 | int n2 = r - m; 13 | 14 | /* create temp arrays */ 15 | int L[n1], R[n2]; 16 | 17 | /* Copy data to temp arrays L[] and R[] */ 18 | for (i = 0; i < n1; i++) 19 | L[i] = arr[l + i]; 20 | for (j = 0; j < n2; j++) 21 | R[j] = arr[m + 1 + j]; 22 | 23 | /* Merge the temp arrays back into arr[l..r]*/ 24 | i = 0; // Initial index of first subarray 25 | j = 0; // Initial index of second subarray 26 | k = l; // Initial index of merged subarray 27 | while (i < n1 && j < n2) { 28 | if (L[i] <= R[j]) { 29 | arr[k] = L[i]; 30 | i++; 31 | } 32 | else { 33 | arr[k] = R[j]; 34 | j++; 35 | } 36 | k++; 37 | } 38 | 39 | /* Copy the remaining elements of L[], if there 40 | are any */ 41 | while (i < n1) { 42 | arr[k] = L[i]; 43 | i++; 44 | k++; 45 | } 46 | 47 | /* Copy the remaining elements of R[], if there 48 | are any */ 49 | while (j < n2) { 50 | arr[k] = R[j]; 51 | j++; 52 | k++; 53 | } 54 | } 55 | 56 | /* l is for left index and r is right index of the 57 | sub-array of arr to be sorted */ 58 | void mergeSort(int arr[], int l, int r) 59 | { 60 | if (l < r) { 61 | // Same as (l+r)/2, but avoids overflow for 62 | // large l and h 63 | int m = l + (r - l) / 2; 64 | 65 | // Sort first and second halves 66 | mergeSort(arr, l, m); 67 | mergeSort(arr, m + 1, r); 68 | 69 | merge(arr, l, m, r); 70 | } 71 | } 72 | 73 | /* UTILITY FUNCTIONS */ 74 | /* Function to print an array */ 75 | void printArray(int A[], int size) 76 | { 77 | int i; 78 | for (i = 0; i < size; i++) 79 | printf("%d ", A[i]); 80 | printf("\n"); 81 | } 82 | 83 | /* Driver program to test above functions */ 84 | int main() 85 | { 86 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 87 | int arr_size = sizeof(arr) / sizeof(arr[0]); 88 | 89 | printf("Given array is \n"); 90 | printArray(arr, arr_size); 91 | 92 | mergeSort(arr, 0, arr_size - 1); 93 | 94 | printf("\nSorted array is \n"); 95 | printArray(arr, arr_size); 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /Sorting Algorithms/Quick Sort.c: -------------------------------------------------------------------------------- 1 | int partition ( int A[],int start ,int end) { 2 | int i = start + 1; 3 | int piv = A[start] ; //make the first element as pivot element. 4 | for(int j =start + 1; j <= end ; j++ ) { 5 | /*rearrange the array by putting elements which are less than pivot 6 | on one side and which are greater that on other. */ 7 | 8 | if ( A[ j ] < piv) { 9 | swap (A[ i ],A [ j ]); 10 | i += 1; 11 | } 12 | } 13 | swap ( A[ start ] ,A[ i-1 ] ) ; //put the pivot element in its proper place. 14 | return i-1; //return the position of the pivot 15 | } 16 | //recursive function Quick_sort : 17 | 18 | void quick_sort ( int A[ ] ,int start , int end ) { 19 | if( start < end ) { 20 | //stores the position of pivot element 21 | int piv_pos = partition (A,start , end ) ; 22 | quick_sort (A,start , piv_pos -1); //sorts the left side of pivot. 23 | quick_sort ( A,piv_pos +1 , end) ; //sorts the right side of pivot. 24 | } 25 | } 26 | //randomized version of the partition function : 27 | int rand_partition ( int A[ ] , int start , int end ) { 28 | //chooses position of pivot randomly by using rand() function . 29 | int random = start + rand( )%(end-start +1 ) ; 30 | 31 | swap ( A[random] , A[start]) ; //swap pivot with 1st element. 32 | return partition(A,start ,end) ; //call the above partition function 33 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Radix Sort.c: -------------------------------------------------------------------------------- 1 | void countsort(int arr[],int n,int place) 2 | { 3 | int i,freq[range]={0}; //range for integers is 10 as digits range from 0-9 4 | int output[n]; 5 | for(i=0;i=0;i--) 10 | { 11 | output[freq[(arr[i]/place)%range]-1]=arr[i]; 12 | freq[(arr[i]/place)%range]--; 13 | } 14 | for(i=0;i 3 | using namespace std; 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | void selectionSort(int arr[], int n) 13 | { 14 | int i, j, min_idx; 15 | 16 | // One by one move boundary of unsorted subarray 17 | for (i = 0; i < n-1; i++) 18 | { 19 | // Find the minimum element in unsorted array 20 | min_idx = i; 21 | for (j = i+1; j < n; j++) 22 | if (arr[j] < arr[min_idx]) 23 | min_idx = j; 24 | 25 | // Swap the found minimum element with the first element 26 | swap(&arr[min_idx], &arr[i]); 27 | } 28 | } 29 | 30 | /* Function to print an array */ 31 | void printArray(int arr[], int size) 32 | { 33 | int i; 34 | for (i=0; i < size; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver program to test above functions 40 | int main() 41 | { 42 | int arr[] = {64, 25, 12, 22, 11}; 43 | int n = sizeof(arr)/sizeof(arr[0]); 44 | selectionSort(arr, n); 45 | cout << "Sorted array: \n"; 46 | printArray(arr, n); 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Sorting Algorithms/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubbleSort(arr): 2 | n = len(arr) 3 | 4 | # Traverse through all array elements 5 | for i in range(n-1): 6 | # range(n) also work but outer loop will repeat one time more than needed. 7 | 8 | # Last i elements are already in place 9 | for j in range(0, n-i-1): 10 | 11 | # traverse the array from 0 to n-i-1 12 | # Swap if the element found is greater 13 | # than the next element 14 | if arr[j] > arr[j+1] : 15 | arr[j], arr[j+1] = arr[j+1], arr[j] 16 | 17 | # Driver code to test above 18 | arr = [64, 34, 25, 12, 22, 11, 90] 19 | 20 | bubbleSort(arr) 21 | 22 | print ("Sorted array is:") 23 | for i in range(len(arr)): 24 | print ("%d" %arr[i]), -------------------------------------------------------------------------------- /Sorting Algorithms/cycleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class cycleSort { 4 | public static void main(String[] args) { 5 | int[] arr= {-4,-1,0,3,10}; 6 | cycle(arr); 7 | } 8 | static void cycle(int[] arr){ 9 | int i= 0; 10 | while (i< arr.length){ 11 | int correct= arr[i]; 12 | if(arr[i] < arr.length && arr[i] != arr[correct]){ 13 | swap(arr, i, correct); 14 | } 15 | else { 16 | i++; 17 | } 18 | } 19 | System.out.println(Arrays.toString(arr)); 20 | } 21 | 22 | static void swap(int[] arr, int first, int second) { 23 | int temp = arr[first]; 24 | arr[first] = arr[second]; 25 | arr[second] = temp; 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Sorting Algorithms/mergesort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | def merge(arr, l, m, r): 7 | n1 = m - l + 1 8 | n2 = r- m 9 | 10 | # create temp arrays 11 | L = [0] * (n1) 12 | R = [0] * (n2) 13 | 14 | # Copy data to temp arrays L[] and R[] 15 | for i in range(0 , n1): 16 | L[i] = arr[l + i] 17 | 18 | for j in range(0 , n2): 19 | R[j] = arr[m + 1 + j] 20 | 21 | # Merge the temp arrays back into arr[l..r] 22 | i = 0 # Initial index of first subarray 23 | j = 0 # Initial index of second subarray 24 | k = l # Initial index of merged subarray 25 | 26 | while i < n1 and j < n2 : 27 | if L[i] <= R[j]: 28 | arr[k] = L[i] 29 | i += 1 30 | else: 31 | arr[k] = R[j] 32 | j += 1 33 | k += 1 34 | 35 | # Copy the remaining elements of L[], if there 36 | # are any 37 | while i < n1: 38 | arr[k] = L[i] 39 | i += 1 40 | k += 1 41 | 42 | # Copy the remaining elements of R[], if there 43 | # are any 44 | while j < n2: 45 | arr[k] = R[j] 46 | j += 1 47 | k += 1 48 | 49 | # l is for left index and r is right index of the 50 | # sub-array of arr to be sorted 51 | def mergeSort(arr,l,r): 52 | if l < r: 53 | 54 | # Same as (l+r)//2, but avoids overflow for 55 | # large l and h 56 | m = (l+(r-1))//2 57 | 58 | # Sort first and second halves 59 | mergeSort(arr, l, m) 60 | mergeSort(arr, m+1, r) 61 | merge(arr, l, m, r) 62 | 63 | 64 | # Driver code to test above 65 | arr = [12, 11, 13, 5, 6, 7] 66 | n = len(arr) 67 | print ("Given array is") 68 | for i in range(n): 69 | print ("%d" %arr[i]), 70 | 71 | mergeSort(arr,0,n-1) 72 | print ("\n\nSorted array is") 73 | for i in range(n): 74 | print ("%d" %arr[i]), 75 | -------------------------------------------------------------------------------- /Sorting Algorithms/selectionsort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Selection 2 | # Sort 3 | import sys 4 | A = [64, 25, 12, 22, 11] 5 | 6 | # Traverse through all array elements 7 | for i in range(len(A)): 8 | 9 | # Find the minimum element in remaining 10 | # unsorted array 11 | min_idx = i 12 | for j in range(i+1, len(A)): 13 | if A[min_idx] > A[j]: 14 | min_idx = j 15 | 16 | # Swap the found minimum element with 17 | # the first element 18 | A[i], A[min_idx] = A[min_idx], A[i] 19 | 20 | # Driver code to test above 21 | print ("Sorted array") 22 | for i in range(len(A)): 23 | print("%d" %A[i]), -------------------------------------------------------------------------------- /binary-search-approaches: -------------------------------------------------------------------------------- 1 | # Problems where its Difficult to figure out if Binary Search can be applied. 2 | 3 | -There are patterns of problems where its little difficult to figure out if binary search can be applied. 4 | -There would be a given array of length (n) and we need to find minimum which satifies contraint on array. 5 | -Runtime of these are normally nLog(m). 6 | 7 | ![link](https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/) 8 | ![link](https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/) 9 | ![link](https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/) 10 | ![link](https://leetcode.com/problems/koko-eating-bananas/) 11 | ![link](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) 12 | 13 | class Solution { 14 | bool isValid(vector& bloomDay, int m, int k, int mid) { 15 | 16 | int count = 0, size = 0; 17 | for (int i = 0; i < bloomDay.size(); i++) { 18 | size = (bloomDay[i] <= mid) ? size+1 : 0; 19 | if (size == k) size = 0, count++; 20 | if (count == m) 21 | return true; 22 | } 23 | 24 | return false; 25 | } 26 | public: 27 | int minDays(vector& bloomDay, int m, int k) { 28 | if(bloomDay.size() == 0 || m == 0 || k == 0) return 0; 29 | if (m * k > bloomDay.size()) return -1; 30 | 31 | int l = INT_MAX, r = INT_MIN; 32 | for (int i = 0; i < bloomDay.size(); i++) { 33 | l = min(l, bloomDay[i]); 34 | r = max(r, bloomDay[i]); 35 | } 36 | 37 | while (l <= r) { 38 | int mid = l + (r-l)/2; 39 | 40 | if (isValid(bloomDay, m, k, mid)) 41 | r = mid-1; 42 | else 43 | l = mid+1; 44 | } 45 | 46 | return l; 47 | } 48 | }; 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | ### Tricky Binary Search 57 | 58 | 59 | 60 | 61 | 62 | 63 | -There are multiple conditions we need to figure out if we need to select left or if we need to select right. 64 | 65 | ![link](https://leetcode.com/problems/find-peak-element/) 66 | ![link](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) 67 | ![link](https://leetcode.com/problems/search-in-rotated-sorted-array/) 68 | ![link](https://leetcode.com/problems/missing-element-in-sorted-array/) 69 | 70 | class Solution { 71 | 72 | int findPeakElementUtil(vector& nums, int l, int r) { 73 | 74 | if (l > r) return -1; 75 | 76 | int m = l + (r-l)/2; 77 | 78 | if (((m > 0) && (nums[m] > nums[m-1])) && 79 | ((m < nums.size()-1) && (nums[m] > nums[m+1]))) 80 | return m; 81 | 82 | if (m == 0 && nums.size() > 1 && nums[m] > nums[m+1]) 83 | return m; 84 | 85 | if ((m == nums.size()-1) && (nums[m] > nums[m-1])) 86 | return m; 87 | 88 | int left = findPeakElementUtil(nums, l, m-1); 89 | int right = findPeakElementUtil(nums, m+1, r); 90 | 91 | if (left != -1) 92 | return left; 93 | else 94 | return right; 95 | } 96 | public: 97 | int findPeakElement(vector& nums) { 98 | 99 | int n = nums.size(); 100 | 101 | if (n == 1) return 0; 102 | 103 | return findPeakElementUtil(nums, 0, n-1); 104 | } 105 | }; 106 | 107 | 108 | 109 | 110 | 111 | ### Simple Binary Search 112 | 113 | 114 | 115 | 116 | 117 | 118 | ![link](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) 119 | ![link](https://leetcode.com/problems/missing-element-in-sorted-array/) 120 | ![link](https://leetcode.com/problems/peak-index-in-a-mountain-array/) 121 | ![link](https://leetcode.com/problems/h-index-ii/) 122 | ![link](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) 123 | ![link](https://leetcode.com/problems/first-bad-version/) 124 | 125 | class Solution { 126 | public: 127 | char nextGreatestLetter(vector& letters, char target) { 128 | 129 | int n = letters.size(); 130 | int l = 0, r = n-1; 131 | 132 | if (target >= letters[n-1] || target < letters[0]) 133 | return letters[0]; 134 | 135 | int m = 0; 136 | while (l <= r) { 137 | m = l + (r-l)/2; 138 | 139 | if (m > 0 && (target >= letters[m-1] && target < letters[m])) 140 | return letters[m]; 141 | else if (target >= letters[m]) 142 | l = m+1; 143 | else 144 | r = m-1; 145 | } 146 | 147 | return letters[m]; 148 | } 149 | }; 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | ### Using C++ STL upper bound for binary search 158 | 159 | 160 | 161 | 162 | 163 | 164 | ![link](https://leetcode.com/problems/time-based-key-value-store/) 165 | ![link](https://leetcode.com/problems/online-election/) 166 | ![link](https://leetcode.com/problems/random-pick-with-weight/) 167 | ![link](https://leetcode.com/problems/find-right-interval/) 168 | 169 | For Java script, built in api is not available. Sharing @claytonjwong approach. Thanks to him. 170 | ![link](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/692931/Javascript-and-C%2B%2B-solutions) 171 | ![link](https://gist.github.com/claytonjwong/53bd1c1489b12eccad176addb8afd8e0) 172 | 173 | class TimeMap { 174 | unordered_map>hm; 175 | public: 176 | /** Initialize your data structure here. */ 177 | TimeMap() { 178 | 179 | } 180 | 181 | void set(string key, string value, int timestamp) { 182 | hm[key].insert({timestamp, value}); 183 | } 184 | 185 | string get(string key, int timestamp) { 186 | auto it = hm[key].upper_bound(timestamp); 187 | return (it == hm[key].begin()) ? "" : prev(it)->second; 188 | } 189 | }; 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | ### Binary search based on condition on 2 arrays 198 | ![link](https://leetcode.com/problems/median-of-two-sorted-arrays/) 199 | 200 | class Solution { 201 | public: 202 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 203 | 204 | int n = nums1.size(); 205 | int m = nums2.size(); 206 | 207 | if (n > m) 208 | return findMedianSortedArrays(nums2, nums1); 209 | 210 | int k = (n+m-1)/2; 211 | 212 | int l = 0; 213 | int r = min(k, n); 214 | 215 | while (l < r) { 216 | int mid1 = l + (r-l)/2; 217 | int mid2 = k-mid1; 218 | 219 | if (nums1[mid1] > nums2[mid2]) 220 | r = mid1; 221 | else 222 | l = mid1+1; 223 | } 224 | 225 | /* if (n+m) is odd, the median is the larger one between nums1[l-1] and nums2[k-l] */ 226 | int a = max(l >= 1 ? nums1[l-1] : INT_MIN, k >= l ? nums2[k-l] : INT_MIN); 227 | if ((n+m) % 2 != 0) 228 | return a; 229 | 230 | /* in case (n+m) is even, take the average of mid 2 elements */ 231 | int b = min(l < n ? nums1[l] : INT_MAX, k-l+1 < m ? nums2[k-l+1] : INT_MAX); 232 | 233 | return (a+b)/2.0; 234 | } 235 | }; 236 | -------------------------------------------------------------------------------- /bst_traversal.c: -------------------------------------------------------------------------------- 1 | # include 2 | # include 3 | # include 4 | 5 | typedef struct BST { 6 | int data; 7 | struct BST *lchild, *rchild; 8 | } node; 9 | 10 | void insert(node *, node *); 11 | void inorder(node *); 12 | void preorder(node *); 13 | void postorder(node *); 14 | node *search(node *, int, node **); 15 | 16 | void main() { 17 | int choice; 18 | char ans = 'N'; 19 | int key; 20 | node *new_node, *root, *tmp, *parent; 21 | node *get_node(); 22 | root = NULL; 23 | 24 | 25 | printf("\nProgram For Binary Search Tree "); 26 | do { 27 | printf("\n1.Create"); 28 | printf("\n2.Search"); 29 | printf("\n3.Recursive Traversals"); 30 | printf("\n4.Exit"); 31 | printf("\nEnter your choice :"); 32 | scanf("%d", &choice); 33 | 34 | switch (choice) { 35 | case 1: 36 | do { 37 | new_node = get_node(); 38 | printf("\nEnter The Element "); 39 | scanf("%d", &new_node->data); 40 | 41 | if (root == NULL) /* Tree is not Created */ 42 | root = new_node; 43 | else 44 | insert(root, new_node); 45 | 46 | printf("\nWant To enter More Elements?(y/n)"); 47 | ans = getch(); 48 | } while (ans == 'y'); 49 | break; 50 | 51 | case 2: 52 | printf("\nEnter Element to be searched :"); 53 | scanf("%d", &key); 54 | 55 | tmp = search(root, key, &parent); 56 | printf("\nParent of node %d is %d", tmp->data, parent->data); 57 | break; 58 | 59 | case 3: 60 | if (root == NULL) 61 | printf("Tree Is Not Created"); 62 | else { 63 | printf("\nThe Inorder display : "); 64 | inorder(root); 65 | printf("\nThe Preorder display : "); 66 | preorder(root); 67 | printf("\nThe Postorder display : "); 68 | postorder(root); 69 | } 70 | break; 71 | } 72 | } while (choice != 4); 73 | } 74 | /* 75 | Get new Node 76 | */ 77 | node *get_node() { 78 | node *temp; 79 | temp = (node *) malloc(sizeof(node)); 80 | temp->lchild = NULL; 81 | temp->rchild = NULL; 82 | return temp; 83 | } 84 | /* 85 | This function is for creating a binary search tree 86 | */ 87 | void insert(node *root, node *new_node) { 88 | if (new_node->data < root->data) { 89 | if (root->lchild == NULL) 90 | root->lchild = new_node; 91 | else 92 | insert(root->lchild, new_node); 93 | } 94 | 95 | if (new_node->data > root->data) { 96 | if (root->rchild == NULL) 97 | root->rchild = new_node; 98 | else 99 | insert(root->rchild, new_node); 100 | } 101 | } 102 | /* 103 | This function is for searching the node from 104 | binary Search Tree 105 | */ 106 | node *search(node *root, int key, node **parent) { 107 | node *temp; 108 | temp = root; 109 | while (temp != NULL) { 110 | if (temp->data == key) { 111 | printf("\nThe %d Element is Present", temp->data); 112 | return temp; 113 | } 114 | *parent = temp; 115 | 116 | if (temp->data > key) 117 | temp = temp->lchild; 118 | else 119 | temp = temp->rchild; 120 | } 121 | return NULL; 122 | } 123 | /* 124 | This function displays the tree in inorder fashion 125 | */ 126 | void inorder(node *temp) { 127 | if (temp != NULL) { 128 | inorder(temp->lchild); 129 | printf("%d", temp->data); 130 | inorder(temp->rchild); 131 | } 132 | } 133 | /* 134 | This function displays the tree in preorder fashion 135 | */ 136 | void preorder(node *temp) { 137 | if (temp != NULL) { 138 | printf("%d", temp->data); 139 | preorder(temp->lchild); 140 | preorder(temp->rchild); 141 | } 142 | } 143 | 144 | /* 145 | This function displays the tree in postorder fashion 146 | */ 147 | void postorder(node *temp) { 148 | if (temp != NULL) { 149 | postorder(temp->lchild); 150 | postorder(temp->rchild); 151 | printf("%d", temp->data); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /house_robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n=nums.size(); 5 | vector dp(n+1,0); 6 | dp[1]=nums[0]; 7 | for(int i=2;i<=n;i++) 8 | dp[i]=max(dp[i-1],nums[i-1]+dp[i-2]); 9 | 10 | 11 | return dp[n]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /leetcode problems/build_array_from_permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector buildArray(vector& nums) { 4 | vector ans(nums.size(),0); 5 | for(int i=0;i& distance) { 2 | unordered_map mp; 3 | for(int i=0;i divideString(string s, int k, char fill) { 4 | vector vect; 5 | int ctr=0; 6 | string str=""; 7 | for(int i=0;i targetIndices(vector& nums, int target) { 4 | vector vect; 5 | sort(nums.begin(),nums.end()); 6 | for(int i=0;i& words) { 4 | for(int i=0;i& nums) { 4 | int maxm=0,minm=100000; 5 | for(int i=0;i>& logs) { 4 | int maxm=0,year; 5 | for(int i=1950;i<=2050;i++) 6 | { 7 | int ctr=0; 8 | for(int j=0;j=logs[j][0] && imaxm) 14 | { 15 | maxm=ctr; 16 | year=i; 17 | } 18 | } 19 | return year; 20 | } 21 | }; -------------------------------------------------------------------------------- /leetcode problems/rings_and_rods.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPoints(string rings) { 4 | unordered_map mp; 5 | int ctr=0; 6 | for(int i=1;i& nums, int k) 4 | { 5 | int n=nums.size(); 6 | vector v; 7 | if(n>1) 8 | { 9 | k=k%n; 10 | for(int i=n-k;i sortEvenOdd(vector& nums) { 4 | vector vect1,vect2; 5 | for(int i=0;i& colors) { 4 | int n=colors.size(); 5 | int i=0,j=n-1; 6 | if(colors[i]!=colors[j]) 7 | return j-i; 8 | int maxm=0; 9 | j=0; 10 | for(int i=n-1;i>=0;i--) 11 | { 12 | if(colors[i]!=colors[j]) 13 | { 14 | maxm=max(maxm,i-j); 15 | break; 16 | } 17 | } 18 | j=n-1; 19 | for(int i=0;i>&dp){ 4 | // base condition 5 | if(i<0)return j<0; 6 | if(j<0){ 7 | for(int idx=0;idx<=i;idx++){ 8 | if(s1[idx]!='*')return 0; 9 | } 10 | return true; 11 | } 12 | //check the cache 13 | if(dp[i][j]!=-1)return dp[i][j]; 14 | //match 15 | if(s1[i]==s2[j] || s1[i]=='?') 16 | return dp[i][j]=solve(s1,s2,i-1,j-1,dp); 17 | // if s1[i] is "*". we can '*' use any number of times ( 0 or more) 18 | if(s1[i]=='*') 19 | return dp[i][j]=solve(s1,s2,i-1,j,dp) || solve(s1,s2,i,j-1,dp); 20 | return dp[i][j]=0; 21 | } 22 | bool isMatch(string s, string p) { 23 | int m=p.size(); 24 | int n=s.size(); 25 | vector>dp(m+1,vector(n+1,-1)); 26 | return solve(p,s,m,n,dp); 27 | } 28 | }; 29 | --------------------------------------------------------------------------------