├── Codechef ├── DSA LEARNING SERIES │ ├── 01 Life, the Universe, and Everything.cpp │ └── 02 Reverse The Number.cpp └── IMG │ └── cp.png ├── GeeksforGeeks ├── FINAL450_Love-Babbar │ ├── 01 Reverse the array.cpp │ └── Readme.md ├── HackerRank │ └── SRM CCC Contest.cpp ├── Missing number in array.cpp └── Trailing zeroes in factorial.cpp ├── Leetcode ├── Easy │ ├── 01 Two Sum.cpp │ ├── 01 two_sum.java │ ├── 02 Contains Duplicate.cpp │ ├── 03 Missing Number.cpp │ ├── 04 Find All Numbers Disappeared in an Array.cpp │ ├── 05 Two Sum II - Input array is sorted.cpp │ ├── 06 Remove Duplicates from Sorted Array.cpp │ ├── 07 Remove element.cpp │ ├── 08 Search Insert Position.cpp │ ├── 09 Maximum Subarray.cpp │ ├── 10 Plus One.cpp │ ├── 11 Merge Sorted Array.cpp │ ├── 12 Pascal's Tringle.cpp │ ├── 13 Pascal's Triangle II.cpp │ ├── 14 Best Time to Buy and Sell Stock.cpp │ ├── 15 Single Number.cpp │ ├── 16 Product of array except self.cpp │ ├── 17 Merge Two Sorted Lists.cpp │ ├── 18 Palindrome Linked List.cpp │ ├── 19 Reverse Linked List.cpp │ ├── 20 Delete Node in a Linked List.cpp │ ├── 21 Remove Linked List Elements.cpp │ ├── 22 Linked List Cycle.cpp │ ├── 23 Middle of the Linked List.cpp │ ├── 24 Remove Duplicates from Sorted List.cpp │ ├── 25 Convert Binary Number in a Linked List to Integer.cpp │ ├── 26 Intersection of Two Linked Lists.cpp │ ├── 27 Majority Element.cpp │ ├── 28 Majority element 2ndsol.cpp │ ├── 29 Move zeores.cpp │ ├── 30 Reverse the string.cpp │ ├── 31 Reverse Only Letters.cpp │ ├── 32 To Lower Case.cpp │ ├── 33 Reverse Integer.cpp │ ├── 34 Fizz Buzz.cpp │ ├── 35 First Unique Character in a String.cpp │ ├── 36 Power of Three.cpp │ ├── 37 1-bit and 2-bit Characters.cpp │ ├── 38 Add to Array-Form of Integer.cpp │ ├── 39 Array Partition I.cpp │ ├── 40 Next Greater Element I.cpp │ ├── 41 Binary Tree Inorder Traversal.cpp │ ├── 42 Binary Search.cpp │ ├── 43 First Bad Version.cpp │ ├── 44 Guess Number Higher or Lower.cpp │ ├── 45 Maximum Depth of Binary Tree.cpp │ ├── 46 Balanced Binary Tree.cpp │ ├── 47 Palindrome Number.cpp │ ├── 48 Valid Parentheses.cpp │ ├── 49 Roman to Integer.cpp │ ├── Add Two Numbers.java │ ├── Longest common prefix.java │ ├── Remove Element.java │ ├── Roman to Integer.java │ ├── Search Insert Position.java │ ├── Sqrt(x).java │ └── valid parenthesis.java ├── Hard │ ├── 01 First Missing Positive.cpp │ ├── 02 Longest Consecutive Sequence.cpp │ ├── 03 Largest Rectangle in Histogram.cpp │ ├── 04 Scramble String.cpp │ ├── 05 Sliding Window Maximum.cpp │ ├── 06 Median of Two Sorted Arrays.cpp │ ├── 07 Longest Valid Parentheses.cpp │ ├── 08 Regular Expression Matching.cpp │ └── 09 Trapping Rain Water.cpp └── Medium │ ├── 01 Find the duplicate number.cpp │ ├── 02 Find All Duplicates in an Array.cpp │ ├── 03 Fibonacci.cpp │ ├── 04 3Sum.cpp │ ├── 05 Next Permutation.cpp │ ├── 06 Set Matrix Zeros.cpp │ ├── 07 Spiral Matrix.cpp │ ├── 08 Rotate Image.cpp │ ├── 09 Add two numbers.cpp │ ├── 10 Longest Substring Without Repeating Characters.cpp │ ├── 11 Minimum Size Subarray Sum.cpp │ ├── 12 Longest Palindromic Subsequence.cpp │ ├── 13 Next Greater Element II.cpp │ ├── 14 Online Stock Span.cpp │ ├── 15 Kth Largest Element in an Array.cpp │ ├── 16 Sort an Array.cpp │ ├── 17 Find First and Last Position of Element in Sorted Array.cpp │ ├── 18 Find Minimum in Rotated Sorted Array.cpp │ ├── 19 Search a 2D Matrix.cpp │ ├── 20 Search a 2D Matrix II.cpp │ ├── 21 Find Peak Element.cpp │ ├── 22 Peak Index in a Mountain Array.cpp │ ├── 23 Sort Colors.cpp │ ├── 24 Merge Intervals.cpp │ ├── 25 pow(x,n).cpp │ ├── 26 4Sum.cpp │ ├── 27 Swap Nodes in Pairs.cpp │ ├── 28 Integer to Roman.cpp │ └── Longest Substring Without Repeating Characters.java ├── README.md └── SDE sheet solution ├── Day 1 ├── 01 Sort an array of 0’s 1’s 2’s without using extra space or sorting algo.cpp ├── 02 Find Missing And Repeating.cpp ├── 03 Merge two sorted Arrays without extra space.cpp ├── 04 Kadane’s Algorithm.cpp ├── 05 Merge Overlapping Subintervals.cpp └── 06 Find the duplicate in an array of N+1 integers.cpp ├── Day 2 ├── 01 Set Matrix zeros.cpp ├── 02 Pascal's Triangle.cpp ├── 03 Next permutation.cpp ├── 04 Count Inversions.cpp ├── 05 Best Time to Buy and Sell Stock II.cpp ├── 06 Stock Buy and Sell.cpp └── 07 Rotate matrix.cpp ├── Day 3 ├── 01 Search in 2d matrix.cpp ├── 02 Pow(x,n).cpp ├── 03 Majority Element.cpp ├── 04 Majority Element II.cpp ├── 05 Unique Paths.cpp └── 06 Reverse Pairs.cpp ├── Day 4 ├── 01 Two Sum.cpp ├── 02 4Sum.cpp └── 03 Longest Consecutive Sequence.cpp ├── Day 5 ├── 01 Reverse a LinkedList.cpp ├── 02 Find middle of LinkedList.cpp ├── 03 Merge Two Sorted Lists.cpp └── 04 Remove Nth Node From End of List.cpp └── Day 6 ├── 01 Intersection of Two Linked Lists.cpp ├── 02 Linked List Cycle.cpp └── 04 Check if a LinkedList is palindrome or not.cpp /Codechef/DSA LEARNING SERIES/01 Life, the Universe, and Everything.cpp: -------------------------------------------------------------------------------- 1 | /*Your program is to use the brute-force approach in order to find the Answer 2 | to Life, the Universe, and Everything. More precisely… rewrite small numbers from 3 | input to output. Stop processing input after reading in the number 42. 4 | All numbers at input are integers of one or two digits. 5 | 6 | Sample Input: 7 | 1 8 | 2 9 | 88 10 | 42 11 | 99 12 | Sample Output: 13 | 1 14 | 2 15 | 88 16 | */ 17 | 18 | #include 19 | using namespace std; 20 | 21 | int main() { 22 | int i; 23 | int A[100]; 24 | while (true) 25 | { 26 | cin>>A[i]; 27 | if (A[i]==42) 28 | { 29 | break; 30 | } 31 | else 32 | { 33 | cout< 44 | using namespace std; 45 | 46 | int main() { 47 | int i; 48 | int A[INT_MAX]; 49 | for (i=0;i>A[i]; 52 | if (A[i]==42) 53 | { 54 | break; 55 | } 56 | else 57 | { 58 | cout< 27 | using namespace std; 28 | 29 | int main() { 30 | int no,i; 31 | cin>>no; 32 | int A[no]; 33 | for (i=0;i>A[i]; 36 | int temp= A[i]; 37 | A[i]=0; 38 | while(temp!=0) 39 | { 40 | int rem= temp%10; 41 | A[i]=A[i]*10+rem; 42 | temp=temp/10; 43 | } 44 | } 45 | for (i=0;i 4 | #include 5 | #include 6 | #include 7 | 8 | int main() { 9 | 10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 11 | char str[100001],rev[100001]; 12 | int i,j=0; 13 | scanf("%[^\n]s",str); 14 | i=0; 15 | while(str[i]) 16 | { 17 | if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U') 18 | { 19 | rev[j]=str[i]; 20 | j++; 21 | } 22 | i++; 23 | } 24 | j--; 25 | i=0; 26 | while(str[i]) 27 | { 28 | if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U') 29 | { 30 | printf("%c",rev[j]); 31 | j--; 32 | } 33 | else 34 | printf("%c",str[i]); 35 | 36 | i++; 37 | } 38 | 39 | 40 | return 0; 41 | } 42 | 43 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 44 | 45 | 46 | O 02 - Printing the Linked List in Reverse 47 | 48 | void ReversePrint(LinkedListNode* head) 49 | { 50 | LinkedListNode* temp=head; 51 | if(temp==NULL) 52 | return; 53 | else 54 | { 55 | ReversePrint(temp->next); 56 | printf("%d ",temp->val); 57 | } 58 | } 59 | 60 | 61 | ------------------------------------------------------------------------------------------------------------------------------------------ 62 | 63 | O M01 - Looped List 64 | 65 | #include "stdio.h" 66 | #include "stdlib.h" 67 | #include "math.h" 68 | #include "string.h" 69 | 70 | struct Node{ 71 | int value; 72 | struct Node* next; 73 | }; 74 | typedef struct Node Node; 75 | Node links[105]; 76 | 77 | void add_link(int from, int to){ 78 | links[from].next = &links[to]; 79 | } 80 | void set_value(int index, int val){ 81 | links[index].value = val; 82 | } 83 | 84 | 85 | //BODY BEGINS HERE 86 | int find_loop(Node* head) 87 | { 88 | Node* f=head; 89 | Node* s=head; 90 | while(f!=NULL && f->next!=NULL) 91 | { 92 | s=s->next; 93 | f=f->next->next; 94 | if(s==f) 95 | return 1; 96 | } 97 | return 0; 98 | } 99 | //BODY ENDS HERE 100 | 101 | //TAIL BEGINS HERE 102 | int main(){ 103 | int i,n,m,tmp,tmp1,tmp2; 104 | scanf("%d %d", &n, &m); 105 | for(i = 0; i < n; i++){ 106 | scanf("%d", &tmp); 107 | set_value(i, tmp); 108 | } 109 | for(i = 0; i < m; i++){ 110 | scanf("%d %d", &tmp1, &tmp2); 111 | add_link(tmp1,tmp2); 112 | } 113 | if(find_loop(&links[0]) == 1) printf("Loop Found"); 114 | else printf("No Loop Found"); 115 | return 0; 116 | } 117 | 118 | ------------------------------------------------------------------------------------------------- 119 | 120 | 121 | O M02 - Comparing Two Linked Lists 122 | 123 | #include 124 | #include 125 | #include 126 | #include 127 | #include 128 | #include 129 | #include 130 | typedef struct LinkedListNode LinkedListNode; 131 | 132 | struct LinkedListNode { 133 | int val; 134 | LinkedListNode *next; 135 | }; 136 | 137 | LinkedListNode* _insert_node_into_singlylinkedlist(LinkedListNode *head, LinkedListNode *tail, int val) { 138 | if(head == NULL) { 139 | head = (LinkedListNode *) (malloc(sizeof(LinkedListNode))); 140 | head->val = val; 141 | head->next = NULL; 142 | tail = head; 143 | } 144 | else { 145 | LinkedListNode *node = (LinkedListNode *) (malloc(sizeof(LinkedListNode))); 146 | node->val = val; 147 | node->next = NULL; 148 | tail->next = node; 149 | tail = tail->next; 150 | } 151 | return tail; 152 | } 153 | 154 | //BODY STARTS HERE 155 | 156 | 157 | /* 158 | * Complete the function below. 159 | */ 160 | /* 161 | For your reference: 162 | LinkedListNode { 163 | int val; 164 | LinkedListNode *next; 165 | }; 166 | */ 167 | int compare(LinkedListNode* headA, LinkedListNode* headB) 168 | { 169 | LinkedListNode* x=headA; 170 | LinkedListNode* y=headB; 171 | while( x && y ) // while (x!=NULL && y!=NULL) 172 | { 173 | if(x->val != y->val) 174 | return 0; 175 | x=x->next; 176 | y=y->next; 177 | } 178 | if(x==NULL && y==NULL) 179 | return 1; 180 | else 181 | return 0; 182 | } 183 | 184 | 185 | //BODY ENDS HERE 186 | 187 | int main() 188 | { 189 | FILE *f = stdout; 190 | char *output_path = getenv("OUTPUT_PATH"); 191 | if (output_path) { 192 | f = fopen(output_path, "w"); 193 | } 194 | 195 | int res; 196 | int headA_size = 0; 197 | 198 | LinkedListNode* headA = NULL; 199 | LinkedListNode* headA_tail = NULL; 200 | 201 | scanf("%d\n", &headA_size); 202 | for(int i = 0; i < headA_size; i++) { 203 | int headA_item; 204 | scanf("%d", &headA_item); 205 | headA_tail = _insert_node_into_singlylinkedlist(headA, headA_tail, headA_item); 206 | 207 | if(i == 0) { 208 | headA = headA_tail; 209 | } 210 | } 211 | 212 | 213 | int headB_size = 0; 214 | 215 | LinkedListNode* headB = NULL; 216 | LinkedListNode* headB_tail = NULL; 217 | 218 | scanf("%d\n", &headB_size); 219 | for(int i = 0; i < headB_size; i++) { 220 | int headB_item; 221 | scanf("%d", &headB_item); 222 | headB_tail = _insert_node_into_singlylinkedlist(headB, headB_tail, headB_item); 223 | 224 | if(i == 0) { 225 | headB = headB_tail; 226 | } 227 | } 228 | 229 | 230 | res = compare(headA, headB); 231 | fprintf(f, "%d\n", res); 232 | 233 | fclose(f); 234 | return 0; 235 | } 236 | 237 | ---------------------------------------------------------------------------------------------------------------------------------- 238 | 239 | 02x00 Maximum Element in the Stack 240 | 241 | #include 242 | #include 243 | #include 244 | #include 245 | int stack[10000001],maxstack[10000001],top=-1,mtop=-1; 246 | int main() 247 | { 248 | int n; 249 | scanf("%d",&n); 250 | while(n--) 251 | { 252 | int ch; 253 | scanf("%d",&ch); 254 | if(ch==1) 255 | { 256 | int x; 257 | scanf("%d",&x); 258 | 259 | if(mtop==-1 || x>=maxstack[mtop]) 260 | maxstack[++mtop]=x; 261 | 262 | stack[++top]=x; 263 | } 264 | else if(ch==2) 265 | { 266 | if(stack[top]==maxstack[mtop]) 267 | mtop--; 268 | 269 | top--; 270 | } 271 | else 272 | printf("%d\n",maxstack[mtop]); 273 | } 274 | 275 | return 0; 276 | } 277 | --------------------------------------------------------------------------------------------------------------------------------------------- 278 | 279 | 02x04 Captain Tsubasa and his Fest 280 | 281 | #include 282 | #include 283 | #include 284 | #include 285 | long int stack[1000000],top=-1,t,n,id,i; 286 | char ch[10]; 287 | void push(long int id) 288 | { 289 | stack[++top]=id; 290 | } 291 | long int pop() 292 | { 293 | long int a=stack[top]; 294 | top--; 295 | return a; 296 | } 297 | void swap() 298 | { 299 | long int x=pop(); 300 | long int y=pop(); 301 | push(x); 302 | push(y); 303 | } 304 | int main() { 305 | 306 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 307 | scanf("%ld",&t); 308 | while(t--) 309 | { 310 | scanf("%ld %ld",&n,&id); 311 | push(id); 312 | for(i=1;i<=n;i++) 313 | { 314 | scanf("%s",ch); 315 | if(ch[0]=='P') 316 | { 317 | scanf("%ld",&id); 318 | push(id); 319 | } 320 | else 321 | { 322 | swap(); 323 | } 324 | } 325 | printf("Player %ld\n",stack[top]); 326 | } 327 | return 0; 328 | } 329 | --------------------------------------------------------------------------------------------------------------------------- 330 | 331 | 02x03 - The MaxMin Card Game 332 | 333 | #include 334 | #include 335 | #include 336 | #include 337 | int stack[100000],minstack[100000],maxstack[100000],top=-1,mintop=-1,maxtop=-1; 338 | int n,x; 339 | char ch[10]; 340 | void push(int x) 341 | { 342 | if(mintop==-1 || x<=minstack[mintop]) 343 | minstack[++mintop]=x; 344 | if(maxtop==-1 || x>=maxstack[maxtop]) 345 | maxstack[++maxtop]=x; 346 | stack[++top]=x; 347 | } 348 | void pop() 349 | { 350 | if(top==-1) 351 | printf("Invalid\n"); 352 | else 353 | { 354 | if(stack[top]==minstack[mintop]) 355 | mintop--; 356 | if(stack[top]==maxstack[maxtop]) 357 | maxtop--; 358 | top--; 359 | } 360 | } 361 | void min() 362 | { 363 | if(top==-1) 364 | printf("Invalid\n"); 365 | else 366 | printf("%d\n",minstack[mintop]); 367 | } 368 | void max() 369 | { 370 | if(top==-1) 371 | printf("Invalid\n"); 372 | else 373 | printf("%d\n",maxstack[maxtop]); 374 | } 375 | int main() { 376 | 377 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 378 | scanf("%d",&n); 379 | while(n--) 380 | { 381 | scanf("%s",ch); 382 | if(ch[0]=='A') 383 | { 384 | scanf("%d",&x); 385 | push(x); 386 | } 387 | else if(ch[0]=='R') 388 | pop(); 389 | else if(ch[6]=='n') 390 | min(); 391 | else 392 | max(); 393 | } 394 | return 0; 395 | } 396 | -------------------------------------------------------------- 397 | 398 | P 301 - Shortest Man on the Team 399 | 400 | 401 | #include 402 | #include 403 | #include 404 | #include 405 | 406 | int main() { 407 | 408 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 409 | int n,minIndex,i; 410 | scanf("%d",&n); 411 | int a[n]; 412 | for(i=0;ia[i]) 418 | minIndex=i; 419 | } 420 | int t=a[0]; 421 | a[0]=a[minIndex]; 422 | a[minIndex]=t; 423 | for(i=0;i 433 | #include 434 | #include 435 | #include 436 | 437 | int main() { 438 | 439 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 440 | int n,minIndex,i,k,j; 441 | scanf("%d",&n); 442 | int a[n]; 443 | for(i=0;ia[i]) 452 | minIndex=i; 453 | } 454 | int t=a[j]; 455 | a[j]=a[minIndex]; 456 | a[minIndex]=t; 457 | } 458 | for(i=0;i 2 | using namespace std; 3 | class Solution 4 | { 5 | public: 6 | int MissingElememnt (vector < int >&array, int n) 7 | { 8 | int actualsum = 0, sum = 0, res = 0; 9 | for (int i = 0; i <= n; i++) 10 | { 11 | actualsum += i; 12 | } 13 | for (int j = 0; j < n - 1; j++) 14 | { 15 | sum += array[j]; 16 | } 17 | res = actualsum - sum; 18 | return res; 19 | } 20 | }; 21 | 22 | int 23 | main () 24 | { 25 | int n; 26 | cin >> n; 27 | vector < int >array (n - 1); 28 | for (int i = 0; i < n - 1; i++) 29 | { 30 | cin >> array[i]; 31 | } 32 | Solution obj; 33 | cout << obj.MissingElememnt (array, n) << endl; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /GeeksforGeeks/Trailing zeroes in factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int trailingzero(int N){ 7 | int count=0; 8 | if (N<=0) 9 | return -1; 10 | for (int i=5;N/i>=1;i*=5){ 11 | count+=N/i; 12 | } 13 | return count; 14 | 15 | } 16 | }; 17 | 18 | int main (){ 19 | int N; 20 | cin>>N; 21 | Solution obj; 22 | cout << obj.trailingzero(N)< twoSum(vector& nums, int target) { 8 | unordered_map hmap; 9 | for (int i=0;i twoSum(vector& nums, int target) { 23 | for (int i=0;i twoSum(vector& nums, int target) { 41 | //Key is the number and value is its index in the vector. 42 | unordered_map hash; 43 | vector res; 44 | for (int i=0;i 62 | #include 63 | 64 | using namespace std; 65 | 66 | // ---------------------------------------------------------- O(n*m) 67 | class Solution { 68 | public: 69 | vector twoSum(vector& nums, int target) { 70 | for (int i=0;i twoSum(vector& nums, int target) { 86 | int n= nums.size(); 87 | unordered_map hmap; 88 | vector ans; 89 | for (int i=0;i twoSum(vector& nums, int target) { 107 | vector twoSumAns; 108 | for (int i = 0; i < nums.size(); i++) { 109 | for (int j = nums.size() - 1; j > i; j--) { 110 | if (nums[i] + nums[j] == target) { 111 | twoSumAns.push_back(i); 112 | twoSumAns.push_back(j); 113 | } 114 | } 115 | } 116 | return twoSumAns; 117 | } 118 | }; 119 | void PrintVector(vector& input) { 120 | for (int i = 0; i < input.size(); i++) { 121 | cout << input[i] << " "; 122 | } 123 | cout << endl; 124 | } 125 | 126 | int main() { 127 | Solution solution; 128 | vector nums = {2,7,11,15}; 129 | int Sum = 9; 130 | /* vector nums = { 3,2,4 }; 131 | int Sum = 6;*/ 132 | vector result = solution.twoSum(nums, Sum); 133 | PrintVector(result); 134 | } 135 | 136 | 137 | 138 | ----------------------------------------------------------------------------------------------------------------------- 139 | 140 | class Solution { 141 | public: 142 | vector twoSum(vector& nums, int target) { 143 | int num1; // make a variable for finding the element 144 | for (int i = 0; i < nums.size(); i++) // iterate through the vector 145 | { 146 | num1 = target - nums[i]; // we will get the 2nd item to bve find 147 | for (int k = i+1; k < nums.size(); k++ ) // for finding the position 148 | { 149 | if(nums[k] == num1) 150 | { 151 | return {i,k}; // just take both the subscript 152 | } 153 | } 154 | } 155 | return {}; 156 | } 157 | }; 158 | // ------------------------------------------------------------------------------------------------------------ 159 | 160 | 161 | class Solution { 162 | public: 163 | std::vector twoSum(vector& nums, int target) { 164 | 165 | //map for finding the complement of current number in the vector 166 | std::unordered_map hashmap; 167 | 168 | //loop for checking if the complement of the current integer exist in the map 169 | for(int i = 0; i < nums.size(); i++){ 170 | //if complement has found, return current index and index of compliment 171 | //index of complement is its value in the map 172 | //with C++20, mappy.contains would probably been better 173 | if(hashmap.count(target-nums[i])){ 174 | //return the index of the current integer in the vector, and the index of the complement 175 | return {i,(hashmap[target - nums[i]])}; 176 | } 177 | //if complement has not been passed by yet, modify the complement's value with its index 178 | hashmap[nums[i]] = i; 179 | } 180 | //return empty vector if no integers answer found 181 | return {}; 182 | } 183 | }; 184 | 185 | ------------------------------------------------------------------------------------------------------------------ 186 | 187 | class Solution { 188 | public: 189 | vector twoSum(vector& nums, int target) { 190 | unordered_map hmap; 191 | for (int i=0;i map = new HashMap(); 206 | 207 | for(int i = 0; i < nums.length; i++) 208 | map.put(nums[i], i); 209 | 210 | for(int i = 0; i < nums.length; i++) 211 | if(map.containsKey(target - nums[i]) && i != map.get(target - nums[i])) 212 | return new int[] {i, map.get(target - nums[i])}; 213 | 214 | return new int[2]; 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /Leetcode/Easy/01 two_sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | int index[] = {-1,-1}; 4 | for (int i=0; i& nums) // creating a vector varible nums 5 | { 6 | sort(nums.begin(), nums.end()); // sorting the vector 7 | int n = nums.size(); // storing the size of the vector in n 8 | 9 | for(int i = 1; i < n; i++) // iterating through the whole vector 10 | { 11 | if(nums[i] == nums[i-1]) // if duplicate found then return true else return false 12 | return true; 13 | } 14 | 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode/Easy/03 Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { // creating the variable by the name of nums as a vector 4 | int result = 0; 5 | for (int i = 0; i < nums.size(); i++) { // iterating through the vector 6 | result =result + (i+1)- nums[i]; // getting the missing number and then returning it 7 | } 8 | return result; 9 | } 10 | }; 11 | ------------------------------------------------- 12 | 13 | class Solution { 14 | public: 15 | int missingNumber(vector& nums) { 16 | int n=nums.size(); 17 | int xor1=0; 18 | int xor2=0; 19 | for (int i=0;i findDisappearedNumbers(vector& nums) { 4 | int no= nums.size(); // taking the size of the vector 5 | vector result; // creating a vector variable 6 | 7 | //In the first for-loop, I am taking the number and finding the index and then making the element at that index negative. 8 | 9 | for (int i=0;i0) 13 | nums[position]=-nums[position];// now make all the elements present in the vector as -ve 14 | } 15 | 16 | 17 | for (int i=0;i0) // the number which is not there in vector is ovious that will be +ve so keep that in the vector 20 | result.push_back(i+1); 21 | } 22 | 23 | return result; 24 | 25 | 26 | } 27 | }; 28 | 29 | /* Suppose I have A[] as {2, 4, 1, 4}. Now I am taking each element and making the number at that index negative. 30 | First iteration, I take A[0] = 2. Index = abs(A[0])-1 = 2 - 1 = 1. Now I am making element at A[1] negative. Array becomes = {2, -4, 1, 4} 31 | Second iteration, I take A[1] = -4 (from last iteration). Index = abs(A[1])-1 = 4 - 1 = 3. Now making A[3] element negative. Array becomes = {2, -4, 1, -4} 32 | Third iteration, I take A[2] = 1. Index = abs(A[2])-1 = 1 - 1 = 0. Now making A[0] element negative. Array becomes = {-2, -4, 1, -4} 33 | Fourth iteration, I take A[3] = -4 (from second iteration). Index = abs(A[3])-1 = 4 - 1 = 3. Now making A[3] element negative. Array becomes = {-2, -4, 1, -4} 34 | Now the only positive number present is 1 which is at index 2. So the missing number is 2+1 (as we are using 0 indexing). 35 | What we did is suppose we have number j from the array. We make the number present at index j negative. In way we are marking what all numbers we have seen while 36 | traversing the array. 37 | 38 | */ 39 | -------------------------------------------------------------------------------- /Leetcode/Easy/05 Two Sum II - Input array is sorted.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& numbers, int target) { 4 | vector res; 5 | int left=0,right=numbers.size()-1; 6 | while (left& nums) { 4 | int position=1; 5 | if (nums.size()==0) return 0; 6 | for (int i=1;inums[i-1]){ 9 | nums[position++]=nums[i]; 10 | } 11 | } 12 | return position; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode/Easy/07 Remove element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | if (nums.size()==0) return 0; 5 | int returned_size=0; 6 | for (int i=0;i& nums, int target) { 4 | int low=0; 5 | int high=nums.size()-1; 6 | while (low<=high) 7 | { 8 | int mid=(low+high)/2; 9 | if (nums[mid]target) high=mid-1; 11 | else return mid; 12 | } 13 | return low; 14 | } 15 | }; 16 | 17 | -------------------------------------------------------------------------------------------------------- 18 | 19 | class Solution { 20 | public: 21 | int searchInsert(vector& nums, int target) { 22 | int n= nums.size(); 23 | int start=0; 24 | int end= n-1; 25 | while (start <=end){ 26 | int mid = start + (end-start)/2; 27 | if (target== nums[mid]) 28 | return mid; 29 | else if (target& nums) { 4 | if (nums.size()==0) return 0; 5 | int max_sum= nums[0]; 6 | int sum_inc_cur = nums[0]; 7 | for (int i=1;i& nums) { 20 | int sum=0; 21 | int maxi=INT_MIN; 22 | for (auto i:nums) 23 | { 24 | sum+=i; 25 | maxi=max(maxi,sum); // everytime take maximum after adding the next element 26 | if (sum<0) sum=0; // whenever sum become less then 0 set its value to zero 27 | } 28 | return maxi; 29 | } 30 | }; 31 | // tc sc =O(n), O(1) 32 | -------------------------------------------------------------------------------- /Leetcode/Easy/10 Plus One.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. 3 | 4 | The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. 5 | 6 | You may assume the integer does not contain any leading zero, except the number 0 itself. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: digits = [1,2,3] 13 | Output: [1,2,4] 14 | Explanation: The array represents the integer 123. 15 | Example 2: 16 | 17 | Input: digits = [4,3,2,1] 18 | Output: [4,3,2,2] 19 | Explanation: The array represents the integer 4321. 20 | Example 3: 21 | 22 | Input: digits = [0] 23 | Output: [1] 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= digits.length <= 100 29 | 0 <= digits[i] <= 9 30 | */ 31 | 32 | class Solution { 33 | public: 34 | vector plusOne(vector& digits) { 35 | int len=digits.size()-1; 36 | while (len>=0) 37 | { 38 | if (digits[len]==9) digits[len]=0; 39 | else { 40 | digits[len]++; 41 | return digits; 42 | } 43 | len--; 44 | } 45 | digits.insert(digits.begin(),1); // resizing the vector 46 | return digits; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode/Easy/11 Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | m--; 5 | n--; 6 | int index = nums1.size()-1; 7 | while (index>=0){ 8 | if (m<0) 9 | nums1[index]=nums2[n--]; 10 | else if (n<0) 11 | nums1[index]=nums1[m--]; 12 | else 13 | { 14 | if (nums1[m]>nums2[n]) 15 | nums1[index]=nums1[m--]; 16 | else 17 | nums1[index]=nums2[n--]; 18 | } 19 | index--; // decrement the loop 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode/Easy/12 Pascal's Tringle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector > nums(numRows); 5 | for (int i=0;i getRow(int rowIndex) { 4 | vector nums(rowIndex+1,1); // create a vector more then the size(1 extra) and initialize it with 1 5 | for (int i=1;i0;j--) 9 | nums[j]= nums[j]+nums[j-1]; 10 | } 11 | return nums; 12 | } 13 | }; 14 | 15 | --------------------------------------------------------------------------------------------------------------- 16 | class Solution { 17 | public: 18 | vector getRow(int rowIndex) { 19 | vector nums(rowIndex+1,1); // create a vector more then the size(1 extra) and initialize it with 1 20 | for (int i=1;i0;j--) 23 | nums[j]= nums[j]+nums[j-1]; 24 | } 25 | return nums; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Leetcode/Easy/14 Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int max_profit=0; //initially set max profit as zero 5 | int min_price= INT_MAX; // min price as max number 6 | for (int i=0;i& prices) { 17 | int leftMin = prices[0]; 18 | int profit = 0; 19 | for(int i=1; iprofit) 23 | profit=prices[i]-leftMin; 24 | } 25 | return profit; 26 | 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Leetcode/Easy/15 Single Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int res=0; 5 | for (int i=0;i& nums) { 18 | sort(nums.begin(),nums.end()); 19 | stacks; 20 | for(int i=0;i productExceptSelf(vector& nums) { 4 | int len = nums.size(); 5 | vector res(len,0); 6 | res[0]=1; 7 | for (int i=1;i=0;i--){ 11 | res[i]*=right; 12 | right*=nums[i]; 13 | } 14 | return res; 15 | } 16 | }; 17 | 18 | ---------------------------------------------------------------------------------------------------------------------------------------------------- 19 | class Solution { // this solution is with less space 20 | public: 21 | vector productExceptSelf(vector& nums) { 22 | vector left(nums.size(),1); 23 | vector right(nums.size(),1); 24 | vector res(nums.size(),0); 25 | for (int i=1;i=0;i--) 30 | { 31 | right[i]=right[i+1]*nums[i+1]; 32 | } 33 | for (int i=0;ival > l2->val){ // if l1 is having more elemnts then l2 9 | head = l2; // so head should point on the smallest of these 10 | l2 = l2->next; //we had taken a node so l2 should move to next everytime 11 | } else 12 | l1 = l1->next; // move l1 to next 13 | 14 | ListNode* curr = head; // lets take a current pointer pointing to head 15 | while(l1 && l2){ // we will run a loop till both are present in the list // if anyone of them become null we will appent the remaining 16 | if(l1->val < l2->val){ // if l2 value is greater then the l1 17 | curr->next = l1; // then we will pick from l1 18 | l1 = l1->next; //we had taken a node so l1 should move to next everytime 19 | } else { 20 | curr->next = l2; // take from l2 21 | l2 = l2->next; // and move next 22 | } 23 | curr = curr->next; // change the pointer 24 | } 25 | if(!l1) curr->next = l2; // if l1 got null take all remaining from l2 26 | else curr->next = l1; // else l2 got null take all remaining from l1 27 | 28 | return head; // store all the node in head pointer and return it 29 | } 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /Leetcode/Easy/18 Palindrome Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(ListNode* head) { 4 | 5 | vector v; // creating a vector 6 | while (head!=0) // while elements is there in the linkedlist 7 | { 8 | v.push_back(head->val); // put all the element in the vector from the list 9 | head=head->next; // move everytime pointer to the next 10 | } 11 | int first= 0, last= v.size()-1; // setting first as zero and last as the size of the list 12 | while (firstnext;// p sud move to next node 22 | q->next = r;// q next sud points on 23 | } 24 | return q; // once we came out of while loop // 1st pointer sud point on q 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Leetcode/Easy/20 Delete Node in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | node->val=node->next->val; 13 | node->next=node->next->next; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode/Easy/21 Remove Linked List Elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* removeElements(ListNode* head, int val) { 14 | 15 | ListNode* p=head; 16 | 17 | while (head && head->val==val) head=head->next; 18 | while (p){ 19 | if (p->next && p->next->val==val) 20 | { 21 | p->next=p->next->next; 22 | } 23 | else 24 | { 25 | p=p->next; 26 | } 27 | 28 | } 29 | return head; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Leetcode/Easy/22 Linked List Cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | if (head == NULL) return false; 13 | ListNode* p = head; 14 | ListNode* q = head; 15 | while (p->next != NULL && p->next->next != NULL) { // this condition should be satisfied for forting a loop 16 | q = q->next; // move everytime q to one position 17 | p = p->next->next; // everytime move p two times 18 | if (p == q) // if this two meets at a place then there will ba cycle 19 | return true; 20 | } 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode/Easy/23 Middle of the Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* p=head; // create a pointer node p and move on the head node 15 | while (head && head->next) // iterate through the list till nodes is there. 16 | { 17 | head=head->next->next; //the time p will move one head will move two 18 | p=p->next; // this way we can take nodes 19 | } 20 | return p; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode/Easy/24 Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | ListNode* q = head; // point q on head 15 | while (q && q->next) // when element is there in the list 16 | { 17 | if (q->val == q->next->val) // if data is matching // means duplicate is there 18 | { 19 | q->next=q->next->next; // then skip that and point next to next 20 | } 21 | else // if there is duplicate value 22 | { 23 | 24 | q = q->next; // and move q to next 25 | } 26 | 27 | } 28 | return head; // at last take the list 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Leetcode/Easy/25 Convert Binary Number in a Linked List to Integer.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | int getDecimalValue(ListNode* head) { 14 | ListNode* p=head; 15 | int c=0; 16 | while (p) 17 | { 18 | c++; 19 | p=p->next; 20 | } 21 | p=head; 22 | int decimal=0; 23 | while (p) 24 | { 25 | c--; 26 | if(p->val==1) 27 | { 28 | decimal=decimal+pow(2,c); 29 | } 30 | p=p->next; 31 | } 32 | return decimal; 33 | 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Leetcode/Easy/26 Intersection of Two Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 | ListNode *p =headA; 5 | ListNode *q= headB; 6 | 7 | while (p!= q) 8 | { 9 | p = !p ? headB : p->next; 10 | q = !q ? headA : q->next; 11 | 12 | } 13 | return p; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode/Easy/27 Majority Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | // if you can see highest frequency will always be in the middle of the list ater sorting 5 | 6 | int middle=(nums.size())/2; 7 | // We don't need to sort the whole list, just need to pinpoint the number at the mid position. 8 | nth_element(nums.begin(),nums.begin()+middle,nums.end()); 9 | return nums[middle]; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode/Easy/28 Majority element 2ndsol.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | int candidate=nums[0],count=1; 5 | for(int i=1 ; i& nums) { 4 | int non_zero_index=0; 5 | for (int i=0;i& s) { 4 | int i = 0 , j = s.size()-1; 5 | while(i v; 5 | for(int i=0;i=65 && s[i]<=90 || s[i]>=97 && s[i]<=122){ 7 | v.push_back(s[i]); 8 | } 9 | } 10 | int j=v.size()-1; 11 | for(int i=0;i=65 && s[i]<=90 || s[i]>=97 && s[i]<=122){ 13 | s[i]=v[j]; 14 | j--; 15 | } 16 | } 17 | return s; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode/Easy/32 To Lower Case.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string toLowerCase(string str) { 4 | for (int i=0;str[i]!='\0';i++) 5 | { 6 | if (str[i]>=65 && str[i]<=90) 7 | str[i]+=32; 8 | } 9 | return str; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode/Easy/33 Reverse Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long reverse(int n) { 4 | // support variables 5 | long res = 0; 6 | // restructuring the number 7 | while (n) { 8 | res = res * 10 + n % 10; 9 | n /= 10; 10 | } 11 | // filtering out invalid results 12 | if (res < -2147483648 || res > 2147483647) return 0; 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode/Easy/34 Fizz Buzz.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fizzBuzz(int n) { 4 | vector v; 5 | for(int i =1;i<=n;i++) 6 | { 7 | if((i%3 == 0) && (i%5 == 0)) 8 | { 9 | v.push_back("FizzBuzz"); 10 | } 11 | else if(i%3 == 0) 12 | { 13 | v.push_back("Fizz"); 14 | } 15 | else if(i%5 == 0) 16 | { 17 | v.push_back("Buzz"); 18 | } 19 | else 20 | v.push_back(to_string(i)); 21 | } 22 | return v; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode/Easy/35 First Unique Character in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstUniqChar(string s) { 4 | vector temp(26,0); 5 | for(int i=0; s[i]!='\0'; i++){ 6 | temp[s[i] - 97]++; 7 | } 8 | for(int i=0; s[i]!='\0'; i++){ 9 | if(temp[s[i]-97] == 1) return i; 10 | } 11 | return -1; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode/Easy/36 Power of Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | if (n == 1) 5 | return true; 6 | else if (n % 3 != 0 || n ==0) 7 | return false; 8 | 9 | // recursive function call 10 | return isPowerOfThree(n / 3); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode/Easy/37 1-bit and 2-bit Characters.cpp: -------------------------------------------------------------------------------- 1 | // problem : https://leetcode.com/problems/1-bit-and-2-bit-characters/ 2 | // Solution : https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1157774/explained-with-pen-paper-easy-clean-sol 3 | class Solution { 4 | public: 5 | bool isOneBitCharacter(vector& bits) { 6 | int len = bits.size(); 7 | int i=0; 8 | while (i addToArrayForm(vector& A, int K) { 4 | vector ans; 5 | int carry = 0, i = A.size()-1; 6 | while(i>=0 || carry > 0 || K!=0){ 7 | if(K!=0){ 8 | carry += K%10; 9 | K = K/10; 10 | } 11 | if(i>=0){ 12 | carry += A[i]; 13 | i--; 14 | } 15 | ans.push_back(carry%10); 16 | carry = carry/10; 17 | } 18 | reverse(ans.begin(),ans.end()); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode/Easy/39 Array Partition I.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/array-partition-i/ 2 | class Solution { 3 | public: 4 | 5 | int arrayPairSum(vector& nums) { 6 | sort(nums.begin(), nums.end()); 7 | int len = nums.size(); 8 | size_t sum = 0; 9 | for(int i = 0; i < len; i+=2) 10 | sum += nums[i]; 11 | return sum; 12 | } 13 | 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode/Easy/40 Next Greater Element I.cpp: -------------------------------------------------------------------------------- 1 | // aditya verma stack question varations 2 | class Solution { 3 | public: 4 | vector nextGreaterElement(vector& nums1, vector& nums2) { 5 | 6 | stackS; 7 | vectorans; 8 | unordered_mapM; 9 | for (int i=nums2.size()-1;i>=0;i--) 10 | { 11 | while(S.size() and nums2[i]>S.top()) // when there is element in stack and element in array is greater then stack top ; then pop that elemet 12 | S.pop(); 13 | 14 | if(S.size()) 15 | M[nums2[i]] = S.top(); 16 | 17 | else 18 | M[nums2[i]] = -1; 19 | 20 | S.push(nums2[i]); 21 | } 22 | 23 | 24 | for(auto n:nums1) 25 | ans.push_back(M[n]); 26 | 27 | return ans; 28 | 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Leetcode/Easy/41 Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector inorderTraversal(TreeNode* root) { 15 | vector v; 16 | stack st; 17 | while (root!=0 || st.size()!=0) 18 | { 19 | if (root!=0) 20 | { 21 | st.push(root); 22 | root=root->left; 23 | } 24 | else 25 | { 26 | root= st.top(); 27 | st.pop(); 28 | v.push_back(root->val); 29 | root=root->right; 30 | } 31 | } 32 | return v; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Leetcode/Easy/42 Binary Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int start= 0; 5 | int end= nums.size()-1; 6 | while (start <= end) 7 | { 8 | int mid = start + (end-start)/2; 9 | if (target==nums[mid]) 10 | return mid; 11 | else if (targetleft); 21 | rh=maxDepth(root->right); 22 | } 23 | return 1+max(lh,rh); 24 | } 25 | 26 | 27 | }; 28 | -------------------------------------------------------------------------------- /Leetcode/Easy/46 Balanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxDepth(TreeNode* root, bool & isbal) { 15 | int lh,rh; 16 | if (root==nullptr) 17 | return 0; 18 | if(isbal==false) 19 | return 0; 20 | 21 | lh=maxDepth(root->left,isbal); 22 | rh=maxDepth(root->right,isbal); 23 | if (abs(lh-rh)>1) 24 | isbal=false; 25 | 26 | return 1+max(lh,rh); 27 | } 28 | bool isBalanced(TreeNode* root) { 29 | bool isbal = true; 30 | int ht= maxDepth(root,isbal); 31 | return isbal; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Leetcode/Easy/47 Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | long long digit,rev=0; 5 | long long n=x; 6 | if (x<0) 7 | return false; 8 | do 9 | { 10 | digit=x%10; 11 | rev=(rev*10)+digit; 12 | x/=10; 13 | }while(x!=0); 14 | if (rev==n) 15 | return true; 16 | return false; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode/Easy/48 Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack st; //taking stack for keep tracking the order of the brackets.. 5 | for(auto i:s) //iterate over each and every elements 6 | { 7 | if(i=='(' or i=='{' or i=='[') st.push(i); //if current element of the string will be opening bracket then we will just simply push it into the stack 8 | else //if control comes to else part, it means that current element is a closing bracket, so check two conditions current element matches with top of the stack and the stack must not be empty... 9 | { 10 | if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or (st.top()=='[' and i!=']')) return false; 11 | st.pop(); //if control reaches to that line, it means we have got the right pair of brackets, so just pop it. 12 | } 13 | } 14 | return st.empty(); //at last, it may possible that we left something into the stack unpair so return checking stack is empty or not.. 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode/Easy/49 Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) 4 | { 5 | unordered_map T = { { 'I' , 1 }, 6 | { 'V' , 5 }, 7 | { 'X' , 10 }, 8 | { 'L' , 50 }, 9 | { 'C' , 100 }, 10 | { 'D' , 500 }, 11 | { 'M' , 1000 } }; 12 | 13 | int sum = T[s.back()]; 14 | for (int i = s.length() - 2; i >= 0; --i) 15 | { 16 | if (T[s[i]] < T[s[i + 1]]) 17 | { 18 | sum -= T[s[i]]; 19 | } 20 | else 21 | { 22 | sum += T[s[i]]; 23 | } 24 | } 25 | 26 | return sum; 27 | } 28 | }; 29 | --------------------------------------------------------------------------------------------------------------------------------------- 30 | 31 | class Solution { 32 | public: 33 | int romanToInt(string s) { 34 | int num = 0; 35 | int size = s.size(); 36 | 37 | for (int i = 0; i < size; i++) { 38 | if (i < (size - 1) && romanCharToInt(s[i]) < romanCharToInt(s[i + 1])) { 39 | num -= romanCharToInt(s[i]); 40 | } else { 41 | num += romanCharToInt(s[i]); 42 | } 43 | } 44 | return num; 45 | } 46 | 47 | int romanCharToInt(char c) { 48 | switch (c) { 49 | case 'I': return 1; 50 | case 'V': return 5; 51 | case 'X': return 10; 52 | case 'L': return 50; 53 | case 'C': return 100; 54 | case 'D': return 500; 55 | case 'M': return 1000; 56 | default: return 0; 57 | } 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Leetcode/Easy/Add Two Numbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 | ListNode dummy = new ListNode(0); // creating an dummy list 4 | ListNode curr = dummy; // intialising an pointer 5 | int carry = 0; // intialising our carry with 0 intiall 6 | // while loop will run, until l1 OR l2 not reaches null OR if they both reaches null. But our carry has some value in it. 7 | // We will add that as well into our list 8 | while(l1 != null || l2 != null || carry == 1){ 9 | int sum = 0; // intialising our sum 10 | if(l1 != null){ // adding l1 to our sum & moving l1 11 | sum += l1.val; 12 | l1 = l1.next; 13 | } 14 | if(l2 != null){ // adding l2 to our sum & moving l2 15 | sum += l2.val; 16 | l2 = l2.next; 17 | } 18 | sum += carry; // if we have carry then add it into our sum 19 | carry = sum/10; // if we get carry, then divide it by 10 to get the carry 20 | ListNode node = new ListNode(sum % 10); // the value we'll get by moduloing it, will become as new node so. add it to our list 21 | curr.next = node; // curr will point to that new node if we get 22 | curr = curr.next; // update the current every time 23 | } 24 | return dummy.next; // return dummy.next bcz, we don't want the value we have consider in it intially!! 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Leetcode/Easy/Longest common prefix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestCommonPrefix(String[] strs) { 3 | StringBuilder longestCommonPrefix = new StringBuilder(); 4 | int index = 0; 5 | 6 | outer: 7 | for (char c : strs[0].toCharArray()) { 8 | for (int i = 1; i < strs.length; i++) { 9 | if (index >= strs[i].length() || c != strs[i].charAt(index)) { 10 | break outer; 11 | } 12 | } 13 | 14 | longestCommonPrefix.append(c); 15 | index++; 16 | } 17 | 18 | return longestCommonPrefix.toString(); 19 | } 20 | } 21 | 22 | // TC: O(s * n) 23 | // let s be the length of the first string in strs array 24 | // n is the length of the strs array 25 | 26 | // SC: O(1) 27 | -------------------------------------------------------------------------------- /Leetcode/Easy/Remove Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int count = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] != val) { 6 | nums[count++] = nums[i]; 7 | } 8 | } 9 | return count; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Leetcode/Easy/Roman to Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | Map charToInt = Map.of( 4 | 'I', 1, 5 | 'V', 5, 6 | 'X', 10, 7 | 'L', 50, 8 | 'C', 100, 9 | 'D', 500, 10 | 'M', 1000); 11 | 12 | int result = 0; 13 | 14 | for (int i = 0; i < s.length(); i++) { 15 | int current = charToInt.get(s.charAt(i)); 16 | if (i + 1 < s.length() && current < charToInt.get(s.charAt(i + 1))) { 17 | result -= current; 18 | } else { 19 | result += current; 20 | } 21 | } 22 | 23 | return result; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Leetcode/Easy/Search Insert Position.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | int l = 0, r = nums.length-1; 4 | int mid = l +(r-l)/2; 5 | while(l<=r){ 6 | mid = l +(r-l)/2; 7 | if(nums[mid]==target) 8 | return mid; 9 | else if(nums[mid]>target){ 10 | r = mid-1; 11 | }else{ 12 | l=mid+1; 13 | } 14 | } 15 | return l; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Leetcode/Easy/Sqrt(x).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int x) { 3 | int l = 1; 4 | int r = x; 5 | 6 | while(l <= r){ 7 | int mid = (l + r) / 2; 8 | 9 | if(x / mid == mid){ 10 | return mid; 11 | } else if(mid > x / mid){ 12 | r = mid - 1; 13 | } else { 14 | l = mid + 1; 15 | } 16 | } 17 | 18 | return r; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Leetcode/Easy/valid parenthesis.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(String s) { 3 | 4 | 5 | // Create a new stack to store the characters. 6 | Stack stack = new Stack<>(); 7 | 8 | 9 | // convert string into char array and access the characters using for each loop. 10 | for(char ch: s.toCharArray()) 11 | { 12 | // check ch 13 | switch (ch) 14 | { 15 | // open bracket then push it in stack. 16 | // close bracket then pop the item and compare. 17 | case '(': 18 | case '{': 19 | case '[': 20 | stack.push(ch); 21 | break; 22 | case ')': 23 | if(stack.isEmpty() || stack.pop() != '(') 24 | 25 | // if the stack is empty then it means string have no open bracket. 26 | // hence it is invalid. 27 | { 28 | return false; 29 | } 30 | break; 31 | case '}': 32 | if(stack.isEmpty() || stack.pop() != '{') 33 | { 34 | return false; 35 | } 36 | break; 37 | case ']': 38 | if(stack.isEmpty() || stack.pop() != '[') 39 | { 40 | return false; 41 | } 42 | break; 43 | } 44 | } 45 | 46 | 47 | // After the loop we have to check one more condition. 48 | // return true only if the stack is empty. 49 | // if stack is not empty that means we have unused brackets. 50 | 51 | if(stack.isEmpty()) 52 | return true; 53 | else 54 | return false; 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Leetcode/Hard/01 First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int firstMissingPositive(vectornums) 5 | { 6 | int n=nums.size(); // size of the vector 7 | for(int i = 0; i < nums.size(); i++) // iterating through the nums 8 | // checking the underflow and the overflow condition then 9 | while(nums[i] > 0 && nums[i] <= nums.size() && nums[abs(nums[i] - 1)] != nums[i]) 10 | swap(nums[i], nums[nums[i] - 1]); 11 | 12 | for(int i = 0; i < n; i++) 13 | if(nums[i] != i + 1) 14 | return i + 1; 15 | 16 | return n + 1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode/Hard/02 Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | if(nums.size()==0) return 0; 5 | int x=0,m=0; 6 | map h; 7 | for(int i=0;i& heights) { 5 | int n= heights.size(); 6 | vector left,right; 7 | stack> s1,s2; 8 | int pseudo_index =-1; 9 | int pseudo_index1 =n; 10 | for (int i=0;i0 && s1.top().first0 && s1.top().first>=heights[i]) 21 | { 22 | while(s1.size()>0 && s1.top().first>=heights[i]) 23 | { 24 | s1.pop(); 25 | } 26 | if (s1.size()==0) 27 | { 28 | left.push_back(pseudo_index); 29 | } 30 | else 31 | { 32 | left.push_back(s1.top().second); 33 | } 34 | } 35 | s1.push({heights[i],i}); 36 | } 37 | for (int i=n-1;i>=0;i--) 38 | { 39 | if (s2.size()==0) 40 | { 41 | right.push_back(pseudo_index1); 42 | } 43 | else if (s2.size()>0 && s2.top().first0 && s2.top().first >= heights[i]) 48 | { 49 | while(s2.size()>0 && s2.top().first >= heights[i]) 50 | { 51 | s2.pop(); 52 | } 53 | if (s2.size()==0) 54 | { 55 | right.push_back(pseudo_index1); 56 | } 57 | else 58 | { 59 | right.push_back(s2.top().second); 60 | } 61 | } 62 | s2.push({heights[i],i}); 63 | } 64 | reverse(right.begin(),right.end()); 65 | int m=INT_MIN; 66 | for (long long i=0;i ump; 4 | bool isScramble(string X, string Y) { 5 | 6 | string key = X + " " + Y; 7 | if (ump.find(key) != ump.end()) // if we did not found the and travesed upto end of the map 8 | return ump[key]; 9 | 10 | if (X.compare(Y) == 0) { 11 | ump[key] = true; 12 | return true; 13 | } 14 | if (X.length() <= 1) { 15 | ump[key] = false; 16 | return false; 17 | } 18 | 19 | int n = X.length(); 20 | int flag = false; 21 | for (int i = 1; i <= n - 1; i++) { 22 | if ((isScramble(X.substr(0, i), Y.substr(n - i, i)) && isScramble(X.substr(i), Y.substr(0, n - i))) || 23 | (isScramble(X.substr(0, i), Y.substr(0, i)) && isScramble(X.substr(i), Y.substr(i)))) { 24 | flag = true; 25 | break; 26 | } 27 | } 28 | 29 | return ump[key] = flag; // store in table for further reference 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Leetcode/Hard/05 Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | vector ans; 5 | deque l; 6 | int i=0; 7 | int j=0; 8 | 9 | if (k>nums.size()) 10 | { 11 | ans.push_back(*max_element(nums.begin(),nums.end())); 12 | return ans; 13 | } 14 | 15 | while (j0 && l.back() nums.size()) 33 | ans.push_back(*max_element(nums.begin(),nums.end())); 34 | 35 | } 36 | return ans; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Leetcode/Hard/06 Median of Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double mediann(vector&a,vector&b){ 4 | int m=a.size(); 5 | int n=b.size(); 6 | if(m>n) 7 | return mediann(b,a); 8 | int l=0,r=m; 9 | while(l<=r){ 10 | int partx=l+(r-l)/2; 11 | int party=(m+n+1)/2-partx; 12 | int maxlx=(partx==0)?INT_MIN:a[partx-1]; 13 | int minrx=(partx==m)?INT_MAX:a[partx]; 14 | int maxly=(party==0)?INT_MIN:b[party-1]; 15 | int minry=(party==n)?INT_MAX:b[party]; 16 | if(maxlx<=minry&&maxly<=minrx){ 17 | if((m+n)%2==0) 18 | return (double)(max(maxlx,maxly)+min(minrx,minry))/2; 19 | else 20 | return (double)(max(maxlx,maxly)); 21 | }else if(maxlx>minry) 22 | r=partx-1; 23 | else 24 | l=partx+1; 25 | } 26 | return -1.0; 27 | } 28 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 29 | double ans; 30 | ans=mediann(nums1,nums2); 31 | return ans; 32 | } 33 | }; 34 | 35 | -------------------------------------------------------------------------------------------------------------- 36 | 37 | class Solution { 38 | public: 39 | int kthElement(vector &arr1, vector &arr2, int n, int m, int k) 40 | { 41 | // most important thing, initialization of low, high 42 | int low = max(0, k-m), high = min( n, k ); 43 | int indx, indx2; 44 | while(low <= high) 45 | { 46 | 47 | int mid = low + (high - low) / 2; 48 | int x = mid; 49 | int y = k - x; // x + y == k 50 | 51 | int A = ( x==0 ) ? INT_MIN : arr1[x-1]; 52 | int B = ( y==0 ) ? INT_MIN : arr2[y-1]; 53 | 54 | int C = ( x+1 <= n) ? arr1[x] : INT_MAX ; 55 | int D = ( y+1 <= m) ? arr2[y] : INT_MAX ; 56 | 57 | // Array visualization 58 | // ---------A C--------- 59 | // ---------B D--------- 60 | 61 | if( (A<=D) && (B<=C) ) 62 | { 63 | indx = mid; 64 | indx2 = k - mid; 65 | break; 66 | } 67 | else if( A > D ) 68 | high = mid - 1; 69 | else 70 | low = mid + 1; 71 | } 72 | 73 | int ans; 74 | if(indx <= n) 75 | { 76 | int a = (indx > 0) ? arr1[indx - 1] : INT_MIN; 77 | int b = (indx2 > 0) ? arr2[ indx2 - 1] : INT_MIN; 78 | return max(a, b); 79 | } 80 | return arr2[ indx2 - 1]; 81 | } 82 | 83 | double findMedianSortedArrays(vector& arr1, vector& arr2) { 84 | int n = arr1.size(); 85 | int m = arr2.size(); 86 | 87 | if( (n+m)%2 ) return kthElement(arr1, arr2, n, m, (n+m+1)/2); 88 | 89 | int a = kthElement(arr1, arr2, n, m, (n+m)/2); 90 | int b = kthElement(arr1, arr2, n, m, (n+m)/2 + 1); 91 | 92 | return (a + b) / 2.0 ; 93 | } 94 | }; 95 | 96 | /* 97 | Intuition : 98 | We have to select first K elements from the final merged array. So we can suppose some x elements are coming from where arr1 and some y elements are coming from arr2 where x or y may be zero but x+y==k. 99 | 100 | Question 1 : How to find x and y ? 101 | For some fixed value of x , y = k - x becuase x+y==k. 102 | And to find x naive approach is we can iterate the arr1 from start to end and it will take O(n) time. 103 | But as array is sorted if we choose some pivot point as x and if it will not be satisfying the criteria of partition ( we will see the criteria later) then we can move the pivot to the right or left by checking the condition. Here moving the pivot to the right or left gives the idea of using Binary Search to find the value of x. 104 | 105 | Question 2 : How to use Binary Search? 106 | If we select first x elements from array1 and first y elements from array2 then it will divide the array in two part. 107 | 108 | arr1 : ---------A C--------- 109 | arr2 : ---------B D--------- 110 | Here A is the xth element of arr1 and C is x+1th element of first array 111 | Similary B is the yth element of arr1 and D is y+1th element of second array. 112 | 113 | Suppose it is valid partioning of both the array, here valid partioning means 114 | 115 | merged(arr1, arr2) = merged( ------A, ------B ) + merged( C----------, D-------- ) 116 | (first k elements) (last n-k elements) 117 | first part second part 118 | And if it is proper division of both array to merged then Kth smallest element will be last element of first part, which can be either A or B. So our problem reduced to find maximum between A and B. 119 | 120 | Question 3 : What will be criteria to check valid partioning? 121 | To be valid partioning each element of first part must be less than or equal to second element. 122 | But as arrays are already sorted, we only need to check that maxElement(part1) <= maxElement(part2). 123 | 124 | A <= C (trivial because [ -----A C------] was sorted array) 125 | A <= D 126 | 127 | B <= C 128 | B <= D (trivial because [ -----B D------] was sorted array) 129 | So we only need to check (A<=D) && (B<=C) to be a valid partioning. 130 | 131 | Question 4 : How to move left or right if the condition is false? 132 | 133 | Let's suppose ( A > D ) which is false condition, then we have to move in direction where it becomes true ( A <= D ), so we can move pointer x to left becuase it will decrease A and condition ( A <= D ) may become true. 134 | high = mid - 1. 135 | 136 | Let's suppose ( B > C ) which is false condition, then we have to move in direction where it becomes true ( B <= C ), so we can move pointer y to left ( indirectly pointer x to right, because x+y is always equal to k, if x moves toward right then y will move left and vice versa) so it will decrease B and condition ( B <= C ) may become true. 137 | low = mid + 1. 138 | 139 | Initialising range for binary search 140 | Here n1 and n2 are length of array1 and array2 141 | 142 | x 143 | ↓ 144 | arr1 : 0 ----------------- n1 145 | arr2 : 0 ----------------------- n2 146 | ↑ 147 | y 148 | x >= 0 -- eq 1 149 | x <=n1 -- eq 2 150 | (y = k - x ) >= 0 => ( x <= k ) -- eq 3 151 | (y = k - x ) <= n2 => ( x >= k-n2 ) -- eq 4 152 | 153 | 154 | From eq 1 & eq 4 155 | x >= max(0, k-m) // low = max(0, k-n1) 156 | From eq 2 & eq 3 157 | x <= min( n2, k ) // high = min( n2, k ) 158 | Corner Condition : 159 | 160 | if x == 0, then arr1[ x - 1 ] will not exist and as this can be valid partioning and we are always comparing A <= D, so to get condition always true (because valid partionining) we have set A as minimum possible value, A = INT_MIN 161 | Same case y == 0, then arr2[ y - 1 ] will not exist and as this can be valid partioning and we are always comparing B <= C, so to get condition always true (because valid partionining) we have set B as minimum possible value, B = INT_MIN 162 | Similary if x == n1, then arr1[ x ] will not exist and as this can be valid partioning and we are always comparing B <= C, so to get condition always true (because valid partionining) we have set C as maximum possible value, C = INT_MAX. 163 | Similary if y == n2, then arr2[ y ] will not exist and as this can be valid partioning and we are always comparing A <= D, so to get condition alway0s true (because valid partionining) we have set D as maximum possible value, D = INT_MAX. 164 | 165 | */ 166 | -------------------------------------------------------------------------------- /Leetcode/Hard/07 Longest Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestValidParentheses(string s) { 4 | int n = s.length(), longest = 0; 5 | stack st; 6 | for (int i = 0; i < n; i++) { 7 | if (s[i] == '(') st.push(i); 8 | else { 9 | if (!st.empty()) { 10 | if (s[st.top()] == '(') st.pop(); 11 | else st.push(i); 12 | } 13 | else st.push(i); 14 | } 15 | } 16 | if (st.empty()) longest = n; 17 | else { 18 | int a = n, b = 0; 19 | while (!st.empty()) { 20 | b = st.top(); st.pop(); 21 | longest = max(longest, a-b-1); 22 | a = b; 23 | } 24 | longest = max(longest, a); 25 | } 26 | return longest; 27 | } 28 | }; 29 | 30 | 31 | /* 32 | 33 | 34 | The workflow of the solution is as below. 35 | 36 | Scan the string from beginning to end. 37 | If current character is '(', 38 | push its index to the stack. If current character is ')' and the 39 | character at the index of the top of stack is '(', we just find a 40 | matching pair so pop from the stack. Otherwise, we push the index of 41 | ')' to the stack. 42 | After the scan is done, the stack will only 43 | contain the indices of characters which cannot be matched. Then 44 | let's use the opposite side - substring between adjacent indices 45 | should be valid parentheses. 46 | If the stack is empty, the whole input 47 | string is valid. Otherwise, we can scan the stack to get longest 48 | valid substring as described in step 3. 49 | 50 | */ 51 | -------------------------------------------------------------------------------- /Leetcode/Hard/08 Regular Expression Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | // dynamic programming 5 | int m=s.length(), n = p.length(); 6 | vector> dp (m+1, vector (n+1, false)); 7 | // initial state 8 | dp[0][0] = true; 9 | for(int i = 0; i < m+1; i++) { 10 | for(int j = 1; j < n+1; j++) { 11 | if(p[j-1] != '*') { 12 | dp[i][j] = i > 0 && dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.'); 13 | } 14 | else { 15 | dp[i][j] = dp[i][j-2] || (i > 0 && dp[i-1][j] && (s[i-1] == p[j-2] || p[j-2] == '.')); 16 | } 17 | } 18 | } 19 | return dp[m][n]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode/Hard/09 Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& h) { 4 | // edge case: empty input 5 | if (!h.size()) return 0; 6 | // support variables 7 | int len = h.size(), dp[len], currMax = -1, res = 0; 8 | // computing the maximum capacity looking from left 9 | for (int i = 0, e; i < len; i++) { 10 | e = h[i]; 11 | currMax = max(currMax, e); 12 | dp[i] = currMax - e; 13 | } 14 | // computing the maximum capacity looking from right 15 | currMax = -1; 16 | for (int i = len - 1, e; i > -1; i--) { 17 | e = h[i]; 18 | currMax = max(currMax, e); 19 | res += min(dp[i], currMax - e); 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode/Medium/01 Find the duplicate number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | for (int i=1;i findDuplicates(vector& nums) { 4 | vector result; 5 | for(int n : nums){ // iterated through the nums 6 | n = abs(n); 7 | if(nums[n-1] > 0) nums[n-1] *= -1; // if it is greater than zero i.e we are reaching for the 1st time 8 | // since we negeted the values everytime so when duplicate will come it will become +ve & we will push back in vector 9 | else result.push_back(n); // if this is negetive i.e we are reaching here for the second time so take that duplicate value 10 | } 11 | return result; 12 | } 13 | }; 14 | 15 | --------------------------------------------- 16 | 17 | 18 | class Solution { 19 | public: 20 | vector findDuplicates(vector& nums) { 21 | vector res; 22 | // this question is all about playing with index 23 | // in this 8 will be the maximum number & 1 will be min 24 | for (int i=0;i0) //now those which number is greater then zero take that in vector 33 | 34 | res.push_back(abs(nums[i])); // keep that indeth element in the array 35 | } 36 | return res; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Leetcode/Medium/03 Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string ltrim(const string &); 6 | string rtrim(const string &); 7 | 8 | 9 | /* 10 | * Complete the 'fibonacci' function below. 11 | * 12 | * The function is expected to return an INTEGER_ARRAY. 13 | * The function accepts INTEGER n as parameter. 14 | */ 15 | 16 | vector fibonacci(int n) { 17 | vector values(n); 18 | values[0] = 0; 19 | values[1] = 1; 20 | for (int i = 2; i < n; i++){ 21 | values[i] = values[i - 2] + values[i - 1]; 22 | } 23 | return values; 24 | 25 | } 26 | int main() 27 | { 28 | ofstream fout(getenv("OUTPUT_PATH")); 29 | 30 | string n_temp; 31 | getline(cin, n_temp); 32 | 33 | int n = stoi(ltrim(rtrim(n_temp))); 34 | 35 | vector result = fibonacci(n); 36 | 37 | for (int i = 0; i < result.size(); i++) { 38 | fout << result[i]; 39 | 40 | if (i != result.size() - 1) { 41 | fout << "\n"; 42 | } 43 | } 44 | 45 | fout << "\n"; 46 | 47 | fout.close(); 48 | 49 | return 0; 50 | } 51 | 52 | string ltrim(const string &str) { 53 | string s(str); 54 | 55 | s.erase( 56 | s.begin(), 57 | find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) 58 | ); 59 | 60 | return s; 61 | } 62 | 63 | string rtrim(const string &str) { 64 | string s(str); 65 | 66 | s.erase( 67 | find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), 68 | s.end() 69 | ); 70 | 71 | return s; 72 | } 73 | -------------------------------------------------------------------------------- /Leetcode/Medium/04 3Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | set> result; 6 | for (int i=0;i> ans; 22 | copy (result.begin(),result.end(),back_inserter(ans)); 23 | return ans; 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Leetcode/Medium/05 Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/next-permutation/ 2 | /*This problem is similar to a few others here on getting the next bigger number with the same digits or the next permutation of a string, etc. 3 | 4 | This is just easier since we work directly with a vector, so let's crack on! 5 | 6 | First of all, we will create 2 support variables, our indexes i and j, respectively set to be pointing to the penultimate element and past the end of the vector. 7 | 8 | We will then keep reducing i as long as it is non-negative and as long as it points to an element >= than the previous one. 9 | 10 | If we were to finally end up with i == -1, it would mean that the whole vector is set in decreasing order, so no next permutation is possible, and we need to transform the array to the very first one, before leaving the function. 11 | 12 | Now, you might just opt to sort the vector, but since we know it is already ordered, just reversing it might just save us precious computation: O(nlogn) vs. O(n) (or, rather O(n/2)) is a no brainer. 13 | 14 | For any other value of i, we will then search with j for the very first element that is <= nums[i], which is guaranteed to be there (since all the elements before i are in decreasing order). 15 | 16 | Once found, we will swap nums[i] and nums[j], since nums[j] is the next number to go there, and set the rest of the positions from i + 1 to be in increasing order - I guess here reversing and then using insertion sort would perform better, but I did not feel like going for that overkill just in case. 17 | 18 | The code:*/ 19 | 20 | class Solution { 21 | public: 22 | void nextPermutation(vector& nums) { 23 | // support variables 24 | int i = nums.size() - 2, j = i + 2; 25 | while (i >= 0 && nums[i] >= nums[i + 1]) i--; 26 | // edge case: already the highest permutation you can get 27 | if (i == -1) { 28 | reverse(begin(nums), end(nums)); 29 | return; 30 | } 31 | // finding the first element > nums[i] 32 | while (nums[--j] <= nums[i]); 33 | // swapping i and j's values 34 | swap(nums[i], nums[j]); 35 | // ordering the rest 36 | sort(begin(nums) + i + 1, end(nums)); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Leetcode/Medium/06 Set Matrix Zeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& a) { 4 | int n=a[0].size(); 5 | int m=a.size(); 6 | int col0=1; // for taking care of column number 0 7 | for(int i=0;i=0;i--) 20 | { 21 | for(int j=n-1;j>=1;j--) 22 | { 23 | if(a[i][0]==0 || a[0][j]==0) 24 | a[i][j]=0; 25 | } 26 | if(col0==0) 27 | a[i][0]=0; 28 | } 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Leetcode/Medium/07 Spiral Matrix.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/spiral-matrix/discuss/1113633/every-line-is-explained-faster-than-100-sub-with-notes 2 | 3 | class Solution { 4 | public: 5 | vector spiralOrder(vector>& matrix) { 6 | vector ans; 7 | int top = 0; // the beginning row is set to be zero 8 | int right = matrix[0].size() - 1; // this is for end of the col 9 | int left = 0; // this is for column beginning 10 | int bottom = matrix.size() - 1; //this is end of row 11 | 12 | while(top <= bottom && left <= right){ // row beg is less then row end && col begi is less then col end 13 | //top row 14 | for(int i = left; i <= right; i++) 15 | ans.push_back(matrix[top][i]); // this will enter the 1st line [1,2,3] 16 | top++; // now top is at 1st row and last col(i.e at 3) 17 | 18 | //left colm 19 | for(int i = top; i <= bottom; i++) 20 | ans.push_back(matrix[i][right]); // this will enter [6,9] 21 | right--; // now right is at last row last col(i.e at 9) 22 | 23 | //bottom row 24 | if(top <= bottom){ 25 | for(int i = right; i >= left; i--) // now move from bottom right to bottom left 26 | ans.push_back(matrix[bottom][i]); // this will store [8,7] 27 | bottom--;// here botom is at last row 1st col (i.e at 7) 28 | } 29 | 30 | //right colm 31 | if(left <= right){ 32 | for(int i = bottom; i >= top; i--) // now move from left bottom to left top 33 | ans.push_back(matrix[i][left]); // now take 4 and so on ............ 34 | left++; 35 | } 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode/Medium/08 Rotate Image.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-image/discuss/1113693/Easy-explained-solution-oror-faster-then-the-100-sub 2 | class Solution { 3 | public: 4 | void rotate(vector>& matrix) { 5 | int n= matrix.size(); 6 | // this loops are for the transpose if the matrix 7 | for (int i=0;ival; 22 | l1=l1->next; 23 | } 24 | if (l2) 25 | { 26 | extra+=l2->val; 27 | l2=l2->next; 28 | } 29 | p->next= new ListNode(extra%10); 30 | extra/=10; 31 | p=p->next; 32 | } 33 | return preHead.next; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------------- 37 | // https://leetcode.com/problems/add-two-numbers/ 38 | 39 | /** 40 | * Definition for singly-linked list. 41 | * struct ListNode { 42 | * int val; 43 | * ListNode *next; 44 | * ListNode() : val(0), next(nullptr) {} 45 | * ListNode(int x) : val(x), next(nullptr) {} 46 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 47 | * }; 48 | */ 49 | class Solution { 50 | public: 51 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 52 | ListNode *res = new ListNode(0); // initialize a resultant node with zero 53 | ListNode *p = l1, *q= l2, *current = res; // assifgn to new pointers 54 | int carry =0; 55 | 56 | while (p || q ) 57 | { 58 | int x = (p)? p->val : 0; 59 | int y = (q)? q->val : 0; 60 | int sum = carry+x+y; 61 | carry= sum/10; // take carry suppose 19/10 =1 carry 62 | current->next= new ListNode(sum%10); // store reminder in the new node like 19 %9 = 9--> srore it in new node 63 | current= current->next; 64 | if (p) p=p->next; // move p to next everytime 65 | if (q) q= q->next; 66 | } 67 | if (carry > 0) 68 | current->next = new ListNode(carry); 69 | return res->next; // return next because we initialized 1st res node as zero on the top 70 | } 71 | 72 | }; 73 | -------------------------------------------------------------------------------- /Leetcode/Medium/10 Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) 4 | { 5 | // Return 0 if string is empty 6 | if( s == "") { return 0; } 7 | 8 | // Hash table for storing characters and count dublicates 9 | std::map charactersOfSubstr; 10 | 11 | // Longest sequence that will be returned in the end 12 | int longest = 0; 13 | int j = 0; 14 | 15 | // Each character from string add to HashTable: for dublicates increase value that used in result calculation 16 | for (int i = 0; i < s.length(); ++i) 17 | { 18 | // Try to find character in the HashTable 19 | // If current character already exist in the HashTable - increment value 20 | if ( charactersOfSubstr.find(s[i]) != charactersOfSubstr.end() ) 21 | { 22 | charactersOfSubstr.find(s[i])->second++; 23 | } 24 | // Othervise add it to HashTable 25 | else 26 | { 27 | charactersOfSubstr.insert(pair(s[i], 1)); 28 | } 29 | 30 | // ONLY if in HashTable exist several same characters: 31 | // decrease ALL characters between j and i in HashTable AND increase j for calculation while s[i] value in Hash table > 1 32 | while ( charactersOfSubstr.find(s[i])->second > 1 ) 33 | { 34 | // Descrease value of existing character 35 | charactersOfSubstr.find(s[j])->second--; 36 | // Increase j for future calculation 37 | ++j; 38 | } 39 | 40 | // longest will be chosen between larger value: old longest OR current sequance (i - j + 1) 41 | longest = longest >= i - j + 1 ? longest : i - j + 1; 42 | } 43 | 44 | return longest; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Leetcode/Medium/11 Minimum Size Subarray Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int target, vector& nums) { 4 | int mn= INT_MAX; 5 | int j=0; // taking to the left most element to the array 6 | int sum=0; 7 | for (int i=0;i=target){ 10 | mn = min(mn,i-j+1); // i-j+1 will give the size of window and maintain the size of the window 11 | sum-=nums[j]; // decrease the size of window by one. 12 | j++; // increment in order to maintain the window size. 13 | } 14 | 15 | } 16 | return (mn!=INT_MAX)? mn:0; // return the minimum size the window to get the target 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode/Medium/12 Longest Palindromic Subsequence.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/longest-palindromic-subsequence/ 2 | class Solution { 3 | public: 4 | 5 | int LCS(string X, string Y, int n, int m) { 6 | int dp[n + 1][m + 1]; // DP - matrix 7 | 8 | // base case of recursion --> for initialization of dp - matrix 9 | for (int i = 0; i <= n; i++) 10 | for (int j = 0; j <= m; j++) 11 | if (i == 0 || j == 0) 12 | dp[i][j] = 0; 13 | 14 | for (int i = 1; i <= n; i++) 15 | for (int j = 1; j <= m; j++) 16 | if (X[i - 1] == Y[j - 1]) // when last character is same 17 | dp[i][j] = 1 + dp[i - 1][j - 1]; 18 | else // when last character is not same -> pick max 19 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); 20 | 21 | return dp[n][m]; 22 | } 23 | int longestPalindromeSubseq(string s) { 24 | 25 | string rev_X = s; 26 | int n = s.length(); 27 | reverse(rev_X.begin(), rev_X.end()); // reverse the string // take reversed string as another string of lcs and apply lcs 28 | return LCS(s, rev_X, n, n); 29 | } 30 | }; 31 | 32 | ----------------------------------------------------------------------------------------------------------------------------------------------- 33 | 34 | class Solution 35 | { 36 | public: 37 | string longestPalindrome(string s) 38 | { 39 | int n = s.size(); 40 | if (n == 0) 41 | return ""; 42 | 43 | // dp[i][j] will be 'true' if the string from index i to j is a palindrome. 44 | bool dp[n][n]; 45 | 46 | //Initialize with false 47 | 48 | memset(dp, 0, sizeof(dp)); 49 | 50 | //Every Single character is palindrome 51 | for (int i = 0; i < n; i++) 52 | dp[i][i] = true; 53 | 54 | string ans = ""; 55 | ans += s[0]; 56 | 57 | for (int i = n - 1; i >= 0; i--) 58 | { 59 | for (int j = i + 1; j < n; j++) 60 | { 61 | if (s[i] == s[j]) 62 | { 63 | //If it is of two character OR if its susbtring is palindrome. 64 | if (j - i == 1 || dp[i + 1][j - 1]) 65 | { 66 | //Then it will also a palindrome substring 67 | dp[i][j] = true; 68 | 69 | //Check for Longest Palindrome substring 70 | if (ans.size() < j - i + 1) 71 | ans = s.substr(i, j - i + 1); 72 | } 73 | } 74 | } 75 | } 76 | return ans; 77 | } 78 | }; 79 | -------------------------------------------------------------------------------- /Leetcode/Medium/13 Next Greater Element II.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/next-greater-element-ii/ 2 | class Solution { 3 | public: 4 | vector nextGreaterElements(vector& nums) { 5 | vector v; // creating a vector to store result 6 | int n= nums.size(); // size of arrray 7 | stack s; // creating a stack 8 | for (int i=n-1;i>=0;i--) 9 | { 10 | s.push(nums[i]); // take elements in the stack from array 11 | } 12 | for (int i=n-1;i>=0;i--) 13 | { 14 | if (s.size()==0) // when stack size is empty there is no element in stack return output as -1; 15 | v.push_back(-1); 16 | else if (s.size()>0 && s.top()>nums[i])// when there is element in stack and stack top is greater then array element 17 | v.push_back(s.top()); // take stack top in the result vector 18 | else if (s.size()>0 && s.top()<= nums[i]) // when there is element in stack and that element is less then array element 19 | { 20 | while (s.size()>0 && s.top() <= nums[i])// upto when there is element and stack top is less then array's element delete the element from stack 21 | s.pop();// delete the element from stack 22 | if (s.size()==0) 23 | v.push_back(-1); // when stack became empty return -1 24 | else 25 | v.push_back(s.top());// else push stack top in the vector 26 | } 27 | s.push(nums[i]);// push array in stack 28 | } 29 | reverse(v.begin(),v.end()); // while returning reverse the vector and return it. 30 | return v; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Leetcode/Medium/14 Online Stock Span.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/online-stock-span/ 2 | class StockSpanner { 3 | stack > s; 4 | public: 5 | StockSpanner() { 6 | } 7 | 8 | 9 | int next(int price) { 10 | int res=1; 11 | while (s.size()!=0 && s.top().first<=price) 12 | { 13 | res+=s.top().second; 14 | s.pop(); 15 | } 16 | s.push({price,res}); 17 | return res; 18 | } 19 | }; 20 | 21 | /** 22 | * Your StockSpanner object will be instantiated and called as such: 23 | * StockSpanner* obj = new StockSpanner(); 24 | * int param_1 = obj->next(price); 25 | */ 26 | -------------------------------------------------------------------------------- /Leetcode/Medium/15 Kth Largest Element in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { // declare a min heap // where in question it is given largest/greatest means create min heap and for smaller create max heap 4 | int val; 5 | priority_queue,greater> minh; 6 | int n= nums.size(); 7 | for (int i=0;ik) 12 | minh.pop(); 13 | } 14 | } 15 | return minh.top(); 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode/Medium/16 Sort an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums, int l, int m, int r) 4 | { 5 | int n1 = m - l + 1; 6 | int n2 = r - m; 7 | int A[n1], B[n2]; 8 | 9 | for(int i = 0; i < n1; i++) 10 | A[i] = nums[l + i]; 11 | 12 | for(int i = 0; i < n2; i++) 13 | B[i] = nums[m + 1 + i]; 14 | 15 | int i = 0, j = 0; 16 | int k = l; 17 | 18 | while(i < n1 && j < n2) 19 | { 20 | if(A[i] <= B[j]) 21 | nums[k++] = A[i++]; 22 | else 23 | nums[k++] = B[j++]; 24 | } 25 | 26 | while(i < n1) 27 | nums[k++] = A[i++]; 28 | while(j < n2) 29 | nums[k++] = B[j++]; 30 | } 31 | 32 | void mergeSort(vector& nums, int l, int r) 33 | { 34 | if(l >= r) //remember to put the equal to sign 35 | return; 36 | 37 | int m = l + (r - l)/2; 38 | mergeSort(nums, l, m); 39 | mergeSort(nums, m + 1, r); 40 | merge(nums, l, m, r); 41 | } 42 | 43 | vector sortArray(vector& nums) 44 | { 45 | mergeSort(nums, 0, nums.size() - 1); 46 | return nums; 47 | } 48 | 49 | 50 | }; 51 | -------------------------------------------------------------------------------- /Leetcode/Medium/17 Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | vector res; 5 | int start=0; 6 | int first=-1, last=-1; 7 | int end= nums.size()-1; 8 | while(start <=end) 9 | { 10 | int mid = start + (end-start)/2; 11 | if (target==nums[mid]) 12 | { 13 | first=mid; 14 | end=mid-1; 15 | 16 | } 17 | else if (target < nums[mid]) 18 | end= mid-1; 19 | else 20 | start = mid+1; 21 | } 22 | start=0,end= nums.size()-1; 23 | while (start <= end) 24 | { 25 | int mid = start+(end-start)/2; 26 | if (target== nums[mid]) 27 | { 28 | last=mid; 29 | start=mid+1; 30 | } 31 | else if (target< nums[mid]) 32 | end= mid-1; 33 | else 34 | start = mid+1; 35 | } 36 | res.push_back(first); 37 | res.push_back(last); 38 | return res; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Leetcode/Medium/18 Find Minimum in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n= nums.size(); 5 | int start=0; 6 | int end = nums.size()-1; 7 | if (n==1) 8 | return nums[0]; 9 | while (start<=end){ 10 | int mid= start+ (end-start)/2; 11 | int prev=(mid+n-1)%n; 12 | int next= (mid+1)%n; 13 | if (nums[mid]>& matrix, int target) { 4 | int n=matrix.size(); 5 | int m=matrix[0].size(); 6 | int i=0; 7 | int j=m-1; 8 | 9 | while ((i>=0 && i=0 && j<=m)){ 10 | if (matrix[i][j]==target) 11 | return true; 12 | else if (matrix[i][j]>target) 13 | j--; 14 | else if(matrix[i][j]>& matrix, int target) { 4 | int n= matrix.size(); 5 | int m=matrix[0].size(); 6 | int i=0; 7 | int j=m-1; 8 | while ((i>=0 && i=0 && jtarget) 13 | j--; 14 | else if (matrix[i][j]& nums) { 4 | int start=0, end=nums.size(); 5 | while (start < end) { 6 | int mid=start+(end-start)/2; 7 | if (mid < nums.size()-1 && nums[mid] < nums[mid+1]) { 8 | start=mid+1; 9 | } 10 | else { 11 | end=mid; 12 | } 13 | } 14 | 15 | return start; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode/Medium/22 Peak Index in a Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& nums) { 4 | int start=0, end=nums.size(); 5 | while (start < end) { 6 | int mid=start+(end-start)/2; 7 | if (mid < nums.size()-1 && nums[mid] < nums[mid+1]) { 8 | start=mid+1; 9 | } 10 | else { 11 | end=mid; 12 | } 13 | } 14 | 15 | return start; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode/Medium/23 Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | // this is the variation of dutch national flag algo it states that 2 | // all element towards the left of low will be zero 3 | // all element towards right of high will be two 4 | // everything between (Low and mid-1) will be one 5 | class Solution { 6 | public: 7 | void sortColors(vector& nums) { 8 | int low=0; 9 | int mid=0; 10 | int high=nums.size()-1; 11 | while (mid<=high) // we will move mid pointer untill it crosses high pointer 12 | { 13 | switch(nums[mid]){ 14 | // In between we will be doing three checks i.e when mid is pointing to 0,1 and 2; 15 | case 0://1st mid is pointing to zero // then we will swap index low with the index mid and increment both (low &mid) 16 | swap(nums[low],nums[mid]); 17 | low++; 18 | mid++; 19 | break; 20 | 21 | 22 | 23 | case 1: // now mid is pointing to 1 // then simply move mid pointer by one 24 | mid++; 25 | break; 26 | 27 | 28 | case 2:// now mid is pointing two // then we will swap index high with the index mid and decrement only high 29 | swap(nums[mid],nums[high]); // this time mid pointer will not be incremented 30 | high--; 31 | break; 32 | 33 | } 34 | } 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Leetcode/Medium/24 Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | vector > mergedIntervals; // declearing data structure 5 | // edge case 6 | if (intervals.size()==0) // when there is no element in intervals we will return empty interval 7 | return mergedIntervals; 8 | sort(intervals.begin(),intervals.end()); // 1st of all sort the vector 9 | vector TempInterval=intervals[0];// store 1st pair from intervals to temp intrvals // vector of size two kept in temp 10 | for (auto it : intervals) // once sorting done iterate lineraly through all the intervals 11 | { 12 | if(it[0]<=TempInterval[1]) // now check either pairs is merging or or not 13 | TempInterval[1]=max(it[1],TempInterval[1]); // whichever is maximum from the rightmost of the it and temp make a pair of that. 14 | else // if they are not merging 15 | { 16 | mergedIntervals.push_back(TempInterval); // pair which is not merged we are going to take that in merged intervals 17 | TempInterval=it; // if it does not merges with the pair then replace temp with next iterator 18 | } 19 | } 20 | mergedIntervals.push_back(TempInterval); // now whatever pair is there in temp data structure will be pushed in fianl result 21 | return mergedIntervals; 22 | } 23 | }; 24 | 25 | // tc o(nlogn)+n 26 | //sc O(n) 27 | -------------------------------------------------------------------------------- /Leetcode/Medium/25 pow(x,n).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | double ans=1.0; 5 | long long nn=n; 6 | if (nn<0) // if number is negetive make it posetive 7 | nn=nn*-1; 8 | while (nn){ 9 | if (nn%2==0) // when power is even 10 | { 11 | x*=x; // multiply number by number 12 | nn/=2;// devide power by 2 13 | } 14 | else // when power is odd 15 | { 16 | ans =ans*x;// multiply ans by given number 17 | nn-=1; // decrease power everytime 18 | } 19 | } 20 | if (n<0) // when power is negetive 21 | ans=(double)(1.0)/(double)(ans); // keep ans in denominator 22 | return ans;// at last return the answer 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode/Medium/26 4Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The key idea is to downgrade the problem to a 2Sum problem eventually. And the same algorithm can be expand to NSum problem. 4 | 5 | After you had a look at my explanation of 3Sum, the code below will be extremely easy to understand. 6 | 7 | */ 8 | class Solution { 9 | public: 10 | vector > fourSum(vector &num, int target) { 11 | 12 | vector > res; 13 | 14 | if (num.empty()) 15 | return res; 16 | 17 | std::sort(num.begin(),num.end()); 18 | 19 | for (int i = 0; i < num.size(); i++) { 20 | 21 | int target_3 = target - num[i]; 22 | 23 | for (int j = i + 1; j < num.size(); j++) { 24 | 25 | int target_2 = target_3 - num[j]; 26 | 27 | int front = j + 1; 28 | int back = num.size() - 1; 29 | 30 | while(front < back) { 31 | 32 | int two_sum = num[front] + num[back]; 33 | 34 | if (two_sum < target_2) front++; 35 | 36 | else if (two_sum > target_2) back--; 37 | 38 | else { 39 | 40 | vector quadruplet(4, 0); 41 | quadruplet[0] = num[i]; 42 | quadruplet[1] = num[j]; 43 | quadruplet[2] = num[front]; 44 | quadruplet[3] = num[back]; 45 | res.push_back(quadruplet); 46 | 47 | // Processing the duplicates of number 3 48 | while (front < back && num[front] == quadruplet[2]) ++front; 49 | 50 | // Processing the duplicates of number 4 51 | while (front < back && num[back] == quadruplet[3]) --back; 52 | 53 | } 54 | } 55 | 56 | // Processing the duplicates of number 2 57 | while(j + 1 < num.size() && num[j + 1] == num[j]) ++j; 58 | } 59 | 60 | // Processing the duplicates of number 1 61 | while (i + 1 < num.size() && num[i + 1] == num[i]) ++i; 62 | 63 | } 64 | 65 | return res; 66 | 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /Leetcode/Medium/27 Swap Nodes in Pairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | 11 | Pointer-pointer pp points to the pointer to the current node. So at first, pp points to head, and later it points to the next field of ListNodes. Additionally, 12 | for convenience and clarity, pointers a and b point to the current node and the next node. 13 | 14 | We need to go from *pp == a -> b -> (b->next) to *pp == b -> a -> (b->next). The first three lines inside the loop do that, setting those three pointers 15 | (from right to left). The fourth line moves pp to the next pair. 16 | 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* swapPairs(ListNode* head) { 21 | ListNode **pp = &head, *a, *b; 22 | while ((a = *pp) && (b = a->next)) { 23 | a->next = b->next; 24 | b->next = a; 25 | *pp = b; 26 | pp = &(a->next); 27 | } 28 | return head; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Leetcode/Medium/28 Integer to Roman.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string intToRoman(int num) 4 | { 5 | string res; 6 | string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 7 | int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 8 | 9 | for(int i=0; num != 0; i++) 10 | { 11 | while(num >= val[i]) 12 | { 13 | num -= val[i]; 14 | res += sym[i]; 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode/Medium/Longest Substring Without Repeating Characters.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int lengthOfLongestSubstring(String s) { 4 | Map map = new HashMap<>(); 5 | int i = 0; 6 | int j = 0; 7 | int max = 0; 8 | while(j < s.length()){ 9 | map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1); 10 | if(map.size() == j - i + 1){ 11 | max = Math.max(max, j - i + 1); 12 | j++; 13 | } 14 | else if(map.size() < j - i + 1){ 15 | while(map.size() < j - i + 1){ 16 | map.put(s.charAt(i), map.get(s.charAt(i)) - 1); 17 | if(map.get(s.charAt(i)) == 0) map.remove(s.charAt(i)); 18 | i++; 19 | } 20 | j++; 21 | } 22 | } 23 | return max; 24 | } 25 | } 26 | 27 | https://leetcode.com/problems/longest-substring-without-repeating-characters/solutions/2133524/java-c-a-reall-detailed-explanation/ 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Competitive-Coding 2 | 3 | 4 | ![Language](https://img.shields.io/badge/language-C++11-orange.svg) ![Progress](https://img.shields.io/badge/progress-30%20%2F%201594-ff69b4.svg) 5 | ![Visitors](https://visitor-badge.laobi.icu/badge?page_id=skjha1.Competitive-Coding) 6 | 7 | This Section contains competitive coding form different different coding plateform... 8 |

9 | 10 |

11 | 12 | 13 | ## Topics 14 | 15 | * [Array](https://github.com/skjha1/Competitive-Coding#array) 16 | * [Linked List](https://github.com/skjha1/Competitive-Coding#LinkedList) 17 | 18 | 19 | ## Array 20 | | S.No | Title | Solution | Time | Space | Difficulty | 21 | |-----|---------------- | --------------- | --------------- | --------------- | ------------- | 22 | 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/01%20Two%20Sum.cpp) | _O(n)_ | _O(n)_ | Easy | 23 | 2 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/02%20Contains%20Duplicate.cpp) | _O(n)_ | _O(1)_ | Easy | 24 | 3 | [Missing Number](https://leetcode.com/problems/missing-number/) | [souece](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/03%20Missing%20Number.cpp) | _O(n)_ | _O(1)_ | Easy | 25 | 4 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/04%20Find%20All%20Numbers%20Disappeared%20in%20an%20Array.cpp) | _O(n)_ | _O(n)_ | Easy | 26 | 5 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/05%20Two%20Sum%20II%20-%20Input%20array%20is%20sorted.cpp) | _O(n)_ | _O(n)_ | Easy | 27 | 6 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/06%20%20Remove%20Duplicates%20from%20Sorted%20Array.cpp) | _O(n)_ | _O(n)_ | Easy | 28 | 7 | [Remove element](https://leetcode.com/problems/remove-element/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/07%20Remove%20element.cpp) | _O(n)_ | _O(n)_ | Easy | 29 | 8 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/08%20Search%20Insert%20Position.cpp) | _O(n)_ | _O(n)_ | Easy | 30 | 9 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [source](https://github.com/skjha1/Competitive-Coding/blob/main/Leetcode/Easy/09%20Maximum%20Subarray.cpp) | _O(n)_ | _O(n)_ | Easy | 31 | 32 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 1/01 Sort an array of 0’s 1’s 2’s without using extra space or sorting algo.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/ 2 | // this is the variation of dutch national flag algo it states that 3 | // all element towards the left of low will be zero 4 | // all element towards right of high will be two 5 | // everything between (Low and mid-1) will be one 6 | class Solution { 7 | public: 8 | void sortColors(vector& nums) { 9 | int low=0; 10 | int mid=0; 11 | int high=nums.size()-1; 12 | while (mid<=high) // we will move mid pointer untill it crosses high pointer 13 | { 14 | switch(nums[mid]){ 15 | // In between we will be doing three checks i.e when mid is pointing to 0,1 and 2; 16 | case 0://1st mid is pointing to zero // then we will swap index low with the index mid and increment both (low &mid) 17 | swap(nums[low],nums[mid]); 18 | low++; 19 | mid++; 20 | break; 21 | 22 | 23 | 24 | case 1: // now mid is pointing to 1 // then simply move mid pointer by one 25 | mid++; 26 | break; 27 | 28 | 29 | case 2:// now mid is pointing two // then we will swap index high with the index mid and decrement only high 30 | swap(nums[mid],nums[high]); // this time mid pointer will not be incremented 31 | high--; 32 | break; 33 | 34 | } 35 | } 36 | 37 | 38 | ---------------------------------------------------------------------------- 39 | class Solution { 40 | public: 41 | void sortColors(vector& nums) { 42 | int low=0; 43 | int mid=0; 44 | int high=nums.size()-1; 45 | 46 | while (mid<=high) 47 | { 48 | switch(nums[mid]){ 49 | case 0: 50 | swap(nums[low++],nums[mid++]); 51 | break; 52 | case 1: 53 | mid++; 54 | break; 55 | case 2: 56 | swap(nums[mid],nums[high--]); 57 | break; 58 | } 59 | } 60 | } 61 | }; 62 | 63 | } 64 | }; 65 | 66 | Complexity Analysis: 67 | Time Complexity: O(n). 68 | Only one traversal of the array is needed. 69 | Space Complexity: O(1). 70 | No extra space is required. 71 | Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s. 72 | 73 | ----------------------------------------------------------------------- 74 | class Solution { 75 | public: 76 | void sortColors(vector& nums) { 77 | int n=nums.size(); 78 | int i; 79 | int cnt0=0; 80 | int cnt1=0; 81 | int cnt2=0; 82 | for (i=0;i0) 101 | { 102 | nums[i++]=0; // store zero in the array and move ahead; 103 | cnt0--; 104 | } 105 | // now update 1 in the array 106 | while (cnt1>0) 107 | { 108 | nums[i++]=1; 109 | cnt1--; 110 | } 111 | // now keep 2 in the array 112 | while (cnt2>0) 113 | { 114 | nums[i++]=2; 115 | cnt2--; 116 | } 117 | 118 | } 119 | }; 120 | Complexity Analysis: 121 | Time Complexity: O(n). 122 | Only two traversals of the array is needed. 123 | Space Complexity: O(1). 124 | As no extra space is required. 125 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 1/02 Find Missing And Repeating.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/viewSol.php?subId=5621ab6a6084c0a6b5eadfa4857f98da&pid=702678&user=shivendrajha 2 | class solution 3 | { 4 | public: 5 | int *findTwoElement(int *arr, int n) { 6 | int *res= new int(2); 7 | int freq[n+1]={0}; 8 | for (int i=0;i1) // if the index is greater then 1 that means it is a duplicate element 15 | res[0]=arr[i]; 16 | if (freq[i]==0) // the index which will be having 0 will be the missing number 17 | res[1]=i; 18 | } 19 | // this is edge case when result's 1st index will be zero i.e last number is missing 20 | /* For example 21 | Possibly your code doesn't work correctly for multiple test-cases (TCs). 22 | The first test case where your code failed: 23 | Input: 24 | 14 25 | 12 7 5 1 13 1 10 8 11 9 2 4 3 6 26 | Its Correct output is: 27 | 1 14 28 | And Your Code's output is: 29 | 1 0 30 | */ 31 | if (res[1]==0) 32 | res[1]=n; 33 | return res; 34 | } 35 | }; 36 | 37 | // O(2n)tc 38 | // o(n)sc 39 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 1/03 Merge two sorted Arrays without extra space.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/merge-two-sorted-arrays-o1-extra-space/ 2 | 3 | int nextGap(int gap){ 4 | if (gap <= 1){ 5 | return 0; 6 | } 7 | return (gap / 2) + (gap % 2); 8 | } 9 | 10 | void merge(int arr1[], int arr2[], int n, int m) { 11 | 12 | int gap = n + m; // we took gap as sum sum the size of both the array 13 | int i, j; 14 | 15 | gap = nextGap(gap); // everytime we will get a next gap from this 16 | for(; gap > 0 ; gap = nextGap(gap) ){ 17 | 18 | //Comparing elements in first array arr1[] 19 | for(i = 0; i + gap < n; i++){ 20 | if(arr1[i] > arr1[i+gap]) // whenever element in 1st array is greater then 2nd array swap the element and move ahead 21 | swap(arr1[i], arr1[i+gap]); 22 | } 23 | 24 | //Comparing elements in both array arr1[] and arr2[] 25 | for(j = (gap > n) ? (gap - n) : 0; i < n && j < m; i++, j++ ){ 26 | if(arr1[i] > arr2[j]) // whenever element in 1st array is greater then 2nd array swap the element and move ahead 27 | swap(arr1[i], arr2[j]); 28 | } 29 | 30 | //Comparing elements in second array arr2[] 31 | if(j < m){ 32 | for(j = 0; j + gap < m; j++){ 33 | if(arr2[j] > arr2[j + gap]) 34 | swap(arr2[j], arr2[j+gap]); 35 | } 36 | } 37 | } 38 | } 39 | 40 | //tc: O(n*logn), sc:O(1) 41 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 1/04 Kadane’s Algorithm.cpp: -------------------------------------------------------------------------------- 1 | // this is the variation of dutch national flag algo it states that 2 | // all element towards the left of low will be zero 3 | // all element towards right of high will be two 4 | // everything between (Low and mid-1) will be one 5 | class Solution { 6 | public: 7 | void sortColors(vector& nums) { 8 | int low=0; 9 | int mid=0; 10 | int high=nums.size()-1; 11 | while (mid<=high) // we will move mid pointer untill it crosses high pointer 12 | { 13 | switch(nums[mid]){ 14 | // In between we will be doing three checks i.e when mid is pointing to 0,1 and 2; 15 | case 0://1st mid is pointing to zero // then we will swap index low with the index mid and increment both (low &mid) 16 | swap(nums[low],nums[mid]); 17 | low++; 18 | mid++; 19 | break; 20 | 21 | 22 | 23 | case 1: // now mid is pointing to 1 // then simply move mid pointer by one 24 | mid++; 25 | break; 26 | 27 | 28 | case 2:// now mid is pointing two // then we will swap index high with the index mid and decrement only high 29 | swap(nums[mid],nums[high]); // this time mid pointer will not be incremented 30 | high--; 31 | break; 32 | 33 | } 34 | } 35 | 36 | } 37 | }; -------------------------------------------------------------------------------- /SDE sheet solution/Day 1/05 Merge Overlapping Subintervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | vector > mergedIntervals; // declearing data structure 5 | // edge case 6 | if (intervals.size()==0) // when there is no element in intervals we will return empty interval 7 | return mergedIntervals; 8 | sort(intervals.begin(),intervals.end()); // 1st of all sort the vector 9 | vector TempInterval=intervals[0];// store 1st pair from intervals to temp intrvals // vector of size two kept in temp 10 | for (auto it : intervals) // once sorting done iterate lineraly through all the intervals 11 | { 12 | if(it[0]<=TempInterval[1]) // now check either pairs is merging or or not 13 | TempInterval[1]=max(it[1],TempInterval[1]); // whichever is maximum from the rightmost of the it and temp make a pair of that. 14 | else // if they are not merging 15 | { 16 | mergedIntervals.push_back(TempInterval); // pair which is not merged we are going to take that in merged intervals 17 | TempInterval=it; // if it does not merges with the pair then replace temp with next iterator 18 | } 19 | } 20 | mergedIntervals.push_back(TempInterval); // now whatever pair is there in temp data structure will be pushed in fianl result 21 | return mergedIntervals; 22 | } 23 | }; 24 | 25 | // tc o(nlogn)+n 26 | //sc O(n) -------------------------------------------------------------------------------- /SDE sheet solution/Day 1/06 Find the duplicate in an array of N+1 integers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 1.Take two pointers (basically integers) namely, slow and fast. Initially both will point to first element 4 | 2.Increase slow by 1 and fast by two. 5 | 3.Step 2 will be done as follows: slow = nums[slow]; fast = nums[nums[fast]]. 6 | 4.There will be one time when slow and fast will meet. They will meet in a cycle. 7 | 5.At step 4 we have to stop. 8 | 6.Now move fast to initial position i.e. fast = nums[0]. 9 | 7.Now move both slow and fast by one position till both of them meet. 10 | 8.Step 7 increment will be done as follows: slow = nums[slow]; fast = nums[fast]. 11 | 9.The node at which both slow and fast will meet will be the duplicate number. 12 | 10Return slow or fast. 13 | 14 | */ 15 | 16 | class Solution { 17 | public: 18 | int findDuplicate(vector& nums) { 19 | int slow = nums[0]; 20 | int fast = nums[0]; 21 | 22 | do 23 | { 24 | slow = nums[slow]; 25 | fast = nums[nums[fast]]; 26 | }while(slow != fast); 27 | 28 | fast = nums[0]; 29 | while(slow != fast) 30 | { 31 | slow = nums[slow]; 32 | fast = nums[fast]; 33 | } 34 | 35 | return slow; 36 | } 37 | }; -------------------------------------------------------------------------------- /SDE sheet solution/Day 2/01 Set Matrix zeros.cpp: -------------------------------------------------------------------------------- 1 | /*Approach-First of all create two vectors rowmarker and columnmarker to store the positions of column and row where the element is zero. 2 | If element in either row marker or columnmarker is 0.Then make the element in the whole matrix 0. 3 | */ 4 | 5 | void setZeroes(vector>& matrix) { 6 | int rowsize=matrix.size(); 7 | int columnsize=matrix[0].size(); 8 | vectorrowmarker(rowsize,1); // a dummy vector of size row 9 | vectorcolumnmarker(columnsize,1); // adummy vector of size colunm 10 | for(int i=0;i>& matrix) { 37 | int col0=1; 38 | int rows=matrix.size(); 39 | int col=matrix[0].size(); 40 | 41 | for (int i=0;i=0;i--) 52 | { 53 | for (int j=col-1;j>=1;j--) 54 | if(matrix[i][0]==0 || matrix[0][j]==0) 55 | matrix[i][j]=0; 56 | if (col0==0) 57 | matrix[i][0]=0; 58 | } 59 | 60 | 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 2/02 Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> m(numRows);// creating 2-D vector with rows=numRows 5 | 6 | for(int i=0;i &nums) 26 | { 27 | // initialize variable: 28 | int breakPoint = -1; 29 | 30 | // find a breakpoint: 31 | for (int i = nums.size() - 1; i > 0; i--) 32 | { 33 | if (nums[i] > nums[i - 1]) 34 | { 35 | breakPoint = i - 1; 36 | break; 37 | } 38 | } 39 | 40 | // if no breakpoint 41 | if (breakPoint < 0) 42 | { 43 | reverse(nums.begin(), nums.end()); 44 | return; 45 | } 46 | 47 | // if found a breakpoint 48 | for (int i = nums.size() - 1; i >= 0; i--) 49 | { 50 | if (nums[i] > nums[breakPoint]) 51 | { 52 | swap(nums[breakPoint], nums[i]); 53 | reverse(nums.begin() + breakPoint + 1, nums.end()); 54 | break; 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /SDE sheet solution/Day 2/04 Count Inversions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | // arr[]: Input Array 9 | // N : Size of the Array arr[] 10 | // Function to count inversions in the array. 11 | long long int merge(long long int arr[], long long int s, long long int e, long long int N) { 12 | long long int mid = (s + e) / 2; 13 | long long int i = s; 14 | long long int j = mid + 1; 15 | long long int k = s; 16 | long long int temp[N]; 17 | long long int invert = 0; 18 | while (i <= mid && j <= e) { 19 | if (arr[i] <= arr[j]) 20 | temp[k++] = arr[i++]; 21 | else { 22 | temp[k++] = arr[j++]; 23 | invert += mid - i + 1; 24 | } 25 | } 26 | while (j <= e) 27 | temp[k++] = arr[j++]; 28 | while (i <= mid) 29 | temp[k++] = arr[i++]; 30 | for (int i = s; i <= e; i++) 31 | arr[i] = temp[i]; 32 | return invert; 33 | 34 | } 35 | long long int inversion(long long arr[], long long int s, long long int e, long long int N) { 36 | if (s >= e) 37 | return 0; 38 | long long int mid = (s + e) / 2; 39 | long long int x = inversion(arr, s, mid, N); 40 | long long int y = inversion(arr, mid + 1, e, N); 41 | long long int z = merge(arr, s, e, N); 42 | return x + y + z; 43 | } 44 | long long int inversionCount(long long arr[], long long N) 45 | { 46 | return inversion(arr, 0, N - 1, N); 47 | } 48 | 49 | }; 50 | 51 | // { Driver Code Starts. 52 | 53 | int main() { 54 | 55 | long long T; 56 | cin >> T; 57 | 58 | while(T--){ 59 | long long N; 60 | cin >> N; 61 | 62 | long long A[N]; 63 | for(long long i = 0;i> A[i]; 65 | } 66 | Solution obj; 67 | cout << obj.inversionCount(A,N) << endl; 68 | } 69 | 70 | return 0; 71 | } 72 | // } Driver Code Ends 73 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 2/05 Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector &prices) { 4 | int ret = 0; 5 | for (int p = 1; p < prices.size(); ++p) 6 | ret += max(prices[p] - prices[p - 1], 0); 7 | return ret; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 2/06 Stock Buy and Sell.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector > stockBuySell(vector A, int n){ 4 | vector> res; 5 | 6 | for(int i = 0; i < n-1; i++){ 7 | if(A[i] < A[i+1]) 8 | res.push_back({i, i+1}); 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 2/07 Rotate matrix.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/ 2 | // solution : https://uploads.disquscdn.com/images/a2bee3cd55348623b01e27c191b7dc79a53de1dabbc7a64e2619bcec6e391acb.png 3 | // This is ratate image fron leetcode 4 | class Solution { 5 | public: 6 | void rotate(vector>& matrix) { 7 | int n= matrix.size(); 8 | // this loops are for the transpose if the matrix 9 | for (int i=0;i>& matrix, int target) { 4 | int n=matrix.size(); // numbers of the row 5 | int m=matrix[0].size(); // numbers of the column 6 | int i=0; // keep i at starting of the matrix. 7 | int j=m-1; // keep j on the right most top corner. 8 | if (!matrix.size()) return false; 9 | while ((i>=0 && i=0 && j<=m)){ // as long as i & j is not going out of the bound 10 | if (matrix[i][j]==target) 11 | return true; 12 | else if (matrix[i][j]>target) 13 | j--; // move to left 14 | else if(matrix[i][j]& nums) { 4 | int candidate=nums[0]; 5 | int count =1; 6 | for (int i=0;i& nums) { 26 | sort(nums.begin(), nums.end()); 27 | int len = nums.size(); 28 | return nums[len / 2]; 29 | } 30 | }; -------------------------------------------------------------------------------- /SDE sheet solution/Day 3/04 Majority Element II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Here what we are essentially doing is making pairs with majority element, fix a majority element increment the count till you find a different one and decrease the count for different elements. Here decreasing the count simply means, making a pair of majority and non-majority element and removing them from the array. Once the count reaches zero, make a new majority element because the deleted pairs had an equal count of majority and non-majority element. When we reach the end we will have the majority element selected due to the process we followed and since it was mentioned in the question that "You may assume that the array is non-empty and the majority element always exist in the array" we do not verify the solution. You can do if you want to in a single pass. 3 | 4 | So, taking the idea from the basic problem we can extend it to find majority elements that appear more than n/3 times. 5 | In this case, first we nneed to understand that there will be atmost 2 majority elements. This is pretty self explainatory if you read the question carefully. 6 | 7 | Okay, so just like we did in the simpler version of the problem, we take two elements as the majority element and maintain their frequency counts and once we find an element that differs from the two, we decrement both the elements' counts. In this case we have to look for triplets instead of pairs. This essentially means that we form a triplet out of 2 majority and one non-majority element and remove them from the array. We repeat the process till we consider all array elements and simply verify if the elements we found are correct or not, which can be done in a single pass. 8 | 9 | Please refer the code below and try to understand it with the explaination I provided above. 10 | Time Complexity: O(n) 11 | Space Complexity: O(1) 12 | */ 13 | class Solution { 14 | public: 15 | vector majorityElement(vector& nums) 16 | { 17 | int sz = nums.size(); 18 | int num1 = -1, num2 = -1, count1 = 0, count2 = 0, i; 19 | for (i = 0; i < sz; i++) 20 | { 21 | if (nums[i] == num1) 22 | count1++; 23 | else if (nums[i] == num2) 24 | count2++; 25 | else if (count1 == 0) 26 | { 27 | num1 = nums[i]; 28 | count1 = 1; 29 | } 30 | else if (count2 == 0) 31 | { 32 | num2 = nums[i]; 33 | count2 = 1; 34 | } 35 | else 36 | { 37 | count1--; 38 | count2--; 39 | } 40 | } 41 | vector ans; 42 | count1 = count2 = 0; 43 | for (i = 0; i < sz; i++) 44 | { 45 | if (nums[i] == num1) 46 | count1++; 47 | else if (nums[i] == num2) 48 | count2++; 49 | } 50 | if (count1 > sz/3) 51 | ans.push_back(num1); 52 | if (count2 > sz/3) 53 | ans.push_back(num2); 54 | return ans; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 3/05 Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | // Since the robot can only move right and down, when it arrives at a point, it either arrives from left or above. If we use dp[i][j] for the number of unique paths 2 | // to arrive at the point (i, j), then the state equation is dp[i][j] = dp[i][j - 1] + dp[i - 1][j]. Moreover, we have the base cases dp[0][j] = dp[i][0] = 1 for all valid i and j. 3 | 4 | 5 | class Solution { 6 | public: 7 | int uniquePaths(int m, int n) { 8 | vector> dp(m, vector(n, 1)); 9 | for (int i = 1; i < m; i++) { 10 | for (int j = 1; j < n; j++) { 11 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 12 | } 13 | } 14 | return dp[m - 1][n - 1]; 15 | } 16 | }; 17 | /* 18 | The above solution runs in O(m * n) time and costs O(m * n) space. However, you may have noticed that each time when we update dp[i][j], we only need dp[i - 1][j] 19 | (at the previous row) and dp[i][j - 1] (at the current row). So we can reduce the memory usage to just two rows (O(n)). 20 | */ 21 | 22 | class Solution { 23 | public: 24 | int uniquePaths(int m, int n) { 25 | vector pre(n, 1), cur(n, 1); 26 | for (int i = 1; i < m; i++) { 27 | for (int j = 1; j < n; j++) { 28 | cur[j] = pre[j] + cur[j - 1]; 29 | } 30 | swap(pre, cur); 31 | } 32 | return pre[n - 1]; 33 | } 34 | }; 35 | /* 36 | Further inspecting the above code, pre[j] is just the cur[j] before the update. So we can further reduce the memory usage to one row. 37 | */ 38 | class Solution { 39 | public: 40 | int uniquePaths(int m, int n) { 41 | vector cur(n, 1); 42 | for (int i = 1; i < m; i++) { 43 | for (int j = 1; j < n; j++) { 44 | cur[j] += cur[j - 1]; 45 | } 46 | } 47 | return cur[n - 1]; 48 | } 49 | }; 50 | /* 51 | Now, you may wonder whether we can further reduce the memory usage to just O(1) space since the above code seems to use only two variables (cur[j] and cur[j - 1]). 52 | However, since the whole row cur needs to be updated for m - 1 times (the outer loop) based on old values, all of its values need to be saved and thus O(1)-space is 53 | impossible. However, if you are having a DP problem without the outer loop and just the inner one, then it will be possible. 54 | */ 55 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 3/06 Reverse Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int merge(vector &nums, int l, int m, int h) { 4 | int count=0; 5 | int j=m+1; 6 | for(int i=l;i<=m;++i) { 7 | while(j<=h && nums[i] > 2LL*nums[j]) ++j; 8 | count += (j - (m+1)); 9 | } 10 | // merge of two sorted array 11 | vector temp; 12 | int left=l,right=m+1; 13 | // loop till on of them execuested 14 | while(left<=m && right<=h) { 15 | if(nums[left]<=nums[right]) temp.push_back(nums[left++]); 16 | else temp.push_back(nums[right++]); 17 | } 18 | // remaining elements of left side 19 | while(left<=m) temp.push_back(nums[left++]); 20 | // remaining elements of right side 21 | while(right<=h) temp.push_back(nums[right++]); 22 | // assingn in main vector after merging 23 | for(int i=l;i<=h;++i) { 24 | nums[i]=temp[i-l]; 25 | } 26 | return count; 27 | } 28 | int mergeSort(vector &nums, int l, int h) { 29 | if(l>=h) return 0; // A single element does not contain any pair 30 | int m=(l+h)/2; 31 | int count=0; 32 | count += mergeSort(nums,l,m); // count from left side of vector 33 | count += mergeSort(nums,m+1,h); // count from right side of vector 34 | count += merge(nums,l,m,h); // count merge 35 | return count; 36 | } 37 | int reversePairs(vector& nums) { 38 | return mergeSort(nums, 0, nums.size()-1); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 4/01 Two Sum.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum/discuss/1162422/Explained-with-pen-and-paper-and-gfg-ref 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // ---------------------------------------------------------- O(n*m) 9 | class Solution { 10 | public: 11 | vector twoSum(vector& nums, int target) { 12 | for (int i=0;i twoSum(vector& nums, int target) { 28 | int n= nums.size(); 29 | unordered_map hmap; 30 | vector ans; 31 | for (int i=0;i twoSum(vector& nums, int target) { 49 | vector twoSumAns; 50 | for (int i = 0; i < nums.size(); i++) { 51 | for (int j = nums.size() - 1; j > i; j--) { 52 | if (nums[i] + nums[j] == target) { 53 | twoSumAns.push_back(i); 54 | twoSumAns.push_back(j); 55 | } 56 | } 57 | } 58 | return twoSumAns; 59 | } 60 | }; 61 | void PrintVector(vector& input) { 62 | for (int i = 0; i < input.size(); i++) { 63 | cout << input[i] << " "; 64 | } 65 | cout << endl; 66 | } 67 | 68 | int main() { 69 | Solution solution; 70 | vector nums = {2,7,11,15}; 71 | int Sum = 9; 72 | /* vector nums = { 3,2,4 }; 73 | int Sum = 6;*/ 74 | vector result = solution.twoSum(nums, Sum); 75 | PrintVector(result); 76 | } 77 | 78 | 79 | 80 | ----------------------------------------------------------------------------------------------------------------------- 81 | 82 | class Solution { 83 | public: 84 | vector twoSum(vector& nums, int target) { 85 | int num1; // make a variable for finding the element 86 | for (int i = 0; i < nums.size(); i++) // iterate through the vector 87 | { 88 | num1 = target - nums[i]; // we will get the 2nd item to bve find 89 | for (int k = i+1; k < nums.size(); k++ ) // for finding the position 90 | { 91 | if(nums[k] == num1) 92 | { 93 | return {i,k}; // just take both the subscript 94 | } 95 | } 96 | } 97 | return {}; 98 | } 99 | }; 100 | // ------------------------------------------------------------------------------------------------------------ 101 | 102 | 103 | class Solution { 104 | public: 105 | std::vector twoSum(vector& nums, int target) { 106 | 107 | //map for finding the complement of current number in the vector 108 | std::unordered_map hashmap; 109 | 110 | //loop for checking if the complement of the current integer exist in the map 111 | for(int i = 0; i < nums.size(); i++){ 112 | //if complement has found, return current index and index of compliment 113 | //index of complement is its value in the map 114 | //with C++20, mappy.contains would probably been better 115 | if(hashmap.count(target-nums[i])){ 116 | //return the index of the current integer in the vector, and the index of the complement 117 | return {i,(hashmap[target - nums[i]])}; 118 | } 119 | //if complement has not been passed by yet, modify the complement's value with its index 120 | hashmap[nums[i]] = i; 121 | } 122 | //return empty vector if no integers answer found 123 | return {}; 124 | } 125 | }; 126 | 127 | ------------------------------------------------------------------------------------------------------------------ 128 | 129 | class Solution { 130 | public: 131 | vector twoSum(vector& nums, int target) { 132 | unordered_map hmap; 133 | for (int i=0;i map = new HashMap(); 148 | 149 | for(int i = 0; i < nums.length; i++) 150 | map.put(nums[i], i); 151 | 152 | for(int i = 0; i < nums.length; i++) 153 | if(map.containsKey(target - nums[i]) && i != map.get(target - nums[i])) 154 | return new int[] {i, map.get(target - nums[i])}; 155 | 156 | return new int[2]; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 4/02 4Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > fourSum(vector &num, int target) { 4 | 5 | vector > res; 6 | 7 | if (num.empty()) 8 | return res; 9 | 10 | std::sort(num.begin(),num.end()); 11 | 12 | for (int i = 0; i < num.size(); i++) { 13 | 14 | int target_3 = target - num[i]; 15 | 16 | for (int j = i + 1; j < num.size(); j++) { 17 | 18 | int target_2 = target_3 - num[j]; 19 | 20 | int front = j + 1; 21 | int back = num.size() - 1; 22 | 23 | while(front < back) { 24 | 25 | int two_sum = num[front] + num[back]; 26 | 27 | if (two_sum < target_2) front++; 28 | 29 | else if (two_sum > target_2) back--; 30 | 31 | else { 32 | 33 | vector quadruplet(4, 0); 34 | quadruplet[0] = num[i]; 35 | quadruplet[1] = num[j]; 36 | quadruplet[2] = num[front]; 37 | quadruplet[3] = num[back]; 38 | res.push_back(quadruplet); 39 | 40 | // Processing the duplicates of number 3 41 | while (front < back && num[front] == quadruplet[2]) ++front; 42 | 43 | // Processing the duplicates of number 4 44 | while (front < back && num[back] == quadruplet[3]) --back; 45 | 46 | } 47 | } 48 | 49 | // Processing the duplicates of number 2 50 | while(j + 1 < num.size() && num[j + 1] == num[j]) ++j; 51 | } 52 | 53 | // Processing the duplicates of number 1 54 | while (i + 1 < num.size() && num[i + 1] == num[i]) ++i; 55 | 56 | } 57 | 58 | return res; 59 | 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 4/03 Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector &num) { 4 | if(num.empty()){ 5 | return 0; 6 | } 7 | unordered_set set; 8 | for(int i = 0; i < num.size(); i++){ 9 | set.insert(num[i]); 10 | } 11 | int maxLength = 0; 12 | while(!set.empty()){ 13 | int length = 1; 14 | unordered_set::iterator seed = set.begin(); 15 | for(int i = *seed;; i--){ 16 | if(set.find(i - 1) != set.end()){ 17 | length++; 18 | set.erase(i - 1); 19 | } 20 | else{ 21 | break; 22 | } 23 | } 24 | for(int i = *seed;; i++){ 25 | if(set.find(i + 1) != set.end()){ 26 | length++; 27 | set.erase(i + 1); 28 | } 29 | else{ 30 | break; 31 | } 32 | } 33 | set.erase(*seed); 34 | maxLength = max(maxLength, length); 35 | } 36 | return maxLength; 37 | } 38 | 39 | 40 | }; 41 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 5/01 Reverse a LinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode *t=NULL; 15 | while (head) 16 | { 17 | ListNode *next=head->next; 18 | head->next=t; 19 | t=head; 20 | head=next; 21 | } 22 | return t; 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /SDE sheet solution/Day 5/02 Find middle of LinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode * slow=head; 15 | ListNode* fast=head; 16 | 17 | while (fast && fast->next) 18 | { 19 | slow=slow->next; 20 | fast=fast->next->next; 21 | } 22 | return slow; 23 | } 24 | }; -------------------------------------------------------------------------------- /SDE sheet solution/Day 5/03 Merge Two Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 | ListNode dummy{0}; 5 | auto curr = &dummy; 6 | 7 | while (l1 && l2) { 8 | if (l1->val <= l2->val) { 9 | curr->next = l1; 10 | l1 = l1->next; 11 | } else { 12 | curr->next = l2; 13 | l2 = l2->next; 14 | } 15 | curr = curr->next; 16 | } 17 | curr->next = l1 ? l1 : l2; 18 | 19 | return dummy.next; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 5/04 Remove Nth Node From End of List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | 10 | * }; 11 | 12 | The difference between the final node and the to_be_delete node is N. And here the assumption is that n is always valid. 13 | 14 | fast pointer points to the node which is N step away from the to_be_delete node. 15 | 16 | slow pointer points to the to_be_delete node. 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* removeNthFromEnd(ListNode* head, int n) { 21 | //Make an offset pointer and make it move n spaces. 22 | ListNode* offset = head; 23 | 24 | //Then start moving from head again(using curr) so that you can get the n-last position 25 | ListNode* curr = head; 26 | 27 | //Prev required so that curr can be deleted rightaway 28 | ListNode* prev = new ListNode(-1); 29 | prev->next = curr; 30 | 31 | for(int i = 1; i < n; ++i) 32 | offset = offset->next; 33 | 34 | 35 | while(offset->next != NULL) 36 | { 37 | offset = offset->next; 38 | prev=curr; 39 | curr = curr->next; 40 | } 41 | 42 | prev->next = curr->next; 43 | 44 | //For cases where only one number is there OR the first number is deleted 45 | if(curr==head) 46 | return head->next; 47 | 48 | //Delete the node from memory to avoid leak 49 | delete curr; 50 | 51 | return head; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------------- 55 | 56 | class Solution { 57 | public: 58 | ListNode* removeNthFromEnd(ListNode* head, int n) { 59 | 60 | ListNode* start = new ListNode(0); 61 | start->next = head; 62 | 63 | ListNode* fast = start; 64 | ListNode* slow = start; 65 | 66 | for(int i = 1; i <= n; ++i) 67 | fast = fast->next; 68 | 69 | while(fast->next != NULL) 70 | { 71 | fast = fast->next; 72 | slow = slow->next; 73 | } 74 | 75 | slow->next = slow->next->next; 76 | 77 | return start->next; 78 | } 79 | }; 80 | -------------------------------------------------------------------------------- /SDE sheet solution/Day 6/01 Intersection of Two Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) 12 | { 13 | ListNode *p1 = headA; 14 | ListNode *p2 = headB; 15 | 16 | if (p1 == NULL || p2 == NULL) return NULL; 17 | 18 | while (p1 != NULL && p2 != NULL && p1 != p2) { 19 | p1 = p1->next; 20 | p2 = p2->next; 21 | 22 | 23 | // Any time they collide or reach end together without colliding 24 | // then return any one of the pointers. 25 | // 26 | if (p1 == p2) return p1; 27 | 28 | // 29 | // If one of them reaches the end earlier then reuse it 30 | // by moving it to the beginning of other list. 31 | // Once both of them go through reassigning, 32 | // they will be equidistant from the collision point. 33 | // 34 | if (p1 == NULL) p1 = headB; 35 | if (p2 == NULL) p2 = headA; 36 | } 37 | 38 | return p1; 39 | } 40 | }; -------------------------------------------------------------------------------- /SDE sheet solution/Day 6/02 Linked List Cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | ->Use two pointers, walker and runner. 9 | ->walker moves step by step. runner moves two steps at time. 10 | ->if the Linked List has a cycle walker and runner will meet at some 11 | point. 12 | */ 13 | class Solution { 14 | public: 15 | bool hasCycle(ListNode *head) { 16 | if (head==NULL || head->next==NULL) return false; 17 | ListNode *slow=head; 18 | ListNode *fast=head; 19 | while (fast->next && fast->next->next) 20 | { 21 | slow=slow->next; 22 | fast=fast->next->next; 23 | if (slow==fast) 24 | return true; 25 | } 26 | return false; 27 | } 28 | }; 29 | 30 | /* 31 | 32 | use faster and lower runner solution. (2 pointers) 33 | the faster one move 2 steps, and slower one move only one step. 34 | if there's a circle, the faster one will finally "catch" the slower one. 35 | (the distance between these 2 pointers will decrease one every time.) 36 | 37 | if there's no circle, the faster runner will reach the end of linked list. (NULL) 38 | */ -------------------------------------------------------------------------------- /SDE sheet solution/Day 6/04 Check if a LinkedList is palindrome or not.cpp: -------------------------------------------------------------------------------- 1 | bool isPalindrome(ListNode* head) { 2 | 3 | stack nodeStack; // A stack is first in last out, traversing a list is quasi-first in first out 4 | 5 | ListNode* pHead = head; 6 | while (pHead) { 7 | nodeStack.push(pHead); 8 | pHead = pHead->next; 9 | } 10 | 11 | while (head) { 12 | if (head->val != nodeStack.top()->val) { // We are going forwards on the linked list and backwards via a stack. 13 | return false; // If the values differ, well it isn't a palindrome. 14 | } 15 | nodeStack.pop(); // Similar to head->next but in reverse. 16 | head = head->next; 17 | } 18 | return true; // If we get to the end of the linked list and the values in the stack didn't differ from those 19 | // of the linked list, then it is a palindrome. 20 | } 21 | --------------------------------------------------------------------------------