├── README.md ├── c ├── 1143. Longest Common Subsequence.c ├── 125- Valid Palindrome.c ├── 2. Ugly Number.c ├── 200- Number of Islands.c ├── 21- Merge Two Sorted Lists.c ├── 35- Search Insert Position.c └── 7. Reverse Integer.c ├── categorize_scripts.py ├── cpp ├── 0043_multiply_strings.cpp ├── 0485_max_consecutive_ones.cpp ├── 1-Two_Sum.cpp ├── 10. Regular Expression Matching.cpp ├── 11.Container_with_most_water.cpp ├── 115. Distinct Subsequences.cpp ├── 12. Integer to Roman.cpp ├── 121_Best Time to Buy and Sell Stock.cpp ├── 127_Word_Ladder.cpp ├── 13.Roman_to_Integer.cpp ├── 132. Palindrome_Partitioning_II.cpp ├── 1346. Check If N and Its Double Exist ├── 142_Linked_List_Cycle_II.cpp ├── 1431. Kids With the Greatest Number of Candies.cpp ├── 1458. Max Dot Product of Two Subsequences.cpp ├── 1470.Shuffle the Array.cpp ├── 14_Longest_common_prefix.cpp ├── 152_maximum_product_subarray.cpp ├── 160.IntersectionofLinkedLists.cpp ├── 1603_design_parking_system.cpp ├── 162_Find_Peak_Element.cpp ├── 164_MaximumGap.cpp ├── 1929.Concatenation_of_Array.cpp ├── 199. Binary Tree Right Side View.cpp ├── 19_Remove_Nth_Node_From_End_of_List.cpp ├── 2-Add_Two_Numbers.cpp ├── 20. Valid Parentheses.cpp ├── 204. CountPrimes.cpp ├── 206. Reverse Linked List.cpp ├── 21. Merge Two Sorted Lists.cpp ├── 215_Kth_Largest_Element_in_an_Array.cpp ├── 22. Generate Parentheses.cpp ├── 230_kth_Elementh_BST_Morris_Traversal.cpp ├── 26. Remove Duplicates from Sorted Array.cpp ├── 26.Remove Duplicates from Sorted Array.cpp ├── 263. Ugly Number.cpp ├── 268. Missing Number ├── 273.Integer_to_English_Words.cpp ├── 278. First Bad Version ├── 279.perfect-squares.cpp ├── 27_Remove Element.cpp ├── 283. Move Zeroes ├── 3-Longest_Substring_Without_Repeating_Characters.cpp ├── 300. Longest Increasing Subsequence.cpp ├── 31_Next Permutation.cpp ├── 329_Longest_Increasing_Path_in_a_Matrix.cpp ├── 33. Search in Rotated Sorted Array.cpp ├── 338_Counting_Bits.cpp ├── 350.IntersectionOfTwoArraysII.cpp ├── 367. Valid Perfect Square ├── 36_Valid_Sudoku.cpp ├── 374._Guess_Number_Higher_or_Lower.cpp ├── 4. Median of Two Sorted Arrays.cpp ├── 412. Fizz Buzz.cpp ├── 416. Partition Equal Subset Sum.cpp ├── 42.Trapping_rain_water.cpp ├── 44_Wildcard_Matching.cpp ├── 451_Sort_Characters_By_Frequency.cpp ├── 452.minimum-number-of-arrows-to-burst-balloons.cpp ├── 48-Rotate_Image.cpp ├── 48.rotate_image.cpp ├── 485. Max Consecutive Ones.cpp ├── 485_max_consecutive_ones.cpp ├── 5-Longest_Palindromic_Substring.cpp ├── 50. Pow(x,n).cpp ├── 51. nQueens.cpp ├── 516. Longest Palindromic Subsequence.cpp ├── 52. nQueens2.cpp ├── 55_Jump Game.cpp ├── 567.Permutation_in_string.cpp ├── 62.Unique Paths.cpp ├── 62_Unique Paths.cpp ├── 665_Non-decreasing_Array.cpp ├── 66_Plus_One.cpp ├── 695.Maxareaisland.cpp ├── 695_Max_Area_of_Island.cpp ├── 7. Reverse Integer ├── 707.design-linked-list.cpp ├── 713. Subarray Product Less Than K.cpp ├── 72_Edit_distance.cpp ├── 746. Min Cost Climbing Stairs.cpp ├── 74_search-a-2d-matrix.cpp ├── 775.Global and Local Inversions ├── 79. Word Search.cpp ├── 829. Consecutive Numbers Sum ├── 887. Super Egg Drop.cpp ├── 887_Super_Egg_Drop.cpp ├── 888. Fair Candy Swap ├── 8_String_to_integer(atoi).cpp ├── 90_subsetsii.cpp ├── 91_Decode_Ways.cpp ├── 97. Interleaving String.cpp ├── 987. Vertical Order Traversal of a Binary Tree ├── Median_of_2_sorted_arrays.cpp ├── printpattern.cpp └── sum of Contiguos array ├── go ├── 338_Counting_Bits.go └── 9. Palindrome Number.go ├── java ├── 11.ContainerWithMostWater.java ├── 15. 3Sum.java ├── 156. Binary Tree Upside-Down.java ├── 19. Remove_Nth_node_from_end_of_list.java ├── 1_Two_Sum.java ├── 20. Valid Parentheses.java ├── 215. KthLargestElementInArray.java ├── 22_Generate_Parentheses.java ├── 236. Lowest Common Ancestor of a Binary Tree.java ├── 243. Shortest Word Distance.java ├── 2_Add_Two_Numbers.java ├── 36. Valid Sudoku.java ├── 42. Trapping Rain Water.java ├── 442. Find_All_Duplicates_in_an_Array.java ├── 442_Find_All_Duplicates_in_an_Array.java ├── 455.AssignCokkies.java ├── 494. Target Sum.java ├── 509. Fibonacci Number.java ├── 55. Jump Game.java ├── 55_Jump Game.java ├── 58.Length of Last Word.java ├── 6. ZigZag Conversion.java ├── 605.Can Place Flowers.java ├── 645.Set Mismatch.java ├── 7. Reverse Integer.java ├── 75.Sort Colors.java ├── 88. Merge Sorted Array.java ├── 9.PalindromeNumber.java └── 96. Unique Binary Search Trees.java ├── javascript ├── 461.js ├── 535.js ├── 7. Reverse Integer.js ├── 832.js └── 890.js ├── py ├── 1. Two Sum.py ├── 100. Same Tree.py ├── 100.Same Tree.py ├── 101. Symmetric Tree.py ├── 102. Binary Tree Level Order Traversal.py ├── 104. Maximum Depth of Binary Tree.py ├── 1044. Longest Duplicate Substring.py ├── 108. Convert Sorted Array to Binary Search Tree.py ├── 1095. Find in Mountain Array.py ├── 11. Container With Most Water.py ├── 118. Pascal's Triangle.py ├── 118.PascalTriangle.py ├── 12. Integer to Roman.py ├── 120. Triangle.py ├── 1200. Minimum Absolute Difference.py ├── 121.Best Time to Buy and Sell Stock.py ├── 122. Best Time to Buy and Sell Stock II.py ├── 125. Valid Palindrome.py ├── 1290. Convert Binary Number in a LinkedList to Integer.py ├── 1291. Sequential Digits.py ├── 1295. Find Numbers with Even Number of Digits.py ├── 13. Roman to Integer.py ├── 136. Single Number.py ├── 136. Single_number.py ├── 14. Longest Common Prefix.py ├── 141. Linked List Cycle.py ├── 143. Reorder List ├── 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.py ├── 15. 3Sum.py ├── 1605.Find_Valid_Matrix_Given_Row_and_Column_Sums.py ├── 1606.Find_Servers_That_Handled_Most_Number_of_Requests.py ├── 1608.Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py ├── 1611.Minimum_One_Bit_Operations_to_Make_Integers_Zero.py ├── 162. Find Peak Element.py ├── 167. Two Sum II - Input array is sorted.py ├── 1689. Partitioning Into Minimum Number Of Deci-binary Numbers.py ├── 169. Majority Element.py ├── 1696. Jump Game VI.py ├── 18. 4Sum ├── 189. Rotate Array.py ├── 19. Remove Nth Node From End of List.py ├── 1920. Build Array from Permutation.py ├── 198. House Robber.py ├── 20. Valid Parentheses.py ├── 202. Happy Number.py ├── 204. Count Primes.py ├── 206. Reverse Linked List.py ├── 207. Course Schedule.py ├── 21. Merge Two Sorted Lists.py ├── 214. Shortest Palindrome.py ├── 217. Contains Duplicate.py ├── 234. Palindrome Linked List.py ├── 236. Lowest Common Ancestor of a Binary Tree.py ├── 240. Search a 2D Matrix II.py ├── 242. Valid Anagram.py ├── 26. Remove Duplicates from Sorted Array.py ├── 279. PerfectSquares.py ├── 28. Implement strStr().py ├── 283. Move Zeroes.py ├── 29. Divide Two Integers.py ├── 3 .Longest Substring Without Repeating Characters.py ├── 300. Longest Increasing Subsequence.py ├── 31.Next_Permutation.py ├── 34. Find First and Last Position of Element in Sorted Array.py ├── 350. Intersection of Two Arrays II.py ├── 36. Valid Sudoku.py ├── 37.Sudoku Solver.py ├── 38. Count and Say.py ├── 387. First Unique Character in a String.py ├── 4. Median of Two Sorted Arrays.py ├── 40. Combination Sum II.py ├── 412. FizzBuzz.py ├── 415. Add Strings.py ├── 442. find-all-duplicates-in-an-array.py ├── 45.Jump_Game_II.py ├── 48. Rotate Image.py ├── 5. Longest Palindromic Substring.py ├── 50. Pow(x, n).py ├── 53. Maximum Subarray.py ├── 535. Encode and Decode TinyURL.py ├── 55. Jump Game ├── 62. Unique Paths.py ├── 64. Minimum Path Sum.py ├── 66. Plus One.py ├── 695. Max Area of Island.py ├── 7. Reverse Integer.py ├── 70. Climbing Stairs.py ├── 72. Edit Distance.py ├── 791. Custom Sort String.py ├── 8. String to Integer (atoi).py ├── 9. Palindrome Number.py ├── 931. Minimum Falling Path Sum.py └── 98. Validate Binary Search Tree.py └── sql ├── 176. Second Highest Salary.sql ├── 182. Duplicate Emails.sql ├── 185. Department top three salaries ├── 596. Classes more than 5 students.sql └── 81.Article views 2.sql /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Solutions 2 | Collection of all the LeetCode problem solutions using different programming languages. 3 | 4 | To contribute, you can make a file for the problem of your choice from [LeetCode](https://leetcode.com/), it can be in any programming language of your choice. Please don't duplicate the problems unless there is a better way to solve the same problem. 5 | 6 | ### Steps to contribute: 7 | 1. Fork this repository. ([How to fork?](https://docs.github.com/en/get-started/quickstart/fork-a-repo#forking-a-repository)) 8 | 2. Create a branch. ([How to create a branch?](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/managing-branches#creating-a-branch)) 9 | 3. Create a file with the name of the problem, Commit, Push 10 | 4. Finally raise a PR! ([How to create a PR?](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork)) 11 | 12 | P.S. Star the repo if you like it. ⭐ 13 | 14 | Happy Coding :smiley: 15 | -------------------------------------------------------------------------------- /c/1143. Longest Common Subsequence.c: -------------------------------------------------------------------------------- 1 | 2 | int longestCommonSubsequence(char* ar1,char* ar2) 3 | { 4 | int l1,l2,i,j,check=0; 5 | 6 | l1=strlen(ar1); 7 | l2=strlen(ar2); 8 | 9 | //CREATING DP TABLE 10 | int **arr=(int **)malloc((l1+1)*sizeof(int *)); 11 | for(i=0;i<=l1;i++) 12 | arr[i]=(int *)malloc((l2+1)*sizeof(int *)); 13 | 14 | //PREPROCESSING DP TABLE 15 | for(i=0;i<=l1;i++) 16 | arr[i][0]=0; 17 | for(i=0;i<=l2;i++) 18 | arr[0][i]=0; 19 | 20 | //DP ITERATION STARTS 21 | for(i=1;i<=l1;i++) 22 | { 23 | for(j=1;j<=l2;j++) 24 | { 25 | if(ar1[i-1]==ar2[j-1]) 26 | arr[i][j]=arr[i-1][j-1]+1; 27 | else 28 | { 29 | if(arr[i-1][j]>arr[i][j-1]) 30 | arr[i][j]=arr[i-1][j]; 31 | else 32 | arr[i][j]=arr[i][j-1]; 33 | } 34 | } 35 | } 36 | 37 | 38 | i=l1; 39 | j=l2; 40 | 41 | return arr[l1][l2]; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /c/125- Valid Palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char ch2lower(char ch) { 6 | if (ch >= 'A' && ch <= 'Z') 7 | ch += 0x20; 8 | 9 | return ch; 10 | } 11 | 12 | bool isPalindrome(char *s) { 13 | int len = strlen(s); 14 | int head, tail; 15 | head = tail = 0; 16 | 17 | tail = len - 1; 18 | 19 | while (head <= tail) { 20 | while (ch2lower(s[head]) < '0' 21 | || (ch2lower(s[head]) > '9' && ch2lower(s[head]) < 'a') 22 | || ch2lower(s[head]) > 'z') 23 | { 24 | head++; 25 | if (head > tail) break; 26 | } 27 | 28 | while (ch2lower(s[tail]) < '0' 29 | || (ch2lower(s[tail]) > '9' && ch2lower(s[tail]) < 'a') 30 | || ch2lower(s[tail]) > 'z') 31 | { 32 | tail--; 33 | if (head > tail) break; 34 | } 35 | 36 | if (head > tail) break; 37 | 38 | if (ch2lower(s[head]) != ch2lower(s[tail])) return false; 39 | 40 | head++; 41 | tail--; 42 | } 43 | 44 | return true; 45 | } 46 | 47 | int main() { 48 | char s1[] = "A man, a plan, a canal: Panama"; 49 | char s2[] = "race a car"; 50 | char s3[] = ""; 51 | char s4[] = "a"; 52 | char s5[] = ".,"; 53 | char s6[] = "."; 54 | char s7[] = " "; 55 | 56 | printf("%d\n", isPalindrome(s1)); 57 | printf("%d\n", isPalindrome(s2)); 58 | printf("%d\n", isPalindrome(s3)); 59 | printf("%d\n", isPalindrome(s4)); 60 | printf("%d\n", isPalindrome(s5)); 61 | printf("%d\n", isPalindrome(s6)); 62 | printf("%d\n", isPalindrome(s7)); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /c/2. Ugly Number.c: -------------------------------------------------------------------------------- 1 | bool isUgly(int num){ 2 | if(num <= 0) 3 | return false; 4 | 5 | if(num == 1) 6 | return true; 7 | 8 | while((num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0)) { 9 | if(num % 2 == 0) 10 | num /= 2; 11 | if(num % 3 == 0) 12 | num /= 3; 13 | if(num % 5 == 0) 14 | num /= 5; 15 | if(num == 1) 16 | return true; 17 | } 18 | return false; 19 | } 20 | -------------------------------------------------------------------------------- /c/200- Number of Islands.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void dfs(char **grid, bool **visited, int i, int j, int numRows, int numColumns) { 7 | if (i >= 0 && i < numRows && j >= 0 && j < numColumns && !visited[i][j]) { 8 | visited[i][j] = 1; 9 | if (grid[i][j] == '1') { /* island */ 10 | dfs(grid, visited, i, j - 1, numRows, numColumns); /* left */ 11 | dfs(grid, visited, i, j + 1, numRows, numColumns); /* right */ 12 | dfs(grid, visited, i - 1, j, numRows, numColumns); /* up */ 13 | dfs(grid, visited, i + 1, j, numRows, numColumns); /* down */ 14 | } 15 | } 16 | } 17 | 18 | int numIslands(char **grid, int numRows, int numColumns) { 19 | if (grid == NULL || numRows == 0 || strlen(grid[0]) == 0) 20 | return 0; 21 | 22 | int i, j; 23 | int count = 0; 24 | 25 | bool **visited = (bool **)calloc(numRows, sizeof(bool *)); 26 | for (i = 0; i < numRows; i++) { 27 | visited[i] = (bool *)calloc(numColumns, sizeof(bool)); 28 | } 29 | 30 | for (i = 0; i < numRows; i++) { 31 | for (j = 0; j < numColumns; j++) { 32 | if (!visited[i][j]) { /* has not been visited */ 33 | if (grid[i][j] == '1') /* it's an island */ 34 | count++; 35 | dfs(grid, visited, i, j, numRows, numColumns); 36 | } 37 | } 38 | } 39 | return count; 40 | } 41 | 42 | int main() { 43 | int row = 3; 44 | int col = 3; 45 | char **grid = (char **)calloc(1, sizeof(char *)); 46 | 47 | grid[0] = "111"; 48 | grid[1] = "010"; 49 | grid[2] = "111"; 50 | 51 | /* should be 1 */ 52 | printf("%d\n", numIslands(grid, row, col)); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /c/21- Merge Two Sorted Lists.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { 10 | if (l1 == NULL) return l2; 11 | if (l2 == NULL) return l1; 12 | 13 | struct ListNode *p1 = l1; 14 | struct ListNode *p2 = l2; 15 | 16 | struct ListNode *ret = NULL; 17 | struct ListNode **p = &ret; 18 | 19 | while (1) { 20 | if (p1 && p2) { 21 | if (p1->val <= p2->val) { 22 | *p = p1; 23 | p1 = p1->next; 24 | } 25 | else { 26 | *p = p2; 27 | p2 = p2->next; 28 | } 29 | } 30 | else if (p1 && p2 == NULL) { 31 | *p = p1; 32 | p1 = p1->next; 33 | } 34 | else if (p2 && p1 == NULL) { 35 | *p = p2; 36 | p2 = p2->next; 37 | } 38 | else break; 39 | 40 | p = &((*p)->next); 41 | } 42 | 43 | return ret; 44 | } 45 | 46 | int main() { 47 | 48 | struct ListNode *headA 49 | = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 50 | struct ListNode *headB 51 | = (struct ListNode *)calloc(3, sizeof(struct ListNode)); 52 | 53 | struct ListNode **p = &headA; 54 | int i; 55 | for (i = 1; i <= 5; i++) { 56 | (*p)->val = i; 57 | (*p)->next = *p + 1; 58 | p = &(*p)->next; 59 | } 60 | *p = NULL; 61 | 62 | p = &headB; 63 | for (i = 3; i <= 7; i += 2) { 64 | (*p)->val = i; 65 | (*p)->next = *p + 1; 66 | p = &(*p)->next; 67 | } 68 | *p = NULL; 69 | 70 | printf("List A: "); 71 | struct ListNode *q = headA; 72 | while (q != NULL) { 73 | printf("%d->", q->val); 74 | q = q->next; 75 | } 76 | printf("N\n"); 77 | 78 | printf("List B: "); 79 | q = headB; 80 | while (q) { 81 | printf("%d->", q->val); 82 | q = q->next; 83 | } 84 | printf("N\n"); 85 | 86 | struct ListNode *ret = mergeTwoLists(headA, headB); 87 | 88 | printf("Merged: "); 89 | q = ret; 90 | while (q) { 91 | printf("%d->", q->val); 92 | q = q->next; 93 | } 94 | printf("N\n"); 95 | 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /c/35- Search Insert Position.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int searchInsert(int A[], int n, int target) { 4 | int l, r, m; 5 | l = 0; 6 | r = n - 1; 7 | while (l <= r) { 8 | m = (l + r) / 2; 9 | if (A[m] == target) { 10 | return m; 11 | } 12 | else if (A[m] < target) { 13 | l = m + 1; 14 | } 15 | else { 16 | r = m - 1; 17 | } 18 | } 19 | return l; 20 | } 21 | 22 | int main() { 23 | int num[] = {1}; 24 | /* should be 1 */ 25 | printf("%d\n", searchInsert(num, sizeof(num)/sizeof(num[0]), 4)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /c/7. Reverse Integer.c: -------------------------------------------------------------------------------- 1 | int reverse(long long x) 2 | {int flag=0; 3 | 4 | if ( x>=0 ) { 5 | flag=1; 6 | 7 | } 8 | if (x<0 ) { 9 | flag=0; 10 | x=(-1)*x; 11 | 12 | } 13 | 14 | long long d,s=0; 15 | if(x >=0 && x <= 9) 16 | { 17 | return x; 18 | } 19 | while(x != 0) 20 | { 21 | d = x%10; 22 | s = s*10 + d; 23 | x = x/10; 24 | } 25 | if ( flag==1 && s > 2147483647) { 26 | 27 | return 0; 28 | } 29 | if (flag==0 && s > 2147483648) { 30 | 31 | 32 | return 0; 33 | } 34 | if(flag==0) 35 | return s*(-1); 36 | else 37 | return s; 38 | } -------------------------------------------------------------------------------- /categorize_scripts.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import argparse 3 | import os 4 | import shutil 5 | 6 | class CategoriseFolderContents: 7 | def __init__(self) -> None: 8 | self.skip_this_file = sys.argv[0] 9 | self.skip_git_dir = '.git' 10 | self.skip_readme_md = 'README.md' 11 | 12 | def group_files_by_ext(self, dir_path = os.getcwd()): 13 | all_files = os.listdir(dir_path) 14 | if self.skip_git_dir in all_files: 15 | all_files.remove(self.skip_git_dir) 16 | if self.skip_readme_md in all_files: 17 | all_files.remove(self.skip_readme_md) 18 | if self.skip_this_file in all_files: 19 | all_files.remove(self.skip_this_file) 20 | 21 | for file in all_files: 22 | try: 23 | extension = os.path.splitext(file)[1] 24 | extension = extension.replace('.','') 25 | extension_dir = os.path.join(dir_path, extension) 26 | if not os.path.exists(extension_dir): 27 | os.makedirs(extension_dir,exist_ok=True) 28 | if not os.path.isdir(file): 29 | shutil.move(file, extension_dir) 30 | except: 31 | pass 32 | 33 | def group_contents(self,arguments): 34 | if arguments.groupby == 'ext': 35 | self.group_files_by_ext() 36 | 37 | if __name__ == "__main__": 38 | argp = argparse.ArgumentParser() 39 | argp.add_argument('--groupby', help="filter to group the scripts in the folder", choices=['ext'], default='ext') 40 | arguments = argp.parse_args() 41 | cfc = CategoriseFolderContents() 42 | cfc.group_contents(arguments) -------------------------------------------------------------------------------- /cpp/0043_multiply_strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string multiply(string num1, string num2) { 4 | string result(num1.size() + num2.size(), '0'); 5 | for (int i = num1.size() - 1; i >= 0; --i) { 6 | for (int j = num2.size() - 1; j >= 0; --j) { 7 | int sum = (num1[i] - '0') * (num2[j] - '0') + (result[i + j + 1] - '0'); 8 | result[i + j + 1] = sum % 10 + '0'; 9 | result[i + j] += sum / 10; 10 | } 11 | } 12 | int pos = result.find_first_not_of('0'); 13 | if (pos != string::npos) { 14 | return result.substr(pos); 15 | } 16 | return "0"; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /cpp/0485_max_consecutive_ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | if(nums.size()==0) { 5 | return 0; 6 | } 7 | int i=0; 8 | int count=0; 9 | int lastCount=0; 10 | while (i twoSum(vector& nums, int target) { 5 | vector sol; 6 | for(int i=0;i twoSum(vector& nums, int target) { 24 | vector sol; 25 | unordered_map m; 26 | for(int i=0;i=m and i>=n) return 1; 16 | if(j>=m) return 0; 17 | //dynamic programming conversion 18 | if(dp[i][j]!=-1) return dp[i][j]; 19 | 20 | 21 | // recursive logic 22 | bool match=(i& height) { 4 | int l= 0; 5 | int r = height.size()- 1; 6 | int res =0 ; 7 | while(l>& dp) { 4 | if (ti == t.length()) { 5 | return dp[si][ti] = 1; 6 | } 7 | if (si == s.length()) { 8 | return dp[si][ti] = 0; 9 | } 10 | if (dp[si][ti] != -1) { 11 | return dp[si][ti]; 12 | } 13 | int ans; 14 | if (s[si] == t[ti]) 15 | ans = distSub(s, t, si + 1, ti + 1, dp) + distSub(s, t, si + 1, ti, dp); 16 | else 17 | ans = distSub(s, t, si + 1, ti, dp); 18 | 19 | return dp[si][ti] = ans; 20 | } 21 | int numDistinct(string s, string t) { 22 | int sl = s.length(); 23 | int tl = t.length(); 24 | vector> dp(sl + 1, vector(tl + 1, - 1)); 25 | return distSub(s, t, 0, 0, dp); 26 | } 27 | }; -------------------------------------------------------------------------------- /cpp/12. Integer to Roman.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const int val[13] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 4 | const string rom[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 5 | 6 | string intToRoman(int N) { 7 | string ans = ""; 8 | for (int i = 0; N; i++){ 9 | while (N >= val[i]) { 10 | ans += rom[i]; 11 | N -= val[i]; 12 | } 13 | } 14 | return ans; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /cpp/121_Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | //Best time to buy and sell stock 2 | class Solution { 3 | public: 4 | int maxProfit(vector& prices) { 5 | int maxProfit=0; 6 | int minPrice=INT_MAX; 7 | for(int i=0;i1){ 14 | return false; 15 | } 16 | } 17 | 18 | } 19 | 20 | 21 | return true; 22 | 23 | 24 | } 25 | 26 | 27 | int ladderLength(string beginWord, string endWord, vector& wordList) { 28 | 29 | 30 | if(beginWord==endWord){ 31 | return 0; 32 | } 33 | 34 | unordered_map> adj; 35 | vector vis(wordList.size(),0); 36 | for(int i=0;i q; 52 | 53 | for(int j=0;j M{ 5 | {'I', 1}, 6 | {'V', 5}, 7 | {'X', 10}, 8 | {'L', 50}, 9 | {'C', 100}, 10 | {'D', 500}, 11 | {'M', 1000}, 12 | }; 13 | int sum = M[s.back()]; 14 | for(int i =0 ;i> dp(n + 1, vector(n + 1, 0)); 36 | for (int i = n; i > 0; i--) { 37 | for(int j = i; j <= n ;j++) { 38 | 39 | // the substring of length 1 will always be palindrome 40 | if (i == j ) { 41 | dp[i][j] = 1; 42 | } 43 | 44 | // checking for the length 2 substring 45 | else if (j == i + 1 && s[i] == s[j]) { 46 | dp[i][j] = 1; 47 | } 48 | 49 | // checking if corner character matched, check it with middle part that we already calculated 50 | else if(s[i] == s[j]) { 51 | dp[i][j] = dp[i + 1][j - 1]; 52 | } 53 | } 54 | } 55 | 56 | // dp vector for storing answer, where index denotes the size of substring from starting index 57 | vector res(n + 1, 0); 58 | 59 | for(int i = 1; i <= n; i++){ 60 | res[i] = i - 1; 61 | } 62 | 63 | for (int i = 2; i <= n; i++){ 64 | for(int j = i; j > 1; j--){ 65 | // checking for different partitons 66 | if(dp[j][i]){ 67 | res[i] = min (res[i], res[j-1] + 1); 68 | } 69 | } 70 | // if the whole substring is palindrome 71 | if (dp[1][i]) { 72 | res[i] = 0; 73 | } 74 | 75 | } 76 | for (int i = 1; i <= n; i++){ 77 | } 78 | return res[n] ; 79 | } 80 | }; 81 | -------------------------------------------------------------------------------- /cpp/1346. Check If N and Its Double Exist: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkIfExist(vector& arr) { 4 | sort(arr.begin(),arr.end()); 5 | int l,h; 6 | 7 | for(int i=0;i(2*arr[i])){ 23 | h=mid-1; 24 | } 25 | else{ 26 | l=mid+1; 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /cpp/142_Linked_List_Cycle_II.cpp: -------------------------------------------------------------------------------- 1 | //Problem Link -: https://leetcode.com/problems/linked-list-cycle-ii/ 2 | 3 | 4 | //Solution -: 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | ListNode *detectCycle(ListNode *head) { 17 | if (head == NULL or head -> next == NULL or head->next->next == NULL) { 18 | return NULL; 19 | } 20 | ListNode *p1 = head; 21 | ListNode *p2 = head; 22 | int flag = 0; 23 | while (p1 != NULL and p2 != NULL and p2 -> next != NULL) { 24 | p1 = p1->next; 25 | p2 = p2->next->next; 26 | if (p1 == p2) { 27 | flag++; 28 | break; 29 | } 30 | } 31 | if (flag == 0) { 32 | return NULL; 33 | } 34 | else { 35 | p1 = head; 36 | while (p1 != p2) { 37 | p1 = p1->next; 38 | p2 = p2->next; 39 | } 40 | return p1; 41 | } 42 | } 43 | }; -------------------------------------------------------------------------------- /cpp/1431. Kids With the Greatest Number of Candies.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector kidsWithCandies(vector& candies, int extraCandies) { 4 | vector out; 5 | int max = *max_element(candies.begin(), candies.end()); 6 | 7 | for(int i=0; i < candies.size(); i++){ 8 | if(candies[i]+extraCandies >= max) 9 | out.push_back(true); 10 | else 11 | out.push_back(false); 12 | } 13 | 14 | return out; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /cpp/1458. Max Dot Product of Two Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProd(vector& arr1, vector& arr2, int i1, int i2, vector>& dp) { 4 | if (i1 == arr1.size() || i2 == arr2.size()) { 5 | return -1e7; 6 | } 7 | if (dp[i1][i2] != -1) { 8 | return dp[i1][i2]; 9 | } 10 | int cv = arr1[i1] * arr2[i2] ; 11 | int a = cv + maxProd(arr1, arr2, i1 + 1, i2 + 1, dp); 12 | int b = maxProd(arr1, arr2, i1, i2 + 1, dp); 13 | int c = maxProd(arr1, arr2, i1 + 1, i2, dp); 14 | return dp[i1][i2] = max(max(a, b), max(cv, c)); 15 | } 16 | int maxDotProduct(vector& nums1, vector& nums2) { 17 | vector> dp(nums1.size(), vector(nums2.size(), -1)); 18 | return maxProd(nums1, nums2, 0, 0, dp); 19 | } 20 | }; -------------------------------------------------------------------------------- /cpp/1470.Shuffle the Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector shuffle(vector& nums, int n) { 4 | vector ans; 5 | int j=n; 6 | for(int i=0;i& strs) { 4 | string ans=""; 5 | if(strs.size()==0){ 6 | return ans; 7 | } 8 | int minlen=INT_MAX; 9 | for(string s:strs){ 10 | if(s.length()& nums) { 4 | // currentPos-> currentPositive 5 | //currenNeg -->current Negative 6 | 7 | int i, n = nums.size(); 8 | int currentPos = nums[0], currentNeg = nums[0]; 9 | int result = nums[0]; 10 | 11 | for (i = 1; i < n; i++) 12 | { 13 | if (nums[i] == 0) 14 | { 15 | currentPos = 0; 16 | currentNeg = 0; 17 | result = max(result, 0); 18 | } 19 | else if (nums[i] > 0) 20 | { 21 | 22 | result = max(max(result, nums[i]), currentPos * nums[i]); 23 | currentPos = max(nums[i], currentPos * nums[i]); 24 | currentNeg = currentNeg * nums[i]; 25 | } 26 | 27 | else 28 | { 29 | 30 | result = max(max(result, nums[i]), currentNeg * nums[i]); 31 | int term = currentPos; 32 | currentPos = max(nums[i], currentNeg * nums[i]); 33 | currentNeg = min(term * nums[i], nums[i]); 34 | } 35 | } 36 | return result; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /cpp/160.IntersectionofLinkedLists.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* temp = headA; ListNode* temp2 = headB; int a=0; int b=0; 14 | 15 | if (temp==NULL || temp2==NULL) 16 | return NULL; 17 | 18 | while (temp){a++; temp=temp->next;} 19 | while(temp2){b++; temp2= temp2->next;} 20 | 21 | temp = headA; temp2 = headB; 22 | int d= abs(a-b); 23 | 24 | if (a>b) 25 | { 26 | for (int i=0;inext; 28 | } 29 | 30 | else if (b>a) 31 | { 32 | for(int i=0;inext; 34 | } 35 | 36 | while (temp || temp2) 37 | { 38 | if (temp==temp2) return temp; 39 | 40 | temp = temp->next; temp2=temp2->next; 41 | } 42 | 43 | return temp; 44 | } 45 | 46 | }; 47 | -------------------------------------------------------------------------------- /cpp/1603_design_parking_system.cpp: -------------------------------------------------------------------------------- 1 | class ParkingSystem { 2 | public: 3 | vector count; 4 | ParkingSystem(int big, int medium, int small) { 5 | count = {big, medium, small}; 6 | } 7 | 8 | bool addCar(int carType) { 9 | return count[carType - 1]-- > 0; 10 | } 11 | }; 12 | 13 | /** 14 | * Your ParkingSystem object will be instantiated and called as such: 15 | * ParkingSystem* obj = new ParkingSystem(big, medium, small); 16 | * bool param_1 = obj->addCar(carType); 17 | */ -------------------------------------------------------------------------------- /cpp/162_Find_Peak_Element.cpp: -------------------------------------------------------------------------------- 1 | // Question link : https://leetcode.com/problems/find-peak-element/submissions/ 2 | 3 | class Solution: 4 | def findPeakElement(self, nums: List[int]) -> int: 5 | b = 0 6 | e = len(nums)-1 7 | while(b 2 | using namespace std; 3 | 4 | 5 | int maxdiff(vector a){ 6 | if(a.size()<2){ 7 | return 0; 8 | } 9 | int mini =a[0]; 10 | int maxa=0; 11 | 12 | // Finding max and min value in the input array 13 | for(int i =0; i>n; 60 | vector a; 61 | int value; 62 | for (int i=0;i>value; 64 | a.push_back(value); 65 | } 66 | cout< getConcatenation(vector& nums) { 4 | vector ans(2*nums.size()); 5 | int size=nums.size(); 6 | int i; 7 | for(i=0;i rightside; 4 | void find(TreeNode* root, int num){ 5 | if(root == NULL) return; 6 | rightside[num] = root->val; 7 | find(root->left, num+1); 8 | find(root->right, num+1); 9 | } 10 | 11 | vector rightSideView(TreeNode* root) { 12 | 13 | if(root == NULL) return {}; 14 | find(root, 0); 15 | vector ans; 16 | for(auto it: rightside){ 17 | ans.push_back(it.second); 18 | } 19 | 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /cpp/19_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 | class Solution { 12 | public: 13 | ListNode* removeNthFromEnd(ListNode* head, int n) { 14 | ListNode *slow=head,*fast=head,*curr=head; 15 | while(n>=1) 16 | { 17 | fast=fast->next; 18 | n--; 19 | } 20 | if(fast==nullptr) 21 | { 22 | head=curr->next; 23 | delete(curr); 24 | return head; 25 | } 26 | while(fast->next!=nullptr) 27 | { 28 | slow=slow->next; 29 | fast=fast->next; 30 | } 31 | curr=slow->next; 32 | slow->next=curr->next; 33 | delete(curr); 34 | return head; 35 | } 36 | }; -------------------------------------------------------------------------------- /cpp/2-Add_Two_Numbers.cpp: -------------------------------------------------------------------------------- 1 | //Method 1 - Iterative 2 | /** 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * ListNode *next; 7 | * ListNode() : val(0), next(nullptr) {} 8 | * ListNode(int x) : val(x), next(nullptr) {} 9 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 15 | int carry = 0; 16 | ListNode ans(0); 17 | ListNode *temp = &ans; 18 | while(carry || l1 || l2){ 19 | carry+=(l1?l1->val:0)+(l2?l2->val:0); 20 | temp->next = new ListNode(carry%10); 21 | temp = temp->next; 22 | carry/=10; 23 | if(l1) l1 = l1->next; 24 | if(l2) l2 = l2->next; 25 | } 26 | return ans.next; 27 | } 28 | }; 29 | 30 | //Method 2 - Recursive 31 | /** 32 | * Definition for singly-linked list. 33 | * struct ListNode { 34 | * int val; 35 | * ListNode *next; 36 | * ListNode() : val(0), next(nullptr) {} 37 | * ListNode(int x) : val(x), next(nullptr) {} 38 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 39 | * }; 40 | */ 41 | class Solution { 42 | public: 43 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 44 | if(!l1 && !l2) return NULL; 45 | int carry = (l1?l1->val:0)+(l2?l2->val:0); 46 | ListNode *newHead = new ListNode(carry%10), *next = l1?l1->next:NULL; 47 | carry/=10; 48 | if(next) next->val+=carry; 49 | else if(carry) next = new ListNode(carry); 50 | newHead->next = addTwoNumbers(l2?l2->next:NULL, next); 51 | return newHead; 52 | } 53 | }; -------------------------------------------------------------------------------- /cpp/20. Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValid(string s) 5 | { 6 | 7 | stack st; 8 | for (char c : s) 9 | { 10 | if (c == '(' || c == '{' || c == '[') 11 | { 12 | st.push(c); 13 | } 14 | else 15 | { 16 | if (st.empty()) 17 | return false; 18 | if (c == ')' && st.top() != '(') 19 | return false; 20 | if (c == '}' && st.top() != '{') 21 | return false; 22 | if (c == ']' && st.top() != '[') 23 | return false; 24 | st.pop(); 25 | } 26 | } 27 | return st.empty(); 28 | } 29 | }; -------------------------------------------------------------------------------- /cpp/204. CountPrimes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrimes(int n) { 4 | int count=0; 5 | bool prime[n+1]; 6 | memset(prime,true,sizeof(prime)); 7 | for(int p=2;p*pnext == NULL) return head; 16 | 17 | ListNode* p = NULL; 18 | ListNode* q = head; 19 | ListNode* r = head->next; 20 | 21 | while(q != NULL){ 22 | 23 | q->next = p; 24 | p = q; 25 | q = r; 26 | if(r) r = r->next; 27 | 28 | } 29 | 30 | return p; 31 | 32 | } 33 | }; -------------------------------------------------------------------------------- /cpp/21. Merge Two Sorted Lists.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* mergeTwoLists(ListNode* l1, ListNode* l2) { 14 | ListNode* dummy= new ListNode(0); 15 | ListNode* tail=dummy; 16 | while(l1 && l2){ 17 | if(l1->val < l2->val){ 18 | tail->next=l1; 19 | l1=l1->next; 20 | } 21 | else{ 22 | tail->next=l2; 23 | l2=l2->next; 24 | } 25 | tail=tail->next; 26 | } 27 | if(l1) 28 | tail->next=l1; 29 | else 30 | tail->next=l2; 31 | return dummy->next; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/215_Kth_Largest_Element_in_an_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { 4 | 5 | priority_queuepq; 6 | 7 | for(auto x:nums) 8 | pq.push(x); 9 | 10 | k--; 11 | 12 | 13 | while(k--) 14 | pq.pop(); 15 | 16 | 17 | return pq.top(); 18 | 19 | 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /cpp/22. Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector ans; 4 | void help(string s, int open, int close, int n) { 5 | if(close == n) { 6 | ans.push_back(s); 7 | return; 8 | } 9 | if(open == n) 10 | help(s + ')', open, close + 1, n); 11 | else { 12 | help(s + '(', open + 1, close, n); 13 | if(open > close) 14 | help(s + ')', open, close + 1, n); 15 | } 16 | } 17 | vector generateParenthesis(int n) { 18 | help("", 0, 0, n); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /cpp/230_kth_Elementh_BST_Morris_Traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthSmallest(TreeNode* root, int k) { 4 | int count = 0; 5 | int res = -1; 6 | TreeNode* cur = root; 7 | while(cur != NULL) { 8 | if(cur->left == NULL) { 9 | count++; 10 | if(count == k) res = cur->val; 11 | cur = cur->right; 12 | } 13 | else { 14 | TreeNode* prev = cur->left; 15 | while(prev->right != NULL && prev->right != cur) { 16 | prev = prev->right; 17 | } 18 | 19 | if(prev->right == NULL) { 20 | prev->right = cur; 21 | cur = cur->left; 22 | } 23 | else { 24 | prev->right = NULL; 25 | count++; 26 | if(count == k) res = cur->val; 27 | cur = cur->right; 28 | } 29 | } 30 | } 31 | return res; 32 | } 33 | }; -------------------------------------------------------------------------------- /cpp/26. Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int n = nums.size(); 5 | int j = 0; 6 | for(int i=0;i& nums) { 4 | nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); 5 | return nums.size(); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /cpp/263. Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int n) { 4 | if(n == 1) return true; 5 | if(n <= 0) return false; 6 | if(n == 2 || n == 5 || n == 3) return true; 7 | if(n % 2 == 0) return isUgly(n / 2); 8 | if(n % 3 == 0) return isUgly(n / 3); 9 | if(n % 5 == 0) return isUgly(n / 5); 10 | return false; 11 | } 12 | }; -------------------------------------------------------------------------------- /cpp/268. Missing Number: -------------------------------------------------------------------------------- 1 | /*Link Of Question : https://leetcode.com/problems/missing-number/ 2 | 268. Missing Number 3 | Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.*/ 4 | //Solution : 5 | 6 | class Solution { 7 | public: 8 | int missingNumber(vector& a) { 9 | 10 | int i,n=a.size(); 11 | int j=n; 12 | 13 | for(i=0;i> tens { 7 | {90, "Ninety"}, 8 | {80, "Eighty"}, 9 | {70, "Seventy"}, 10 | {60, "Sixty"}, 11 | {50, "Fifty"}, 12 | {40, "Forty"}, 13 | {30, "Thirty"}, 14 | {20, "Twenty"}, 15 | {10, "-"}, 16 | }; 17 | 18 | vector> underTwenty { 19 | {19, "Nineteen"}, 20 | {18, "Eighteen"}, 21 | {17, "Seventeen"}, 22 | {16, "Sixteen"}, 23 | {15, "Fifteen"}, 24 | {14, "Fourteen"}, 25 | {13, "Thirteen"}, 26 | {12, "Twelve"}, 27 | {11, "Eleven"}, 28 | {10, "Ten"}, 29 | { 9, "Nine"}, 30 | { 8, "Eight"}, 31 | { 7, "Seven"}, 32 | { 6, "Six"}, 33 | { 5, "Five"}, 34 | { 4, "Four"}, 35 | { 3, "Three"}, 36 | { 2, "Two"}, 37 | { 1, "One"}, 38 | }; 39 | string numberToWords(int num) { 40 | string num_str = ""; 41 | 42 | if (num == 0) 43 | return "Zero"; 44 | 45 | if ( num >= 1000000000 ) { 46 | num_str += numberToWords(num/1000000000) + " Billion"; 47 | num = num % 1000000000; 48 | num_str += (num?" ":""); 49 | } 50 | 51 | if ( num >= 1000000 ) { 52 | num_str += numberToWords(num/1000000) + " Million"; 53 | num = num % 1000000; 54 | num_str += (num?" ":""); 55 | } 56 | 57 | if ( num >= 1000 ) { 58 | num_str += numberToWords(num/1000) + " Thousand"; 59 | num = num % 1000; 60 | num_str += (num?" ":""); 61 | } 62 | 63 | if ( num >= 100 ) { 64 | num_str += numberToWords(num/100) + " Hundred"; 65 | num = num % 100; 66 | num_str += (num?" ":""); 67 | } 68 | 69 | if ( num / 10 > 1) { 70 | num_str += tens[tens.size() - num/10].second; 71 | num = num % 10; 72 | num_str += (num?" ":""); 73 | } 74 | 75 | if ( num > 0 ) 76 | num_str += underTwenty[underTwenty.size() - num].second; 77 | 78 | return num_str; 79 | } 80 | }; -------------------------------------------------------------------------------- /cpp/278. First Bad Version: -------------------------------------------------------------------------------- 1 | // The API isBadVersion is defined for you. 2 | // bool isBadVersion(int version); 3 | 4 | class Solution { 5 | public: 6 | int firstBadVersion(int n) { 7 | int l =1; 8 | int r = n; 9 | int mid ; 10 | while(l& nums, int val) 5 | { 6 | nums.erase(remove(nums.begin() ,nums.end(),val),nums.end()); 7 | return nums.size(); 8 | } 9 | }; 10 | 11 | /* 12 | Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. 13 | 14 | Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. 15 | 16 | Return k after placing the final result in the first k slots of nums. 17 | 18 | Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. 19 | 20 | Custom Judge: 21 | 22 | The judge will test your solution with the following code: 23 | 24 | int[] nums = [...]; // Input array 25 | int val = ...; // Value to remove 26 | int[] expectedNums = [...]; // The expected answer with correct length. 27 | // It is sorted with no values equaling val. 28 | 29 | int k = removeElement(nums, val); // Calls your implementation 30 | 31 | assert k == expectedNums.length; 32 | sort(nums, 0, k); // Sort the first k elements of nums 33 | for (int i = 0; i < actualLength; i++) { 34 | assert nums[i] == expectedNums[i]; 35 | } 36 | If all assertions pass, then your solution will be accepted. 37 | 38 | 39 | 40 | Example 1: 41 | 42 | Input: nums = [3,2,2,3], val = 3 43 | Output: 2, nums = [2,2,_,_] 44 | Explanation: Your function should return k = 2, with the first two elements of nums being 2. 45 | It does not matter what you leave beyond the returned k (hence they are underscores). 46 | Example 2: 47 | 48 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 49 | Output: 5, nums = [0,1,4,0,3,_,_,_] 50 | Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. 51 | Note that the five elements can be returned in any order. 52 | It does not matter what you leave beyond the returned k (hence they are underscores). 53 | 54 | 55 | Constraints: 56 | 57 | 0 <= nums.length <= 100 58 | 0 <= nums[i] <= 50 59 | 0 <= val <= 100 60 | */ -------------------------------------------------------------------------------- /cpp/283. Move Zeroes: -------------------------------------------------------------------------------- 1 | void moveZeroes(vector& nums) { 2 | int n = nums.size(); 3 | 4 | // Count the zeroes 5 | int numZeroes = 0; 6 | for (int i = 0; i < n; i++) { 7 | numZeroes += (nums[i] == 0); 8 | } 9 | 10 | // Make all the non-zero elements retain their original order. 11 | vector ans; 12 | for (int i = 0; i < n; i++) { 13 | if (nums[i] != 0) { 14 | ans.push_back(nums[i]); 15 | } 16 | } 17 | 18 | // Move all zeroes to the end 19 | while (numZeroes--) { 20 | ans.push_back(0); 21 | } 22 | 23 | // Combine the result 24 | for (int i = 0; i < n; i++) { 25 | nums[i] = ans[i]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cpp/3-Longest_Substring_Without_Repeating_Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | vector hash(256, -1); 5 | int ans = 0, start = -1; 6 | for(int i=0;istart) start = hash[s[i]]; 8 | hash[s[i]] = i; 9 | ans = max(ans, i-start); 10 | } 11 | return ans; 12 | } 13 | }; 14 | 15 | // Another approach for solving this problem. Yet easy to understand for beginners. 16 | class Solution { 17 | public: 18 | int lengthOfLongestSubstring(string s) { 19 | int n = s.size(); 20 | vector track = {0}; 21 | for(int i = 0; i < n; i++){ 22 | int l = 1; 23 | string ch = ""; 24 | for(int j = i+1; j < n; j++){ 25 | if(s[i] == s[j]){ // level-1 checking goes here 26 | break; // search for the 1st character with every char in every loop 27 | } 28 | int found = ch.find(s[j]); // level-2 checking goes here 29 | if(found != string::npos){ // if char founds in newly formed string it returns index if not it returns string::npos 30 | break; 31 | } else { 32 | ch += s[j]; 33 | l += 1; 34 | } 35 | } 36 | track.push_back(l); //stores length of all possible longest substring 37 | } 38 | int longest_length = *max_element(track.begin(), track.end()); //determines the largest value in the vector 39 | return longest_length; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /cpp/300. Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int LISFromLeftToRight(vector & arr, vector& dp) { 4 | int n = arr.size(); 5 | int ans = -1; 6 | for (int i = 0; i < n; i++) { 7 | dp[i] = 1; 8 | for (int j = 0; j < i; j++) { 9 | int m = dp[j]; 10 | if (arr[i] > arr[j]) { 11 | dp[i] = max(dp[i], m + 1); 12 | } 13 | } 14 | ans = max(ans, dp[i]); 15 | } 16 | return ans; 17 | } 18 | int lengthOfLIS(vector& nums) { 19 | int s = nums.size(); 20 | vector dp(s); 21 | return LISFromLeftToRight(nums, dp); 22 | } 23 | }; -------------------------------------------------------------------------------- /cpp/31_Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | vector ans=nums; 5 | vector temp; 6 | for(int i=nums.size()-1;i>0;i--){ 7 | if(nums[i]<=nums[i-1]){ 8 | temp.push_back(nums[i]); 9 | ans.pop_back(); 10 | } 11 | else{ 12 | temp.push_back(nums[i]); 13 | ans.pop_back(); 14 | int index=upper_bound(temp.begin(),temp.end(),nums[i-1])-temp.begin(); 15 | ans.pop_back(); 16 | ans.push_back(temp[index]); 17 | temp.erase(temp.begin()+index); 18 | temp.insert(temp.begin()+index,nums[i-1]); 19 | for(int i=0;i> &dp,vector> &matrix,int path){ 7 | if(dp[i][j]!=-1){ 8 | return dp[i][j]; 9 | } 10 | int dx[]={0,0,-1,1}; 11 | int dy[]={1,-1,0,0}; 12 | for(int k=0;k<4;k++){ 13 | if(i+dx[k]>=0 && i+dx[k]=0 && j+dy[k]>& matrix) { 28 | vector> dp(matrix.size(),vector(matrix[0].size(),-1)); 29 | int ans=1; 30 | int path=0; 31 | for(int i=0;i& strs) { 4 | string ans=""; 5 | if(strs.size()==0){ 6 | return ans; 7 | } 8 | int minlen=INT_MAX; 9 | for(string s:strs){ 10 | if(s.length() countBits(int n) { 7 | vector ans(n+1); 8 | vector dp; 9 | dp.push_back(0); 10 | for(int i=1; i<=n; i++) 11 | { 12 | if(i%2==0) 13 | dp.push_back(dp[i/2]); 14 | else 15 | dp.push_back(dp[i/2]+1); 16 | } 17 | return dp; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /cpp/350.IntersectionOfTwoArraysII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& nums1, vector& nums2) { 4 | int arr[1001]; 5 | vector ans; 6 | fill_n(arr, 1001, 0); 7 | int sz1= nums1.size(); 8 | int sz2= nums2.size(); 9 | if(sz1>sz2) 10 | { 11 | for(int i=0; i0) 16 | { 17 | ans.push_back(nums2[i]); 18 | arr[nums2[i]]--; 19 | } 20 | } 21 | } 22 | else 23 | { 24 | for(int i=0; i0) 29 | { 30 | ans.push_back(nums1[i]); 31 | arr[nums1[i]]--; 32 | } 33 | } 34 | } 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /cpp/367. Valid Perfect Square: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPerfectSquare(int num){ 4 | if(floor(double(sqrt(num)))==ceil(double(sqrt(num)))) 5 | return true; 6 | else 7 | return false; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /cpp/36_Valid_Sudoku.cpp: -------------------------------------------------------------------------------- 1 | //Problem Link -: https://leetcode.com/problems/valid-sudoku/ 2 | 3 | class Solution { 4 | public: 5 | bool isValidSudokuHelper(int i, int j, vector>board) { 6 | int grp_num = 3 * (i / 3) + (j / 3); 7 | for (int k = 0; k < 9; k++) { 8 | if (board[i][j] == board[i][k] and j != k) { 9 | return false; 10 | } 11 | } 12 | for (int k = 0; k < 9; k++) { 13 | if (board[i][j] == board[k][j] and i != k) { 14 | return false; 15 | } 16 | } 17 | int new_i = 3 * (i / 3), new_j = 3 * (j / 3); 18 | for (int k = new_i; k < new_i + 3; k++) { 19 | for (int l = new_j; l < new_j + 3; l++) { 20 | if (k != i and l != j and board[k][l] == board[i][j]) { 21 | return false; 22 | } 23 | } 24 | } 25 | return true; 26 | } 27 | bool isValidSudoku(vector>& board) { 28 | for (int i = 0; i < board.size(); i++) { 29 | for (int j = 0; j < board[0].size(); j++) { 30 | if (board[i][j] != '.') 31 | if (isValidSudokuHelper(i, j, board) == false) 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /cpp/374._Guess_Number_Higher_or_Lower.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param num your guess 4 | * @return -1 if num is lower than the guess number 5 | * 1 if num is higher than the guess number 6 | * otherwise return 0 7 | * int guess(int num); 8 | */ 9 | 10 | class Solution { 11 | public: 12 | int guessNumber(int n) { 13 | return gn(1,n); 14 | } 15 | int gn(long long l,int h){ 16 | switch(guess((l+h)/2)){ 17 | case 0: 18 | return (l+h)/2; 19 | case 1: 20 | return gn((l+h)/2+1,h); 21 | case -1: 22 | return gn(l,(l+h)/2); 23 | } 24 | return 1; 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /cpp/4. Median of Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | // median of two sorted arrays 2 | #include 3 | using namespace std; 4 | 5 | /* This function returns median of ar1[] and ar2[]. 6 | Assumption in this function: 7 | Both ar1[] and ar2[] are sorted arrays */ 8 | int getMedian(int ar1[], int ar2[], int n, int m) 9 | { 10 | int i = 0; /* Current index of input array ar1[] */ 11 | int j = 0; /* Current index of input array ar2[] */ 12 | int count; 13 | int m1 = -1, m2 = -1; 14 | 15 | // Since there are (n+m) elements, 16 | // There are following two cases 17 | // if n+m is odd then the middle 18 | //index is median i.e. (m+n)/2 19 | if((m + n) % 2 == 1) 20 | { 21 | for (count = 0; count <= (n + m)/2; count++) 22 | { 23 | if(i != n && j != m) 24 | { 25 | m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; 26 | } 27 | else if(i < n) 28 | { 29 | m1 = ar1[i++]; 30 | } 31 | // for case when j ar2[j]) ? ar2[j++] : ar1[i++]; 51 | } 52 | else if(i < n) 53 | { 54 | m1 = ar1[i++]; 55 | } 56 | // for case when j fizzBuzz(int n) { 4 | 5 | vector res; 6 | 7 | for(int i = 1; i <= n; i++){ 8 | 9 | if(i%3 == 0 && i%5 == 0){ 10 | res.push_back("FizzBuzz"); 11 | } else if(i%3 == 0){ 12 | res.push_back("Fizz"); 13 | } else if(i%5 == 0){ 14 | res.push_back("Buzz"); 15 | } else { 16 | res.push_back(to_string(i)); 17 | } 18 | 19 | } 20 | 21 | return res; 22 | 23 | } 24 | }; -------------------------------------------------------------------------------- /cpp/416. Partition Equal Subset Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sumPartition(vector& arr, int idx, int tar, vector>& dp) { 4 | if (tar == 0 || idx == arr.size()) 5 | { 6 | if (tar == 0) 7 | return dp[idx][tar] = 1; 8 | 9 | return dp[idx][tar] = 0; 10 | } 11 | if (dp[idx][tar] != -1) { 12 | return dp[idx][tar]; 13 | } 14 | int ans = 0; 15 | if (tar - arr[idx] >= 0) 16 | ans = ans || sumPartition(arr, idx + 1, tar - arr[idx], dp); 17 | ans = ans || sumPartition(arr, idx + 1, tar, dp); 18 | return dp[idx][tar] = ans; 19 | } 20 | bool canPartition(vector& nums) { 21 | int sum = 0; 22 | int n = nums.size(); 23 | for (int ele : nums) { 24 | sum += ele; 25 | } 26 | if (sum % 2 != 0) { 27 | return 0; 28 | } 29 | else { 30 | int target = sum / 2; 31 | vector> dp(n + 1, vector(target + 1, -1)); 32 | return sumPartition(nums, 0, target , dp); 33 | } 34 | } 35 | }; -------------------------------------------------------------------------------- /cpp/42.Trapping_rain_water.cpp: -------------------------------------------------------------------------------- 1 | //problem link https://leetcode.com/problems/trapping-rain-water/ 2 | // Difficulty level : hard 3 | // most optimised O(N) time and O(1) space 4 | class Solution { 5 | public: 6 | int trap(vector& arr) { 7 | int l=0,r=arr.size()-1; 8 | int leftmax=0,rightmax=0,ans=0; 9 | while(l<=r){ 10 | if(arr[l]<=arr[r]){ 11 | if(arr[l]>=leftmax){ 12 | leftmax=arr[l]; 13 | } 14 | else ans+=leftmax-arr[l]; 15 | 16 | l++; 17 | } 18 | else{ 19 | if(arr[r]>=rightmax){ 20 | rightmax=arr[r]; 21 | } 22 | else ans+=rightmax-arr[r]; 23 | 24 | r--; 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /cpp/44_Wildcard_Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | 5 | 6 | 7 | int doit(int sind,int pind,string &s, string &p,vector> &dp){ 8 | 9 | if(sind<0 && pind<0){ 10 | return 1; 11 | } 12 | 13 | if(sind>=0 && pind<0){ 14 | return 0; 15 | } 16 | 17 | if(sind<0){ 18 | if(p[pind]=='*'){ 19 | return doit(sind,pind-1,s,p,dp); 20 | } 21 | else{ 22 | return 0; 23 | } 24 | } 25 | 26 | if(dp[sind][pind]!=-1){ 27 | return dp[sind][pind]; 28 | } 29 | 30 | if(s[sind]==p[pind]||p[pind]=='?'){ 31 | dp[sind][pind]=doit(sind-1,pind-1,s,p,dp); 32 | } 33 | else if(p[pind]=='*'){ 34 | dp[sind][pind]=(doit(sind-1,pind,s,p,dp)||doit(sind,pind-1,s,p,dp)); 35 | } 36 | else{ 37 | dp[sind][pind]=0; 38 | } 39 | 40 | return dp[sind][pind]; 41 | 42 | } 43 | 44 | 45 | bool isMatch(string s, string p) { 46 | 47 | vector> dp(s.size()+1,vector(p.size()+1,-1)); 48 | if (doit(s.size()-1,p.size()-1,s,p,dp)){ 49 | return true; 50 | } 51 | return false; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /cpp/451_Sort_Characters_By_Frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | 5 | mapmp; 6 | 7 | for(int i=0;i>vp; 12 | 13 | for(auto it:mp) 14 | { 15 | vp.push_back({it.second,it.first}); 16 | 17 | } 18 | sort(vp.begin(),vp.end(),greater>()); 19 | 20 | string st=""; 21 | for(auto it:vp) 22 | { 23 | for(int i=0;i &a,vector &b){ 4 | if(a[1]>& points) { 10 | int ans=1; 11 | sort(points.begin(), points.end(), cmp); 12 | int currEnd = points[0][1]; 13 | int n = points.size(); 14 | for(int i = 1; i < n; i++){ 15 | if(currEnd < points[i][0]){ 16 | ans++; 17 | currEnd = points[i][1]; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /cpp/48-Rotate_Image.cpp: -------------------------------------------------------------------------------- 1 | //Quesrion Link -: https://leetcode.com/problems/rotate-image/ 2 | 3 | 4 | //Solution -: 5 | 6 | class Solution { 7 | public: 8 | void rotate(vector>& matrix) { 9 | int n = matrix.size(); 10 | for (int i = 0; i < n; i++) { 11 | for (int j = i + 1; j < n; j++) { 12 | swap(matrix[i][j], matrix[j][i]); 13 | } 14 | } 15 | 16 | for (int i = 0; i < n; i++) { 17 | for (int j = 0; j < n / 2; j++) { 18 | swap(matrix[i][j], matrix[i][n - j - 1]); 19 | } 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /cpp/48.rotate_image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | int n=matrix[0].size(); 5 | vector> v( n , vector (n)); 6 | for(int i=0;i& nums) { 4 | 5 | int maxConsecutiveOnes = 0; 6 | 7 | int n = nums.size(), count = 0; 8 | 9 | for(int i = 0; i < n; i++){ 10 | 11 | if(nums[i] == 1){ 12 | count++; 13 | 14 | maxConsecutiveOnes = max(maxConsecutiveOnes, count); 15 | } else { 16 | count = 0; 17 | } 18 | 19 | } 20 | 21 | return maxConsecutiveOnes; 22 | 23 | } 24 | }; -------------------------------------------------------------------------------- /cpp/485_max_consecutive_ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | if(nums.size()==0) { 5 | return 0; 6 | } 7 | int i=0; 8 | int count=0; 9 | int lastCount=0; 10 | while (i=0 && rightend-start+1){ 19 | start=i-(l-1)/2; 20 | end=i+l/2; 21 | } 22 | } 23 | return s.substr(start, end-start+1); 24 | } 25 | }; -------------------------------------------------------------------------------- /cpp/50. Pow(x,n).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | 5 | double ans =1; 6 | long nx=n; 7 | 8 | if(nx==0) 9 | return ans; 10 | if(x==1) 11 | return x; 12 | 13 | 14 | if(n<0){ 15 | x=1/x; 16 | nx=-nx; 17 | } 18 | 19 | if(nx&1) 20 | return x*myPow(x*x, (nx/1)/2); 21 | else 22 | return myPow(x*x, nx/2); 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /cpp/51. nQueens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | 5 | void solve(vector &board, int n, int row, vector> &ans) 6 | { 7 | if (row == n) 8 | { 9 | ans.push_back(board); 10 | return; 11 | } 12 | for (int i = 0; i < n; i++) 13 | { 14 | if (isSafe(board, n, row, i)) 15 | { 16 | board[row][i] = 'Q'; 17 | solve(board, n, row + 1, ans); 18 | board[row][i] = '.'; 19 | } 20 | } 21 | } 22 | 23 | 24 | bool isSafe(vector &board, int n, int r, int c) 25 | { 26 | for(int row = 0 ; row < r ; row++) 27 | { 28 | if(board[row][c] == 'Q') 29 | return false ; 30 | } 31 | 32 | int row = r ; 33 | int col = c ; 34 | 35 | while(row >= 0 && col >= 0) 36 | { 37 | if(board[row][col] == 'Q') 38 | return false ; 39 | 40 | row-- ; 41 | col-- ; 42 | } 43 | 44 | row = r ; 45 | col = c ; 46 | 47 | while(row >= 0 && col < n) 48 | { 49 | if(board[row][col] == 'Q') 50 | return false ; 51 | 52 | row-- ; 53 | col++ ; 54 | } 55 | 56 | return true ; 57 | } 58 | 59 | vector> solveNQueens(int n) 60 | { 61 | vector> ans; 62 | vector board(n, string(n, '.')); 63 | 64 | solve(board, n, 0, ans); 65 | return ans; 66 | 67 | } 68 | 69 | }; 70 | -------------------------------------------------------------------------------- /cpp/516. Longest Palindromic Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | //Recursion with memoization solution 5 | int longestPalinSubseq(string& str, int si, int ei, vector>& dp) { 6 | if (ei < si) 7 | return dp[si][ei] = 0; 8 | if (ei == si) 9 | return dp[si][ei] = 1; 10 | 11 | if ( dp[si][ei] != -1) 12 | return dp[si][ei]; 13 | int len = 0; 14 | if (str[si] == str[ei]) { 15 | len = longestPalinSubseq(str, si + 1, ei - 1, dp) + 2; 16 | } 17 | else 18 | len = max(longestPalinSubseq(str, si, ei - 1, dp), longestPalinSubseq(str, si + 1, ei, dp)); 19 | 20 | return dp[si][ei] = len; 21 | } 22 | 23 | int longestPalindromeSubseq(string str) { 24 | int si = 0, ei = str.length() - 1, n = str.length(); 25 | vector> dp(n, vector(n, -1)); 26 | return longestPalinSubseq(str, si, ei, dp); 27 | } 28 | }; -------------------------------------------------------------------------------- /cpp/52. nQueens2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalNQueens(int n) { 4 | vector> ans; 5 | vector board(n, string(n, '.')); 6 | 7 | solve(board, n, 0, ans); 8 | return ans.size(); 9 | } 10 | 11 | void solve(vector &board, int n, int row, vector> &ans) 12 | { 13 | if (row == n) 14 | { 15 | ans.push_back(board); 16 | return; 17 | } 18 | for (int i = 0; i < n; i++) 19 | { 20 | if (isSafe(board, n, row, i)) 21 | { 22 | board[row][i] = 'Q'; 23 | solve(board, n, row + 1, ans); 24 | board[row][i] = '.'; 25 | } 26 | } 27 | } 28 | 29 | 30 | bool isSafe(vector &board, int n, int r, int c) 31 | { 32 | for(int row = 0 ; row < r ; row++) 33 | { 34 | if(board[row][c] == 'Q') 35 | return false ; 36 | } 37 | 38 | int row = r ; 39 | int col = c ; 40 | 41 | while(row >= 0 && col >= 0) 42 | { 43 | if(board[row][col] == 'Q') 44 | return false ; 45 | 46 | row-- ; 47 | col-- ; 48 | } 49 | 50 | row = r ; 51 | col = c ; 52 | 53 | while(row >= 0 && col < n) 54 | { 55 | if(board[row][col] == 'Q') 56 | return false ; 57 | 58 | row-- ; 59 | col++ ; 60 | } 61 | 62 | return true ; 63 | } 64 | 65 | 66 | }; 67 | -------------------------------------------------------------------------------- /cpp/55_Jump Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | 5 | if(nums.size()<2) 6 | return true; 7 | int i,j,k = nums[0]; 8 | if(k==0) return false; 9 | for(i=1;i 0) 10 | count_chars--; 11 | if(count_chars == 0) return true; 12 | if(j - i == s1.size() && map[s2.at(i++) - 'a']++ >= 0) 13 | count_chars++; 14 | } 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /cpp/62.Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | 5 | vector>v(m,vector(n,1)); 6 | int r=findmin(0,0,m,n,v); 7 | return r; 8 | 9 | 10 | } 11 | 12 | int findmin(int i,int j,int m,int n,vector>&dp){ 13 | 14 | 15 | 16 | for(int i=1;i>v(m,vector(n,1)); 6 | int r=findmin(0,0,m,n,v); 7 | return r; 8 | 9 | 10 | } 11 | 12 | int findmin(int i,int j,int m,int n,vector>&dp){ 13 | 14 | 15 | 16 | for(int i=1;i& nums) { 4 | 5 | int inv=0; 6 | vector maxs; 7 | int max=INT_MIN; 8 | for(int i=0;imax){ 11 | max=nums[i]; 12 | } 13 | maxs.push_back(max); 14 | } 15 | int flag=0; 16 | 17 | for(int i=0;inums[i+1]){ 19 | if(i==0){ 20 | if(flag==0){ 21 | flag=1; 22 | } 23 | else{ 24 | return false; 25 | } 26 | nums[i]=nums[i+1]; 27 | } 28 | else{ 29 | if(flag==0){ 30 | flag=1; 31 | } 32 | else{ 33 | return false; 34 | } 35 | int temp=nums[i]; 36 | nums[i]=nums[i+1]; 37 | 38 | if(nums[i] plusOne(vector& digit) { 4 | 5 | int carry =1; 6 | 7 | for(int i=digit.size()-1;i>=0;i--) 8 | { 9 | int k = digit[i]+carry; 10 | digit[i] = k%10; 11 | carry = k/10; 12 | 13 | } 14 | if(digit[0]==0) 15 | { 16 | digit.insert(digit.begin(),1); 17 | } 18 | 19 | 20 | return digit; 21 | 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /cpp/695.Maxareaisland.cpp: -------------------------------------------------------------------------------- 1 | /* Problem Link - https://leetcode.com/problems/max-area-of-island/ 2 | 3 | You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) 4 | You may assume all four edges of the grid are surrounded by water. 5 | 6 | The area of an island is the number of cells with a value 1 in the island. 7 | 8 | Return the maximum area of an island in grid. If there is no island, return 0. 9 | 10 | For example - 11 | m = 4, n = 4 12 | 4x4 matrix 13 | 0 1 0 0 14 | 1 1 0 0 15 | 0 1 0 1 16 | 0 0 1 1 17 | 18 | Islands - 19 | | 1 | 1 20 | | 1 1 | 1 1 21 | | 1 | 22 | 23 | There are 2 islands here first one which is having area 4 24 | and second one whose area is 3 25 | so we return max which is 4. 26 | 27 | */ 28 | /* 29 | Time Complexity - O(mxn) 30 | Space Complexity - O(1) 31 | as we're manipulating original array 32 | */ 33 | 34 | 35 | class Solution { 36 | public: 37 | //Variables to store no. of rows and columns 38 | int row; 39 | int col; 40 | //utility function to check if the row and col are valid. 41 | bool isvalid(int r,int c){ 42 | if((r >= 0 && r < row) && (c >= 0 && c < col)) 43 | return true; 44 | return false; 45 | } 46 | //The dfs recursive function that gives you the area of an island. 47 | int change(vector>& arr,int r,int c){ 48 | //checking if row and col is valid and also it is 1; 49 | if(isvalid(r,c) && arr[r][c] == 1){ 50 | //This is clever trick where we change the element 51 | //from 1 to 0 so when we come across it again we don't 52 | //calculate it's area again 53 | //this saves the extra array to manipulate seen indices 54 | arr[r][c] = 0; 55 | return 1 + change(arr,r+1,c) + change(arr,r-1,c) + change(arr,r,c+1) + change(arr,r,c-1); 56 | } 57 | return 0; 58 | } 59 | //Function given by question 60 | int maxAreaOfIsland(vector>& arr) { 61 | //getting rows and cols 62 | int m = arr.size(); 63 | int n = arr[0].size(); 64 | //setting them 65 | row = m; 66 | col = n; 67 | //intial maxarea to be 0 68 | int maxarea = 0; 69 | //Now going over every element in matrix and checking 70 | //if it is 1, if it is then start dfs search from that index 71 | //to get the area of island 72 | 73 | for(int i = 0; i < m; i++){ 74 | for(int j = 0; j < n; j++){ 75 | if(arr[i][j] == 1) 76 | //getting max area among all islands 77 | maxarea = max(maxarea,change(arr,i,j)); 78 | } 79 | } 80 | return maxarea; 81 | } 82 | }; 83 | -------------------------------------------------------------------------------- /cpp/695_Max_Area_of_Island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int m,n; 4 | vector> a,vis; 5 | int rec(int i, int j) 6 | { 7 | if(i<0 || j<0 || i>=m || j>=n || a[i][j]==0 ||vis[i][j]==1) 8 | return 0; 9 | vis[i][j] = 1; 10 | int ans = 1; 11 | ans += rec(i-1,j); 12 | ans += rec(i,j-1); 13 | ans += rec(i+1,j); 14 | ans += rec(i,j+1); 15 | return ans; 16 | } 17 | 18 | int maxAreaOfIsland(vector>& grid) 19 | { 20 | a = grid; 21 | m = a.size(); 22 | n = a[0].size(); 23 | 24 | vis.resize(m); 25 | for(auto &v:vis) 26 | v.resize(n); 27 | 28 | int ans = 0; 29 | for(int i=0;i0 && res<=INT_MAX) 18 | { 19 | res+= x%10; 20 | x/=10; 21 | 22 | if(x==0) 23 | { 24 | break; 25 | } 26 | res*=10; 27 | } 28 | 29 | if(res>INT_MAX) 30 | { 31 | return 0; 32 | } 33 | 34 | else if(flag==1) 35 | { 36 | res=-res; 37 | } 38 | return res; 39 | 40 | 41 | 42 | 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /cpp/713. Subarray Product Less Than K.cpp: -------------------------------------------------------------------------------- 1 | int numSubarrayProductLessThanK(vector& nums, int k) { 2 | int ans=0; 3 | if(k==0) 4 | return 0; 5 | int prod=1; 6 | int l=0,r=0,reach=0; 7 | while(r=k) 18 | prod=prod/nums[l++]; 19 | 20 | } 21 | 22 | int kk=(r-reach); 23 | int rem=reach-l; 24 | ans+=(kk*(kk+1)/2)+(rem*kk); 25 | return ans<=0?0:ans; 26 | } 27 | } -------------------------------------------------------------------------------- /cpp/72_Edit_distance.cpp: -------------------------------------------------------------------------------- 1 | // Leetcode 72: Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. 2 | // A Space efficient Dynamic Programming 3 | // based C++ program to find minimum 4 | // number operations to convert str1 to str2 5 | #include 6 | using namespace std; 7 | 8 | void EditDistDP(string str1, string str2) 9 | { 10 | int len1 = str1.length(); 11 | int len2 = str2.length(); 12 | 13 | // Create a DP array to memoize result 14 | // of previous computations 15 | int DP[2][len1 + 1]; 16 | 17 | // To fill the DP array with 0 18 | memset(DP, 0, sizeof DP); 19 | 20 | // Base condition when second string 21 | // is empty then we remove all characters 22 | for (int i = 0; i <= len1; i++) 23 | DP[0][i] = i; 24 | 25 | // Start filling the DP 26 | // This loop run for every 27 | // character in second string 28 | for (int i = 1; i <= len2; i++) { 29 | // This loop compares the char from 30 | // second string with first string 31 | // characters 32 | for (int j = 0; j <= len1; j++) { 33 | // if first string is empty then 34 | // we have to perform add character 35 | // operation to get second string 36 | if (j == 0) 37 | DP[i % 2][j] = i; 38 | 39 | // if character from both string 40 | // is same then we do not perform any 41 | // operation . here i % 2 is for bound 42 | // the row number. 43 | else if (str1[j - 1] == str2[i - 1]) { 44 | DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; 45 | } 46 | 47 | // if character from both string is 48 | // not same then we take the minimum 49 | // from three specified operation 50 | else { 51 | DP[i % 2][j] = 1 + min(DP[(i - 1) % 2][j], 52 | min(DP[i % 2][j - 1], 53 | DP[(i - 1) % 2][j - 1])); 54 | } 55 | } 56 | } 57 | 58 | // after complete fill the DP array 59 | // if the len2 is even then we end 60 | // up in the 0th row else we end up 61 | // in the 1th row so we take len2 % 2 62 | // to get row 63 | cout << DP[len2 % 2][len1] << endl; 64 | } 65 | 66 | // Driver program 67 | int main() 68 | { 69 | string str1 = "food"; 70 | string str2 = "money"; 71 | EditDistDP(str1, str2); 72 | return 0; 73 | } -------------------------------------------------------------------------------- /cpp/746. Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector co; 5 | int fin; 6 | int dp[1005]; 7 | 8 | int solve(int cur) { 9 | if(cur>fin) { 10 | return 0; 11 | } 12 | 13 | if(dp[cur]!=-1) { 14 | return dp[cur]; 15 | } 16 | 17 | if(dp[cur+1]==-1) { 18 | dp[cur+1] = solve(cur+1); 19 | } 20 | 21 | if(dp[cur+2]==-1) { 22 | dp[cur+2] = solve(cur+2); 23 | } 24 | 25 | return dp[cur] = co[cur] + min(dp[cur+1],dp[cur+2]); 26 | } 27 | 28 | int minCostClimbingStairs(vector& cost) { 29 | int n = cost.size(); 30 | co.push_back(0); 31 | for(int i=0;i>& matrix, int target) 24 | { 25 | if(matrix.size() == 0) 26 | { 27 | return false; 28 | } 29 | int i = 0; 30 | int j = matrix[0].size() -1; 31 | while(i < matrix.size() && j >= 0) 32 | { 33 | if(matrix[i][j] == target) 34 | { 35 | return true; 36 | } 37 | else if(matrix[i][j] > target) 38 | { 39 | j--; 40 | } 41 | else if(matrix[i][j] < target) 42 | { 43 | i++; 44 | } 45 | 46 | } 47 | return false; 48 | } 49 | }; -------------------------------------------------------------------------------- /cpp/775.Global and Local Inversions: -------------------------------------------------------------------------------- 1 | % 775. Global and Local Inversions 2 | class Solution { 3 | public boolean isIdealPermutation(int[] A) { 4 | for(int i=0;i1)return false; 6 | } 7 | return true; 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /cpp/79. Word Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector> &board,string word,int in,int i,int j){ 4 | if(in == word.length()) 5 | return true; 6 | 7 | int n = board.size(); 8 | int m = board[0].size(); 9 | 10 | if(i>=n || j>=m || i<0 || j<0 || board[i][j]=='#') 11 | return false; 12 | 13 | if(board[i][j] == word[in]){ 14 | char temp =board[i][j]; 15 | board[i][j]='#'; 16 | bool res = search(board,word,in+1,i+1,j) || search(board,word,in+1,i,j+1) || search(board,word,in+1,i-1,j) || search(board,word,in+1,i,j-1); 17 | 18 | board[i][j]=temp; 19 | 20 | return res; 21 | } 22 | 23 | return false; 24 | 25 | } 26 | bool exist(vector>& board, string word) { 27 | 28 | int n = board.size(); 29 | int m = board[0].size(); 30 | 31 | for(int i=0;i fairCandySwap(vector& aliceSizes, vector& bobSizes) { 4 | int sumalice=0,sumbob=0; 5 | sort(bobSizes.begin(),bobSizes.end()); 6 | for(int i=0;i v; 15 | int ans=0; 16 | //we will check for every element of alicesizes 17 | for(int i=0;i=0)){ 18 | return 0; 19 | } 20 | if(st[i]=='-'){ 21 | negflag=1; 22 | len--; 23 | i++; 24 | } 25 | else if(st[i]=='+'){ 26 | negflag=0; 27 | len--; 28 | i++; 29 | } 30 | ll count=0; 31 | 32 | while(st[i]=='0' && i='0' && st[i]<='9' && i10){ 44 | if(negflag){ 45 | return INT_MIN; 46 | } 47 | else{ 48 | return INT_MAX; 49 | } 50 | } 51 | while(count>0){ 52 | if(!(st[i]-'0'<=9 && st[i]-'0'>=0)){ 53 | break; 54 | } 55 | num+=(ll)powl(10,count-1)*(st[i]-'0'); 56 | if(negflag==1 && num>INT_MAX){ 57 | return INT_MIN; 58 | } 59 | else if(negflag==0 && num>INT_MAX){ 60 | return INT_MAX; 61 | } 62 | count--; 63 | i++; 64 | } 65 | if(negflag){ 66 | return num*(-1); 67 | } 68 | else 69 | return num; 70 | 71 | 72 | } 73 | }; 74 | -------------------------------------------------------------------------------- /cpp/90_subsetsii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsetsWithDup(vector& a) 4 | { 5 | set> s; 6 | int n = a.size(); 7 | for(int i=0;i<(1< t; 10 | for(int j=0;j> ans; 19 | for(auto &v:s) 20 | ans.push_back(v); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /cpp/91_Decode_Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int func(char st1,char st2){ 5 | if(st1=='0' && st2=='0'){ 6 | return 2; 7 | } 8 | if(st1=='0' && st2!='0'){ 9 | return 0; 10 | } 11 | if(st1<='2' && st2=='0'){ 12 | return 3; 13 | } 14 | if(st1>'2' && st2=='0'){ 15 | return 2; 16 | } 17 | if(st1<'2'){ 18 | return 1; 19 | } 20 | if(st1=='2' && st2<='6'){ 21 | return 1; 22 | } 23 | else{ 24 | return 0; 25 | } 26 | } 27 | 28 | int numDecodings(string s) { 29 | int n=s.size(); 30 | vector dp(n+1); 31 | dp[0]=1; 32 | if(s[0]=='0'){ 33 | return 0; 34 | } 35 | for(int i=1;i<=n;i++){ 36 | if(i==1){ 37 | dp[i]=dp[i-1]; 38 | } 39 | else{ 40 | int x=func(s[i-2],s[i-1]); 41 | if(x==2){ 42 | return 0; 43 | } 44 | else if(x==3){ 45 | dp[i]=dp[i-2]; 46 | } 47 | else if(x==1){ 48 | dp[i]=dp[i-1]+dp[i-2]; 49 | } 50 | else if(x==0){ 51 | dp[i]=dp[i-1]; 52 | } 53 | } 54 | 55 | 56 | } 57 | return dp[n]; 58 | 59 | 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /cpp/97. Interleaving String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[201][201][201]; 4 | string a, b, c; 5 | bool helper(int n1, int n2, int n3) 6 | { 7 | if(c[n3-1]==a[n1-1] && c[n3-1]==b[n2-1]) 8 | { 9 | if(dp[n1-1][n2][n3-1]==-1) 10 | { 11 | dp[n1-1][n2][n3-1] = helper(n1-1, n2, n3-1); 12 | } 13 | if(dp[n1][n2-1][n3-1]==-1) 14 | { 15 | dp[n1][n2-1][n3-1] = helper(n1, n2-1, n3-1); 16 | } 17 | return dp[n1-1][n2][n3-1] || dp[n1][n2-1][n3-1]; 18 | } 19 | else if(c[n3-1]==b[n2-1]) 20 | { 21 | if(dp[n1][n2-1][n3-1]==-1) 22 | { 23 | dp[n1][n2-1][n3-1] = helper(n1, n2-1, n3-1); 24 | } 25 | return dp[n1][n2-1][n3-1]; 26 | } 27 | else if(c[n3-1]==a[n1-1]) 28 | { 29 | if(dp[n1-1][n2][n3-1]==-1) 30 | { 31 | dp[n1-1][n2][n3-1] = helper(n1-1, n2, n3-1); 32 | } 33 | return dp[n1-1][n2][n3-1]; 34 | } 35 | else 36 | { 37 | return false; 38 | } 39 | } 40 | bool isInterleave(string A, string B, string C) 41 | { 42 | //Your code here 43 | a = A; 44 | b = B; 45 | c = C; 46 | 47 | for(int i=0; i<=100; i++) 48 | { 49 | for(int j=0; j<=100; j++) 50 | { 51 | for(int k=0; k<=100; k++) 52 | { 53 | dp[i][j][k]=-1; 54 | } 55 | } 56 | } 57 | dp[0][0][0]=1; 58 | 59 | return helper(a.length(), b.length(), c.length()); 60 | 61 | } 62 | }; -------------------------------------------------------------------------------- /cpp/987. Vertical Order Traversal of a Binary Tree: -------------------------------------------------------------------------------- 1 | // Vertical Order Traversal of a Binary Tree (LeetCode) 2 | // Difficulty - Hard 3 | //https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ 4 | 5 | class Solution 6 | { 7 | public: 8 | vector> verticalTraversal(TreeNode *root) 9 | { 10 | vector> ans; 11 | if (root == NULL) 12 | return ans; 13 | map>> m; 14 | queue>> q; 15 | 16 | pair> roo; 17 | roo.first = root; 18 | roo.second.first = 0; 19 | roo.second.second = 0; 20 | 21 | q.push(roo); 22 | while (!q.empty()) 23 | { 24 | pair> p = q.front(); 25 | q.pop(); 26 | 27 | m[p.second.first][p.second.second].push_back(p.first->val); 28 | // cout<left) 31 | { 32 | pair> pp; 33 | pp.first = p.first->left; 34 | pp.second.first = p.second.first - 1; 35 | pp.second.second = p.second.second + 1; 36 | 37 | q.push(pp); 38 | } 39 | if (p.first->right) 40 | { 41 | pair> pp; 42 | pp.first = p.first->right; 43 | pp.second.first = p.second.first + 1; 44 | pp.second.second = p.second.second + 1; 45 | 46 | q.push(pp); 47 | } 48 | } 49 | 50 | map>>::iterator itr; 51 | 52 | for (itr = m.begin(); itr != m.end(); ++itr) 53 | { 54 | 55 | vector a; 56 | map>::iterator itrr; 57 | for (itrr = itr->second.begin(); itrr != itr->second.end(); ++itrr) 58 | { 59 | sort(itrr->second.begin(), itrr->second.end()); 60 | for (int i = 0; i < itrr->second.size(); i++) 61 | { 62 | a.push_back(itrr->second[i]); 63 | } 64 | } 65 | 66 | ans.push_back(a); 67 | } 68 | 69 | return ans; 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /cpp/Median_of_2_sorted_arrays.cpp: -------------------------------------------------------------------------------- 1 | /***** Median of 2 sorted arrays ******/ 2 | /***** Contributed by Raunak Gayen ******/ 3 | /***** Time Complexity - O(min(logn1,logn2)) ******/ 4 | /***** Space Complexity - O(1) ******/ 5 | 6 | 7 | #include 8 | using namespace std; 9 | 10 | //function for median calculation 11 | double findMedianSortedArrays(vector arr1,vector arr2) 12 | { 13 | int n1 = arr1.size(); 14 | int n2 = arr2.size(); 15 | 16 | if(n1 > n2) 17 | return findMedianSortedArrays(arr2,arr1); 18 | 19 | int left = 0; 20 | int right = n1; 21 | 22 | while(left <= right) 23 | { 24 | int cut1 = (left + right)/2; 25 | int cut2 = (n1 + n2 + 1)/2 - cut1; 26 | 27 | int l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1]; 28 | int l2 = cut2 == 0 ? INT_MIN : arr2[cut2 - 1]; 29 | 30 | int r1 = cut1 == n1 ? INT_MAX : arr1[cut1]; 31 | int r2 = cut2 == n2 ? INT_MAX : arr2[cut2]; 32 | 33 | if(l1 <= r2 && l2 <= r1) 34 | { 35 | if((n1 + n2) % 2 == 0) 36 | return (double)(max(l1,l2) + min(r1,r2))/2.0; 37 | else 38 | return (double)max(l1,l2); 39 | } 40 | else if(l1 > r2) 41 | { 42 | right = cut1 - 1; 43 | } 44 | else 45 | { 46 | left = cut1 + 1; 47 | } 48 | } 49 | 50 | return 0.0; 51 | 52 | } 53 | 54 | 55 | int main() 56 | { 57 | int n1,n2; 58 | cin>>n1>>n2; // n1 -> size of 1st array and n2 -> size of 2nd array 59 | vector arr1(n1); 60 | vector arr2(n2); 61 | 62 | for(int i = 0; i < n1; i++) cin>>arr1[i]; // taking inputs for 1st array 63 | 64 | for(int i = 0; i < n2; i++) cin>>arr2[i]; // taking inputs for 2nd array 65 | 66 | //lets deal with the smaller array first 67 | 68 | double median = findMedianSortedArrays(arr1,arr2); 69 | 70 | cout<<"The median of the 2 sorted arrays is: "< 2 | 3 | int main() 4 | { 5 | int i, j; 6 | for(i=5;i>=1;i–) 7 | { 8 | for(j=i;j<=5;j++) 9 | { 10 | printf(“%d”,j); 11 | } 12 | printf(“\n”); 13 | } 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /cpp/sum of Contiguos array: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int maxSubArraySum(int a[], int size) 5 | { 6 | int max_so_far = INT_MIN, max_ending_here = 0; 7 | 8 | for (int i = 0; i < size; i++) 9 | { 10 | max_ending_here = max_ending_here + a[i]; 11 | if (max_so_far < max_ending_here) 12 | max_so_far = max_ending_here; 13 | 14 | if (max_ending_here < 0) 15 | max_ending_here = 0; 16 | } 17 | return max_so_far; 18 | } 19 | 20 | int main() 21 | { 22 | int a[100] ,n; 23 | cout<<"Enter the size of the array"; 24 | cin>>n; 25 | cout<<"enter the array elements"; 26 | for(int i=0;i>a[i]; 28 | } 29 | 30 | int max_sum = maxSubArraySum(a, n); 31 | cout << "Maximum contiguous sum is " << max_sum; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /go/338_Counting_Bits.go: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/counting-bits/ 2 | 3 | func countBits(n int) []int { 4 | A := make([]int,n+1) 5 | for i:=1;i<=n;i++{ 6 | A[i] = A[i-(i&(-i))]+1; 7 | } 8 | return A; 9 | } 10 | -------------------------------------------------------------------------------- /go/9. Palindrome Number.go: -------------------------------------------------------------------------------- 1 | // This is a solution for Problem No 9. Palindrom Number in leetcode 2 | // https://leetcode.com/problems/palindrome-number/ 3 | // 4 | // I'm solve this problem with Big-O of log(10) 5 | 6 | func isPalindrome(x int) bool { 7 | originalNumber := x 8 | 9 | if x < 0{ 10 | return false 11 | } 12 | 13 | reversedNumber := x % 10 14 | x = x / 10 15 | 16 | if x > 0{ 17 | for x > 0{ 18 | reversedNumber = reversedNumber * 10 + x % 10 19 | x = x / 10 20 | } 21 | } 22 | 23 | return reversedNumber == originalNumber 24 | } -------------------------------------------------------------------------------- /java/11.ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers (a_1, a_2, ..., a_n)where each represents a point at coordinate (i, a_i). 3 | ‘ n ‘ vertical lines are drawn such that the two endpoints of line i is at (i, a_i) and (i, 0) . 4 | Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | */ 6 | public class Solution { 7 | public int maxArea(int[] height) { 8 | int left = 0, right = height.length -1; 9 | int max = 0; 10 | while (left < right) { 11 | max = Math.max(max, Math.min(height[left], height[right]) * (right - left)); 12 | if (height[left] < height[right]) { 13 | left ++; 14 | } 15 | else { 16 | right --; 17 | } 18 | } 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/15. 3Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> threeSum(int[] nums) { 3 | List> result = new ArrayList<>(); 4 | 5 | Arrays.sort(nums); 6 | 7 | for(int i = 0; i < nums.length - 1; i++) { 8 | int currentElement = nums[i]; 9 | 10 | int l = i + 1; 11 | int r = nums.length - 1; 12 | 13 | if(i > 0 && nums[i] == nums[i-1]) { 14 | continue; 15 | } 16 | 17 | int sum; 18 | while (l < r) { 19 | sum = currentElement + nums[l] + nums[r]; 20 | if(sum < 0) l++; 21 | else if(sum > 0) r--; 22 | else { 23 | result.add(Arrays.asList(currentElement, nums[l++], nums[r])); 24 | 25 | while (nums[l] == nums[l - 1] && l < r) l += 1; 26 | } 27 | } 28 | } 29 | 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /java/19. Remove_Nth_node_from_end_of_list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode removeNthFromEnd(ListNode head, int n) { 13 | 14 | ListNode start=new ListNode(0); 15 | start.next=head; 16 | ListNode slow=start; 17 | ListNode fast=start; 18 | for(int i=1;i<=n;i++) 19 | fast=fast.next; 20 | while(fast.next!=null) 21 | { 22 | slow=slow.next; 23 | fast=fast.next; 24 | } 25 | slow.next=slow.next.next; 26 | 27 | return start.next; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/1_Two_Sum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | class Solution { 3 | public int[] twoSum(int[] nums, int target) { 4 | HashMap map = new HashMap(); 5 | int complement; 6 | for (int i = 0; i st = new Stack(); 5 | for (int i = 0; i < x.length(); i++) { 6 | char ch = x.charAt(i); 7 | if (ch == '(' || ch == '{' || ch == '[') { 8 | st.push(ch); 9 | continue; 10 | } 11 | if (st.isEmpty()) { 12 | return false; 13 | } 14 | char top = 0; 15 | switch (ch) { 16 | case ')': 17 | top = st.pop(); 18 | if (top == '[' || top == '{') 19 | return false; 20 | break; 21 | case ']': 22 | top = st.pop(); 23 | if (top == '{' || top == '(') 24 | return false; 25 | break; 26 | case '}': 27 | top = st.pop(); 28 | if (top == '[' || top == '(') 29 | return false; 30 | break; 31 | } 32 | } 33 | return st.isEmpty(); 34 | } 35 | public static void main(String[] args) { 36 | String str = "{([])}"; 37 | boolean s = ispar(str); 38 | System.out.println(s); 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /java/215. KthLargestElementInArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Question 215: Kth Largest Element in an Array [MEDIUM] 3 | 4 | Given an integer array nums and an integer k, return the kth largest element in the array. 5 | 6 | Note that it is the kth largest element in the sorted order, not the kth distinct element. 7 | 8 | Example 1: 9 | 10 | Input: nums = [3,2,1,5,6,4], k = 2 11 | Output: 5 12 | Example 2: 13 | 14 | Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 15 | Output: 4 16 | 17 | Constraints: 18 | 19 | 1 <= k <= nums.length <= 104 20 | -104 <= nums[i] <= 104 21 | */ 22 | 23 | import java.util.PriorityQueue; 24 | 25 | class Solution { 26 | public int findKthLargest(int[] nums, int k) { 27 | PriorityQueue minHeap = new PriorityQueue<>(); 28 | for(int i:nums) 29 | { 30 | minHeap.add(i); 31 | if(minHeap.size()>k) 32 | minHeap.poll(); 33 | } 34 | return minHeap.peek(); 35 | } 36 | } -------------------------------------------------------------------------------- /java/22_Generate_Parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List generateParenthesis(int n) { 3 | List combinations = new ArrayList(); 4 | generateAll(new char[2 * n], 0, combinations); 5 | return combinations; 6 | } 7 | 8 | public void generateAll(char[] current, int pos, List result) { 9 | if (pos == current.length) { 10 | if (valid(current)) 11 | result.add(new String(current)); 12 | } else { 13 | current[pos] = '('; 14 | generateAll(current, pos+1, result); 15 | current[pos] = ')'; 16 | generateAll(current, pos+1, result); 17 | } 18 | } 19 | 20 | public boolean valid(char[] current) { 21 | int balance = 0; 22 | for (char c: current) { 23 | if (c == '(') balance++; 24 | else balance--; 25 | if (balance < 0) return false; 26 | } 27 | return (balance == 0); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/236. Lowest Common Ancestor of a Binary Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 3 | if(root == null || root == p || root == q) 4 | return root; 5 | 6 | TreeNode left = lowestCommonAncestor(root.left, p, q); 7 | TreeNode right = lowestCommonAncestor(root.right, p, q); 8 | 9 | if(left != null && right != null) 10 | return root; 11 | if(left != null) return left; 12 | if(right!=null) return right; 13 | return null; 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /java/243. Shortest Word Distance.java: -------------------------------------------------------------------------------- 1 | /* 2 | 243. Shortest Word Distance 3 | Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. 4 | 5 | Example: 6 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. 7 | 8 | Input: word1 = “coding”, word2 = “practice” 9 | Output: 3 10 | Input: word1 = "makes", word2 = "coding" 11 | Output: 1 12 | 13 | Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. 14 | 15 | Companies: Amazon, Google, LinkedIn, Microsoft, Oracle, Paypal and Uber 16 | */ 17 | 18 | /* 19 | Algorithm 20 | It is enough to traverse the array once, initialize the two variables p1, p2 to -1, and then traverse the array. 21 | When word 1 is encountered, its position is stored in p1, and if word 2 is encountered, its position is stored in p2. If p1, p2 are not -1 anymore, then update the result. 22 | */ 23 | 24 | //Code: 25 | 26 | public class Shortest_Word_Distance { 27 | 28 | public static void main(String[] args) { 29 | Shortest_Word_Distance out = new Shortest_Word_Distance(); 30 | Solution s = out.new Solution(); 31 | 32 | System.out.println(s.shortestDistance(new String[]{"practice", "makes", "perfect", "coding", "makes"}, "makes", "coding")); 33 | } 34 | 35 | public class Solution { 36 | public int shortestDistance(String[] words, String word1, String word2) { 37 | int posA = -1; 38 | int posB = -1; 39 | int minDistance = Integer.MAX_VALUE; 40 | 41 | for (int i = 0; i < words.length; i++) { 42 | if (words[i].equals(word1)) { 43 | posA = i; 44 | } 45 | 46 | if (words[i].equals(word2)) { 47 | posB = i; 48 | } 49 | 50 | if (posA != -1 && posB != -1) { // will be run every time, after 1st pair is found 51 | minDistance = Math.min(minDistance, Math.abs(posA - posB)); 52 | } 53 | } 54 | 55 | return minDistance; 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /java/2_Add_Two_Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 | ListNode fake = new ListNode(0); 14 | ListNode p = fake; 15 | 16 | ListNode p1 = l1; 17 | ListNode p2 = l2; 18 | 19 | int carry = 0; 20 | while(p1!=null || p2!=null){ 21 | int sum = carry; 22 | if(p1!=null){ 23 | sum += p1.val; 24 | p1 = p1.next; 25 | } 26 | 27 | if(p2!=null){ 28 | sum += p2.val; 29 | p2 = p2.next; 30 | } 31 | 32 | if(sum>9){ 33 | carry=1; 34 | sum = sum-10; 35 | }else{ 36 | carry = 0; 37 | } 38 | 39 | ListNode l = new ListNode(sum); 40 | p.next = l; 41 | p = p.next; 42 | } 43 | 44 | //don't forget check the carry value at the end 45 | if(carry > 0){ 46 | ListNode l = new ListNode(carry); 47 | p.next = l; 48 | } 49 | return fake.next; 50 | } 51 | } -------------------------------------------------------------------------------- /java/36. Valid Sudoku.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | 4 | for(int i=0;i<9;i++) 5 | { 6 | int t[]=new int[9]; 7 | int k[]= new int[9]; 8 | for(int j=0;j<9;j++) 9 | { 10 | if(board[i][j]!='.') 11 | { 12 | if(t[board[i][j]-'1']>0) 13 | return false; 14 | else t[board[i][j]-'1']++; 15 | } 16 | if(board[j][i]!= '.') 17 | { 18 | if(k[board[j][i]-'1']>0) 19 | return false; 20 | else k[board[j][i]-'1']++; 21 | } 22 | } 23 | } 24 | for(int m=0,n=0;m<9;n+=3) 25 | { 26 | int b[]=new int[10]; 27 | for(int i=m;i<(m+3);i++) 28 | { 29 | 30 | for(int j=n;j<(n+3);j++) 31 | { 32 | if(board[i][j]!='.') 33 | {if((b[(board[i][j]-'0')])>0) 34 | return false; 35 | else b[board[i][j]-'0']++; 36 | } 37 | } 38 | } 39 | if(n==6) 40 | { 41 | n=-3; 42 | m+=3; 43 | } 44 | } 45 | return true; 46 | } 47 | } -------------------------------------------------------------------------------- /java/42. Trapping Rain Water.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] height) { 3 | int res=0, n=height.length, i; 4 | if(n!=0){ 5 | int lmax[]=new int[n]; 6 | lmax[0]=height[0]; 7 | int rmax[]=new int[n]; 8 | rmax[n-1]=height[n-1]; 9 | 10 | for(i=1;i=0;i--) 15 | { 16 | rmax[i]= Math.max(rmax[i+1], height[i]); 17 | } 18 | for(i=1;i findDuplicates(int[] nums) { 18 | List list=new ArrayList(); 19 | Arrays.sort(nums); 20 | 21 | for(int i=0;i findDuplicates(int[] nums) { 3 | List output = new ArrayList(); 4 | Arrays.sort(nums); 5 | for(int i=0; i= greed[i]) { 10 | i++; 11 | j++; 12 | } else { 13 | j++; 14 | } 15 | } 16 | return i; 17 | } 18 | } 19 | 20 | //link for the question https://leetcode.com/problems/assign-cookies 21 | -------------------------------------------------------------------------------- /java/494. Target Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findTargetSumWays(int[] nums, int target) { 3 | Map dp = new HashMap<>(); 4 | return findTargetSumWays(nums, 0, target, dp); 5 | } 6 | 7 | private int findTargetSumWays(int[] nums, int i, int target, Map dp) { 8 | String s = i + ", " + target; 9 | if(dp.get(s) != null) return dp.get(s); 10 | if(i == nums.length) { 11 | if(target == 0) { 12 | return 1; 13 | } else { 14 | return 0; 15 | } 16 | } 17 | 18 | 19 | int sum = 0; 20 | sum += findTargetSumWays(nums, i+1, target + nums[i], dp); 21 | sum += findTargetSumWays(nums, i+1, target - nums[i], dp); 22 | 23 | dp.put(s, sum); 24 | return dp.get(s); 25 | } 26 | } -------------------------------------------------------------------------------- /java/509. Fibonacci Number.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int fib(int N) 4 | { 5 | if(N <= 1) 6 | return N; 7 | 8 | int a = 0, b = 1; 9 | 10 | while(N-- > 1) 11 | { 12 | int sum = a + b; 13 | a = b; 14 | b = sum; 15 | } 16 | return b; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/55. Jump Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canJump(int[] nums) { 3 | int n = nums.length; 4 | int target = n-1; 5 | 6 | for(int i=n-2; i>=0; i--){ 7 | if(nums[i] + i >= target){ 8 | target = i; 9 | } 10 | } 11 | 12 | if(target == 0) return true; 13 | return false; 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/55_Jump Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canJump(int[] nums) { 3 | int n = nums.length; 4 | int target = n-1; 5 | 6 | for(int i=n-2; i>=0; i--){ 7 | if(nums[i] + i >= target){ 8 | target = i; 9 | } 10 | } 11 | 12 | if(target == 0) return true; 13 | return false; 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/58.Length of Last Word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | int c=0; 4 | s=s.trim(); 5 | for(int i=s.length()-1;i>=0;i--) 6 | { 7 | if(s.charAt(i)==' ') 8 | break; 9 | c++; 10 | } 11 | return c; 12 | } 13 | } -------------------------------------------------------------------------------- /java/6. ZigZag Conversion.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convert(String s, int numRows) { 3 | 4 | if (numRows == 1) return s; 5 | 6 | StringBuilder ret = new StringBuilder(); 7 | int n = s.length(); 8 | int cycleLen = 2 * numRows - 2; 9 | 10 | for (int i = 0; i < numRows; i++) { 11 | for (int j = 0; j + i < n; j += cycleLen) { 12 | ret.append(s.charAt(j + i)); 13 | if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) 14 | ret.append(s.charAt(j + cycleLen - i)); 15 | } 16 | } 17 | return ret.toString(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/605.Can Place Flowers.java: -------------------------------------------------------------------------------- 1 | //605. Can Place Flowers 2 | //Java 3 | class Solution { 4 | public boolean canPlaceFlowers(int[] f, int n) { 5 | int length = f.length; 6 | for(int i = 0; i=Math.pow(2,31)-1||r<-Math.pow(2,31)) 27 | return 0; 28 | else 29 | return (int)r; 30 | } 31 | } -------------------------------------------------------------------------------- /java/75.Sort Colors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] nums) 3 | { 4 | int zero=0, one=0, two=0; 5 | for(int i=0;i0) 21 | { 22 | nums[i++]=0; 23 | zero--; 24 | } 25 | while(i0) 26 | { 27 | nums[i++]=1; 28 | one--; 29 | } 30 | while(i0) 31 | { 32 | nums[i++]=2; 33 | two--; 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /java/88. Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | int total = n + m; 4 | 5 | for(int i = 0; i < n; i++) { 6 | nums1[total-i-1] = nums2[i]; 7 | } 8 | Arrays.sort(nums1); 9 | 10 | } 11 | } 12 | 13 | 14 | /* 15 | input: 16 | [1,2,3,0,0,0] 17 | 3 18 | [2,5,6] 19 | 3 20 | Output 21 | [1,2,2,3,5,6] 22 | Expected 23 | [1,2,2,3,5,6] 24 | */ 25 | -------------------------------------------------------------------------------- /java/9.PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Question 3 | Given an integer x, return true if x is palindrome integer. 4 | 5 | An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not. 6 | 7 | Example 1: 8 | 9 | Input: x = 121 10 | Output: true 11 | Example 2: 12 | 13 | Input: x = -121 14 | Output: false 15 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 16 | */ 17 | 18 | class Solution { 19 | public boolean isPalindrome(int x) { 20 | if(x < 0) 21 | return false; 22 | int rev=0,tmp = x,d; 23 | while(tmp != 0) 24 | { 25 | d = tmp%10; 26 | rev = rev*10+d; 27 | tmp = tmp/10; 28 | } 29 | if(x == rev) 30 | return true; 31 | 32 | else 33 | return false; 34 | 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/96. Unique Binary Search Trees.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numTrees(int n) { 3 | int[] ways = new int[n+1]; 4 | ways[0] = 1; ways[1] = 1; 5 | return calc(n,ways); 6 | } 7 | 8 | private int calc(int n, int[] ways){ 9 | if(ways[n] != 0) return ways[n]; 10 | 11 | int totalWays = 0; 12 | for(int i = 1; i <= n; i++){ 13 | totalWays += calc(i - 1, ways) * calc(n - i, ways); 14 | } 15 | 16 | return ways[n] = totalWays; 17 | } 18 | } -------------------------------------------------------------------------------- /javascript/461.js: -------------------------------------------------------------------------------- 1 | function dec2bin(dec) { 2 | return (dec >>> 0).toString(2); 3 | } 4 | 5 | const hammingDistance = (x, y) => { 6 | let xBin = dec2bin(x) 7 | let yBin = dec2bin(y) 8 | xBin = '0'.repeat(32 - xBin.length) + xBin 9 | yBin = '0'.repeat(32 - yBin.length) + yBin 10 | let counter = 0 11 | for (let i = 0; i < 32; i++) { 12 | if (xBin[i] !== yBin[i]) counter++ 13 | } 14 | return counter 15 | } -------------------------------------------------------------------------------- /javascript/535.js: -------------------------------------------------------------------------------- 1 | const hashTable = []; 2 | const encode = (longUrl) => { 3 | hashTable.push(longUrl); 4 | return "http://tinyurl.com/" + (hashTable.length - 1).toString(); 5 | } 6 | 7 | const decode = (shortUrl) => { 8 | let num = shortUrl.split(".com/") 9 | return hashTable[num[1]] 10 | } -------------------------------------------------------------------------------- /javascript/7. Reverse Integer.js: -------------------------------------------------------------------------------- 1 | var reverse = function(x) { 2 | const isNegative = x < 0; 3 | const xStrArr = Math.abs(x).toString().split(""); 4 | const reversStr = xStrArr.reverse().join(""); 5 | const num = Number(reversStr); 6 | if (isNegative && num > Math.pow(2, 31)) { 7 | return 0; 8 | } 9 | if (!isNegative && num > Math.pow(2, 31) - 1) { 10 | return 0; 11 | } 12 | return isNegative ? -num : num; 13 | }; 14 | -------------------------------------------------------------------------------- /javascript/832.js: -------------------------------------------------------------------------------- 1 | const flipAndInvertImage = (A) => { 2 | const resArr = [] 3 | for (let arr of A) { 4 | resArr.push(arr.reverse()) 5 | } 6 | for (arr of resArr) { 7 | for (let i = 0; i < arr.length; i++) { 8 | arr[i] = arr[i] === 1 ? 0 : 1; 9 | } 10 | } 11 | return resArr 12 | } -------------------------------------------------------------------------------- /javascript/890.js: -------------------------------------------------------------------------------- 1 | const findAndReplacePattern = (words, pattern) => { 2 | const res = [] 3 | let counter = 1 4 | for (let letter of pattern) { 5 | if (letter.match(/[a-zA-Z]/)) { 6 | let re = new RegExp(letter, "g"); 7 | pattern = pattern.replace(re, counter) 8 | counter++ 9 | } 10 | } 11 | for (let word of words) { 12 | counter = 1 13 | let tmpWord = word 14 | for (letter of word) { 15 | if (letter.match(/[a-zA-Z]/)) { 16 | let re = new RegExp(letter, "g"); 17 | word = word.replace(re, counter) 18 | counter++ 19 | } 20 | } 21 | if (pattern == word) res.push(tmpWord) 22 | } 23 | return res 24 | } -------------------------------------------------------------------------------- /py/1. Two Sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | rem = 0 9 | for ind, n in enumerate(nums): 10 | rem = target - n 11 | if rem in nums and nums.index(rem) != ind: 12 | return [ind, nums.index(rem)] 13 | -------------------------------------------------------------------------------- /py/100. Same Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | def same(root1,root2): 8 | if root1 is None and root2 is None: 9 | return True 10 | if (root1 is None and root2 is not None)or (root1 is not None and root2 is None): 11 | return False 12 | return root1.val==root2.val and same(root1.left,root2.left) and same(root1.right,root2.right) 13 | 14 | class Solution(object): 15 | def isSameTree(self, p, q): 16 | return same(p,q) 17 | 18 | -------------------------------------------------------------------------------- /py/100.Same Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, val=0, left=None, right=None): 4 | self.val = val 5 | self.left = left 6 | self.right = right 7 | 8 | 9 | class Solution: 10 | def isSameTree(self, p, q): 11 | if p is None: 12 | if q is None: 13 | return True # both tree are empty 14 | else: 15 | return False # one tree is empty(p) and other is non-empty(q) 16 | if q is None: 17 | if p is None: 18 | return True # both tree are empty 19 | else: 20 | return False # one tree is empty(q) and other is non-empty(p) 21 | if p.val != q.val: 22 | return False # value of node not equal means not same 23 | 24 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 25 | # recursion on lst and rst if both true then trees are same 26 | 27 | 28 | opt = Solution() 29 | root = TreeNode(1) 30 | root1 = TreeNode(1) 31 | root.left = TreeNode(2) 32 | root1.left = TreeNode(2) 33 | root.right = TreeNode(3) 34 | root1.right = TreeNode(3) 35 | print(opt.isSameTree(root, root1)) 36 | -------------------------------------------------------------------------------- /py/101. Symmetric Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def isSymmetric(self, root): 9 | """ 10 | :type root: TreeNode 11 | :rtype: bool 12 | """ 13 | def is_mirror(t1, t2): 14 | if not t1 and not t2: 15 | return True 16 | if not t1 or not t2: 17 | return False 18 | 19 | return t1.val == t2.val and is_mirror(t1.left, t2.right) and is_mirror(t1.right, t2.left) 20 | 21 | return is_mirror(root.left, root.right) 22 | -------------------------------------------------------------------------------- /py/102. Binary Tree Level Order Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def levelOrder(self, root): 9 | """ 10 | :type root: TreeNode 11 | :rtype: List[List[int]] 12 | """ 13 | q = [] 14 | q.append((root, 0)) 15 | m = {} 16 | while q: 17 | node, lvl = q.pop(0) 18 | if not node: 19 | continue 20 | if lvl in m: 21 | m[lvl].append(node.val) 22 | else: 23 | m[lvl] = [node.val] 24 | 25 | q.append((node.left, lvl+1)) 26 | q.append((node.right, lvl+1)) 27 | 28 | print(m) 29 | rs = [] 30 | for ind, ls in m.items(): 31 | rs.append(ls) 32 | 33 | return rs 34 | -------------------------------------------------------------------------------- /py/104. Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def maxDepth(self, root): 9 | """ 10 | :type root: TreeNode 11 | :rtype: int 12 | """ 13 | if not root: 14 | return 0 15 | l = 1 + self.maxDepth(root.left) 16 | r = 1 + self.maxDepth(root.right) 17 | 18 | return max(l,r) 19 | -------------------------------------------------------------------------------- /py/1044. Longest Duplicate Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestDupSubstring(self, S: str) -> str: 3 | l = 1 4 | h = len(S) 5 | ans = (0,0) 6 | while l<=h: 7 | mid = l+(h-l)//2 8 | pk = self.check(S,mid) 9 | if pk: 10 | ans = pk 11 | l = mid+1 12 | else: 13 | h = mid-1 14 | return S[ans[0]:ans[0]+ans[1]] 15 | 16 | def check(self, A, k): 17 | p = 10**9+7 18 | x = [random.randint(1,p-1) for i in range(2)] 19 | xFactor = [1]*2 20 | for i in range(k): 21 | for j in range(2): 22 | xFactor[j] = (xFactor[j]*x[j])%p 23 | print(x) 24 | print(xFactor) 25 | 26 | hashes = {} 27 | 28 | hash = [0,0] 29 | 30 | for i in range(k): 31 | for j in range(2): 32 | hash[j] = ((hash[j]*x[j])%p +ord(A[i]))%p 33 | 34 | hashes[tuple(hash)] = 0 35 | 36 | for i in range(k,len(A)): 37 | for j in range(2): 38 | hash[j]=((hash[j]*x[j])%p-(ord(A[i-k])*xFactor[j])%p+ord(A[i]))%p 39 | 40 | temp = tuple(hash) 41 | if temp in hashes: 42 | return (hashes[temp],k) 43 | hashes[tuple(hash)] = i-k+1 44 | 45 | return None 46 | 47 | 48 | -------------------------------------------------------------------------------- /py/108. Convert Sorted Array to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def sortedArrayToBST(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: TreeNode 12 | """ 13 | if not nums: 14 | return None 15 | 16 | mid = len(nums) // 2 17 | 18 | node = TreeNode(nums[mid]) 19 | node.left = self.sortedArrayToBST(nums[:mid]) 20 | node.right = self.sortedArrayToBST(nums[mid+1:]) 21 | 22 | return node 23 | -------------------------------------------------------------------------------- /py/1095. Find in Mountain Array.py: -------------------------------------------------------------------------------- 1 | # """ 2 | # This is MountainArray's API interface. 3 | # You should not implement it, or speculate about its implementation 4 | # """ 5 | #class MountainArray: 6 | # def get(self, index: int) -> int: 7 | # def length(self) -> int: 8 | 9 | class Solution: 10 | def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: 11 | end = self.peak_index(mountain_arr) 12 | 13 | inLeft = self.binary_search(mountain_arr, target, 0, end) 14 | 15 | if inLeft != -1: 16 | return inLeft 17 | 18 | else: 19 | return self.binary_search(mountain_arr, target, end+1, mountain_arr.length()-1) 20 | 21 | def peak_index(self, arr): 22 | start, end = 0, arr.length()-1 23 | 24 | while start < end: 25 | mid = (start+end)//2 26 | 27 | if arr.get(mid) > arr.get(mid+1): 28 | end = mid 29 | else: 30 | start = mid + 1 31 | 32 | return start 33 | 34 | def binary_search(self, arr, target, low, high): 35 | asc = True if arr.get(low) <= arr.get(high) else False 36 | 37 | while low <= high: 38 | mid = (low+high)//2 39 | 40 | if arr.get(mid) == target: 41 | return mid 42 | 43 | if asc: 44 | if target < arr.get(mid): 45 | high = mid-1 46 | else: 47 | low = mid + 1 48 | else: 49 | if target > arr.get(mid): 50 | high = mid-1 51 | else: 52 | low = mid + 1 53 | 54 | return -1 55 | -------------------------------------------------------------------------------- /py/11. Container With Most Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | l, r, maxArea = 0, len(height) - 1, -1 4 | while l != r: 5 | maxArea = max(maxArea, (r - l) * min(height[l], height[r])) 6 | if height[l] < height[r]: 7 | l += 1 8 | else: 9 | r -= 1 10 | return maxArea 11 | -------------------------------------------------------------------------------- /py/118. Pascal's Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def factorial(self,n): 3 | if n==0 or n==1: 4 | return 1 5 | return n*self.factorial(n-1) 6 | def generate(self, numRows: int) -> List[List[int]]: 7 | lis = [] 8 | for i in range(numRows): 9 | lisinlis = [] 10 | for j in range(i+1): 11 | lisinlis.append( self.factorial(i) // (self.factorial(i-j) * self.factorial(j) )) 12 | lis.append(lisinlis) 13 | return lis 14 | -------------------------------------------------------------------------------- /py/118.PascalTriangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | Question 4 | Given an integer numRows, return the first numRows of Pascal's triangle. 5 | 6 | Input: numRows = 5 7 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 8 | ''' 9 | 10 | class Solution: 11 | 12 | def generate(self, numRows: int) -> List[List[int]]: 13 | ll = [[]] 14 | tmp = [] 15 | 16 | for i in range(numRows): 17 | tmp = [] 18 | for j in range(i+1): 19 | res = math.factorial(i)/(math.factorial(j) * math.factorial(i-j)) 20 | tmp.append(int(res)) 21 | ll.append(tmp) 22 | ll.pop(0) 23 | return ll 24 | -------------------------------------------------------------------------------- /py/12. Integer to Roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, n: int) -> str: 3 | dic={'I': 1, 4 | 'IV': 4, 5 | 'V' : 5, 6 | 'IX': 9, 7 | 'X' : 10, 8 | 'XL': 40, 9 | 'L' : 50, 10 | 'XC': 90, 11 | 'C' : 100, 12 | 'CD': 400, 13 | 'D' : 500, 14 | 'CM': 900, 15 | 'M' : 1000} 16 | roman=[] 17 | for k,v in reversed(dic.items()): 18 | while n>0: 19 | if v<=n: 20 | n-=v 21 | roman.append(k) 22 | else: 23 | break 24 | return "".join(roman) 25 | -------------------------------------------------------------------------------- /py/120. Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minimumTotal(self, triangle): 3 | row=len(triangle)-1 4 | col=len(triangle[0]) 5 | while row>0: 6 | for j in range(row): 7 | triangle[row-1][j]+=min(triangle[row][j],triangle[row][j+1]) 8 | row=row-1 9 | return triangle[0][0] 10 | 11 | -------------------------------------------------------------------------------- /py/1200. Minimum Absolute Difference.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minimumAbsDifference(self, arr): 3 | """ 4 | :type arr: List[int] 5 | :rtype: List[List[int]] 6 | """ 7 | if not arr: 8 | return [] 9 | 10 | arr.sort() 11 | mindiff = arr[1] - arr[0] 12 | for index in range(2, len(arr)): 13 | mindiff = min(mindiff, (arr[index] - arr[index-1])) 14 | 15 | result = [] 16 | for index in range(1, len(arr)): 17 | if arr[index] - arr[index-1] == mindiff: 18 | result.append([arr[index-1], arr[index]]) 19 | return result -------------------------------------------------------------------------------- /py/121.Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | profit=0 4 | buy=prices[0] 5 | for i in range(1,len(prices)): 6 | if prices[i]profit: 11 | profit=temp 12 | return profit -------------------------------------------------------------------------------- /py/122. Best Time to Buy and Sell Stock II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | peak=prices[0] 4 | valley=prices[0] 5 | profit=0 6 | for i in range(0,len(prices)-1): 7 | if prices[i+1]prices[i]: 10 | peak=prices[i+1] 11 | profit+= peak-valley 12 | valley=peak 13 | # print(peak,valley) 14 | return profit -------------------------------------------------------------------------------- /py/125. Valid Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | ns = '' 8 | for ch in s: 9 | if ch.isalnum(): 10 | ns += ch.lower() 11 | return ns == ns[::-1] 12 | -------------------------------------------------------------------------------- /py/1290. Convert Binary Number in a LinkedList to Integer.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def getDecimalValue(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: int 12 | """ 13 | result = '' 14 | if not head: 15 | return 0 16 | while head: 17 | result+= str(head.val) 18 | head = head.next 19 | return int(result, 2) -------------------------------------------------------------------------------- /py/1291. Sequential Digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sequentialDigits(self, low, high): 3 | """ 4 | :type low: int 5 | :type high: int 6 | :rtype: List[int] 7 | """ 8 | result = [] 9 | start = int(str(low)[0]) 10 | for val in range(1, len(str(low))): 11 | new_val = start%10 + 1 12 | start = start*10 + new_val 13 | if start > high: 14 | return result 15 | 16 | result.append(start) 17 | 18 | while result[-1] <= high: 19 | temp = str(result[-1]) 20 | next_elem = int(temp[-1]) + 1 21 | 22 | if next_elem > 9: 23 | next_greater = 0 24 | for index in range(len(temp) + 1): 25 | next_greater = next_greater*10 + (index+1) 26 | else: 27 | next_greater = int(temp[1:]) * 10 + next_elem 28 | if next_greater <= high: 29 | result.append(next_greater) 30 | else: 31 | break 32 | # print next_greater 33 | final_result = [] 34 | for val in result: 35 | if '0' not in str(val) and val >= low: 36 | final_result.append(val) 37 | return final_result -------------------------------------------------------------------------------- /py/1295. Find Numbers with Even Number of Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findNumbers(self, nums: List[int]) -> int: 3 | count=0 4 | for i in nums: 5 | if len(str(i))%2==0: 6 | count+=1 7 | return count 8 | -------------------------------------------------------------------------------- /py/13. Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def romanToInt(self, s): 3 | 4 | d={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} 5 | l=list(str(s)) 6 | k=len(l) 7 | i=0 8 | 9 | s=0 10 | if k==1: 11 | return d[l[0]] 12 | while id[l[j]]: 16 | s=s+d[l[i]] 17 | if i+2==k: 18 | s=s+d[l[j]] 19 | i=i+1 20 | elif d[l[i]]i: 20 | l2.append(l[i]) 21 | l2.append(l[j]) 22 | i=i+1 23 | j=j-1 24 | 25 | if len(l)%2!=0: 26 | l2.append(l[i]) 27 | 28 | for i in range(0,len(l2)): 29 | curr2.val=l2[i] 30 | 31 | curr2=curr2.next 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /py/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: 3 | # # print(horizontalCuts,verticalCuts) 4 | horizontalCuts=sorted(horizontalCuts) 5 | verticalCuts=sorted(verticalCuts) 6 | # print(horizontalCuts,verticalCuts) 7 | horizontalCuts.insert(0,0) 8 | horizontalCuts.append(h) 9 | verticalCuts.insert(0,0) 10 | verticalCuts.append(w) 11 | # print(horizontalCuts,verticalCuts) 12 | maxh,maxw=0,0 13 | for i in range(1,len(horizontalCuts)): 14 | maxh=max(maxh,horizontalCuts[i]-horizontalCuts[i-1]) 15 | for j in range(1,len(verticalCuts)): 16 | maxw=max(maxw,verticalCuts[j]-verticalCuts[j-1]) 17 | # print(maxh,maxw) 18 | return maxh*maxw -------------------------------------------------------------------------------- /py/15. 3Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | a=nums 4 | a.sort() 5 | i=0 6 | 7 | l=[] 8 | ss=set() 9 | while itemp: 21 | 22 | k=k-1 23 | else: 24 | 25 | j=j+1 26 | i=i+1 27 | return l 28 | 29 | 30 | -------------------------------------------------------------------------------- /py/1605.Find_Valid_Matrix_Given_Row_and_Column_Sums.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: 3 | m = len(rowSum) 4 | n = len(colSum) 5 | matrix = [[0]*n for i in range(m)] 6 | print(matrix) 7 | for i in range(m): 8 | for j in range(n): 9 | matrix[i][j] = min(rowSum[i],colSum[j]) 10 | rowSum[i] -= matrix[i][j] 11 | colSum[j] -= matrix[i][j] 12 | return matrix 13 | -------------------------------------------------------------------------------- /py/1606.Find_Servers_That_Handled_Most_Number_of_Requests.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def busiestServers(self, k, arrival, load): 3 | """ 4 | :type k: int 5 | :type arrival: List[int] 6 | :type load: List[int] 7 | :rtype: List[int] 8 | """ 9 | from sortedcontainers import SortedList 10 | avail = SortedList() 11 | for i in range(k): 12 | avail.add(i) 13 | h = [] 14 | count = [0]*k 15 | for i in range(len(arrival)): 16 | s = arrival[i] 17 | e = arrival[i]+load[i] 18 | while h and h[0][0]<=s: 19 | _, j = heappop(h) 20 | avail.add(j) 21 | if len(h)==k: 22 | continue 23 | si = avail.bisect_left(i%k) 24 | if si==len(avail): 25 | ser = avail[0] 26 | else: 27 | ser = avail[si] 28 | avail.remove(ser) 29 | count[ser]+=1 30 | heappush(h, (e, ser)) 31 | maxReq = max(count) 32 | ans = [] 33 | for i in range(len(count)): 34 | if count[i]==maxReq: 35 | ans.append(i) 36 | return ans 37 | -------------------------------------------------------------------------------- /py/1608.Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def specialArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | out = -1 9 | for i in range(len(nums)): 10 | if nums[~i]>=i+1: 11 | if i==len(nums)-1 or nums[~(i+1)] int: 3 | b = list(bin(n)[2:]) 4 | temp = len(b) 5 | for i in range(1, temp): 6 | b[i] = str(int(b[i]) ^ int(b[i-1])) 7 | return int(''.join(b), 2) 8 | -------------------------------------------------------------------------------- /py/162. Find Peak Element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findPeakElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | i = 1 8 | n = len(nums) 9 | if n == 1: 10 | return 0 11 | while i < n: 12 | pr = nums[i-1] 13 | cr = nums[i] 14 | nx = nums[i+1] if i + 1 < n else float('-inf') 15 | 16 | if pr < cr and cr > nx: 17 | return i 18 | 19 | i += 1 20 | return 0 21 | 22 | -------------------------------------------------------------------------------- /py/167. Two Sum II - Input array is sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 3 | 4 | left, right = 0, len(numbers) - 1 5 | 6 | while left < right: 7 | total = numbers[right] + numbers[left] 8 | 9 | if total > target: 10 | right -= 1 11 | 12 | if total < target: 13 | left += 1 14 | 15 | if total == target: 16 | return left+1, right+1 17 | -------------------------------------------------------------------------------- /py/1689. Partitioning Into Minimum Number Of Deci-binary Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minPartitions(self, n): 3 | max_digit = -1 4 | for digit in n: 5 | if int(digit) > max_digit: 6 | max_digit = int(digit) 7 | return max_digit 8 | -------------------------------------------------------------------------------- /py/169. Majority Element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def majorityElement(self, nums): 3 | c=dict(Counter(nums)) 4 | maxi=max(c.values()) 5 | for key,value in c.items(): 6 | if ( value == maxi ): 7 | return key -------------------------------------------------------------------------------- /py/1696. Jump Game VI.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxResult(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | dp = [0] * len(nums) 9 | dp[0] = nums[0] 10 | d = deque([(nums[0],0)]) 11 | for i in range(1, len(nums)): 12 | dp[i] = nums[i] + d[0][0] 13 | 14 | while d and d[-1][0] < dp[i]: # sliding window maximum variation 15 | d.pop() # sliding window maximum variation 16 | d.append((dp[i],i)) # sliding window maximum variation 17 | 18 | if i-k == d[0][1]: # sliding window maximum variation 19 | d.popleft() # sliding window maximum variation 20 | 21 | return dp[-1] -------------------------------------------------------------------------------- /py/18. 4Sum: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fourSum(self, nums: List[int], target: int) -> List[List[int]]: 3 | 4 | def kSum(nums: List[int], target: int, k: int) -> List[List[int]]: 5 | res = [] 6 | if not nums: 7 | return res 8 | 9 | average_value = target // k 10 | 11 | if average_value < nums[0] or nums[-1] < average_value: 12 | return res 13 | 14 | if k == 2: 15 | return twoSum(nums, target) 16 | 17 | for i in range(len(nums)): 18 | if i == 0 or nums[i - 1] != nums[i]: 19 | for subset in kSum(nums[i + 1:], target - nums[i], k - 1): 20 | res.append([nums[i]] + subset) 21 | 22 | return res 23 | 24 | def twoSum(nums: List[int], target: int) -> List[List[int]]: 25 | res = [] 26 | lo, hi = 0, len(nums) - 1 27 | 28 | while (lo < hi): 29 | curr_sum = nums[lo] + nums[hi] 30 | if curr_sum < target or (lo > 0 and nums[lo] == nums[lo - 1]): 31 | lo += 1 32 | elif curr_sum > target or (hi < len(nums) - 1 and nums[hi] == nums[hi + 1]): 33 | hi -= 1 34 | else: 35 | res.append([nums[lo], nums[hi]]) 36 | lo += 1 37 | hi -= 1 38 | 39 | return res 40 | 41 | nums.sort() 42 | return kSum(nums, target, 4) 43 | -------------------------------------------------------------------------------- /py/189. Rotate Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rotate(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: None Do not return anything, modify nums in-place instead. 7 | """ 8 | def rev(arr, s, e): 9 | while s < e: 10 | arr[s], arr[e] = arr[e], arr[s] 11 | s += 1 12 | e -= 1 13 | 14 | n = len(nums) 15 | k %= n 16 | rev(nums, 0, n-1) 17 | rev(nums, 0, k-1) 18 | rev(nums, k, n-1) 19 | 20 | -------------------------------------------------------------------------------- /py/19. Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def removeNthFromEnd(self, head, n): 8 | """ 9 | :type head: ListNode 10 | :type n: int 11 | :rtype: ListNode 12 | """ 13 | t = head 14 | nthp = head 15 | i = 0 16 | prev = head 17 | while t is not None: 18 | i += 1 19 | t = t.next 20 | if i > n: 21 | prev = nthp 22 | nthp = nthp.next 23 | if nthp != head: 24 | prev.next = nthp.next 25 | nthp = None 26 | else: 27 | if head.next is not None: 28 | head = head.next 29 | else: 30 | head = None 31 | return head 32 | 33 | -------------------------------------------------------------------------------- /py/1920. Build Array from Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildArray(self, nums: List[int]) -> List[int]: 3 | return [nums[x] for x in nums] -------------------------------------------------------------------------------- /py/198. House Robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | dp = [0] * (len(nums) + 1) 4 | dp[0] = 0 5 | dp[1] = nums[0] 6 | 7 | for i in range(2, len(dp)): 8 | dp[i] = max((nums[i - 1] + dp[i-2]), dp[i - 1]) 9 | 10 | return max(dp) -------------------------------------------------------------------------------- /py/20. Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValid(self, s): 3 | l=list(str(s)) 4 | n=len(l) 5 | 6 | d={')':'(','}':'{',']':'['} 7 | l1=[] 8 | for i in l: 9 | if len(l1)==0 and i in ')]}': 10 | return False 11 | if i in '({[': 12 | l1.append(i) 13 | if len(l1)!=0 and i in ')]}': 14 | if d[i]==l1[-1]: 15 | l1.pop() 16 | else: 17 | return False 18 | if len(l1)==0: 19 | return True 20 | else: 21 | return False 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /py/202. Happy Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | 4 | hmap = dict() 5 | 6 | sm = 0 7 | while n != 1: 8 | 9 | if n in hmap.keys(): 10 | break 11 | hmap[n] = 1 12 | 13 | temp, sm = n, 0 14 | while temp: 15 | sm += (temp % 10) ** 2 16 | temp //= 10 17 | n = sm 18 | 19 | if n == 1: 20 | return True 21 | return False 22 | -------------------------------------------------------------------------------- /py/204. Count Primes.py: -------------------------------------------------------------------------------- 1 | def countPrimes(self, n: int) -> int: 2 | 3 | if n < 3: 4 | return 0 5 | 6 | 7 | # 1. boolean Table for prime number setting all number as prime = 1 8 | isPrime = [1] * (n) 9 | isPrime[0] = isPrime[1] = 0 10 | count = 0 11 | 12 | m = int(n**0.5)+1 13 | 14 | for i in range(2,m): 15 | if isPrime[i] == 1: 16 | for j in range(i+i,n,i): # next multiple 17 | isPrime[j] = 0 # non prime 18 | 19 | for i in isPrime: 20 | if i == 1: 21 | count += 1 22 | 23 | return count 24 | -------------------------------------------------------------------------------- /py/206. Reverse Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | def solve(curr,prev,head): 7 | if curr is None: 8 | head=prev 9 | return head 10 | head=solve(curr.next,curr,head) 11 | 12 | curr.next=prev 13 | return head 14 | class Solution(object): 15 | def reverseList(self, head): 16 | return solve(head,None,head) 17 | 18 | -------------------------------------------------------------------------------- /py/207. Course Schedule.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 3 | dic=collections.defaultdict(list) 4 | graySet,blackSet=set(),set() 5 | for c,r in prerequisites: 6 | dic[r]+=[c] 7 | res=True 8 | def topo(i): 9 | nonlocal graySet,blackSet,res 10 | if i in blackSet: 11 | return 12 | elif i in graySet: 13 | res=False 14 | else: 15 | graySet.add(i) 16 | for c in dic[i]: 17 | topo(c) 18 | blackSet.add(i) 19 | for i in range(numCourses): 20 | topo(i) 21 | return res 22 | -------------------------------------------------------------------------------- /py/21. Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def mergeTwoLists(self, l1, l2): 8 | """ 9 | :type l1: ListNode 10 | :type l2: ListNode 11 | :rtype: ListNode 12 | """ 13 | ls = [] 14 | 15 | while l1 is not None: 16 | ls.append(l1.val) 17 | l1 = l1.next 18 | 19 | while l2 is not None: 20 | ls.append(l2.val) 21 | l2 = l2.next 22 | 23 | if not ls: 24 | return None 25 | 26 | ls.sort() 27 | n = ListNode(ls[0]) 28 | t = n 29 | for num in ls[1:]: 30 | t.next = ListNode(num) 31 | t = t.next 32 | return n 33 | -------------------------------------------------------------------------------- /py/214. Shortest Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestPalindrome(self, s: str) -> str: 3 | lth, i, n = 0, 1, len(s) 4 | if n == 0: 5 | return s 6 | s1, lps = s + '#' + s[::-1], [0] * (2 * n) 7 | while i < 2 * n: 8 | if s1[lth] == s1[i]: 9 | lth += 1 10 | lps[i] = lth 11 | i += 1 12 | elif lth > 0: 13 | lth = lps[lth - 1] 14 | else: 15 | i += 1 16 | return s[-1:lps[2 * n - 1]:-1] + s 17 | -------------------------------------------------------------------------------- /py/217. Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def containsDuplicate(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | return len(set(nums)) != len(nums) 8 | -------------------------------------------------------------------------------- /py/234. Palindrome Linked List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def isPalindrome(self, head): 8 | """ 9 | :type head: ListNode 10 | :rtype: bool 11 | """ 12 | 13 | fast = slow = head 14 | 15 | while fast and fast.next: 16 | fast = fast.next.next 17 | slow = slow.next 18 | 19 | prev = None 20 | while slow: 21 | nxt = slow.next 22 | slow.next = prev 23 | prev = slow 24 | slow = nxt 25 | 26 | while prev: 27 | if prev.val != head.val: 28 | return False 29 | prev = prev.next 30 | head = head.next 31 | return True 32 | -------------------------------------------------------------------------------- /py/236. Lowest Common Ancestor of a Binary Tree.py: -------------------------------------------------------------------------------- 1 | def lowestCommonAncestor(self, root, p, q): 2 | 3 | if not root: return None 4 | 5 | if root == p or root == q: return root 6 | 7 | l = self.lowestCommonAncestor(root.left, p, q) 8 | r = self.lowestCommonAncestor(root.right, p, q) 9 | 10 | if l and r: 11 | return root 12 | else: return l if l else r 13 | -------------------------------------------------------------------------------- /py/240. Search a 2D Matrix II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchMatrix(self, matrix, target): 3 | """ 4 | :type matrix: List[List[int]] 5 | :type target: int 6 | :rtype: bool 7 | """ 8 | m=len(matrix) 9 | n=len(matrix[0]) 10 | 11 | def findBinary(si,sj,li,lj,target): 12 | #print si, sj, li, lj 13 | if 0<=sili or sj>lj: 22 | return False 23 | if targettarget: 30 | return findBinary(si,sj,midi-1,midj-1,target) or findBinary(si,midj,midi-1,lj,target) or findBinary(midi,sj,li,midj-1,target) 31 | else: 32 | return findBinary(midi+1,midj+1,li,lj,target) or findBinary(si,midj+1,midi,lj,target) or findBinary(midi+1,sj,li,midj,target) 33 | 34 | return findBinary(0,0,m-1,n-1,target) 35 | 36 | 37 | -------------------------------------------------------------------------------- /py/242. Valid Anagram.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isAnagram(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: bool 7 | """ 8 | if len(s) != len(t): 9 | return False 10 | sd = Counter(s) 11 | td = Counter(t) 12 | 13 | for k,v in sd.items(): 14 | if td.get(k, -1) != v: 15 | return False 16 | return True 17 | -------------------------------------------------------------------------------- /py/26. Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | l = 1 4 | for r in range(1, len(nums)): 5 | if nums[r] != nums[r-1]: 6 | nums[l] = nums[r] 7 | l += 1 8 | return l 9 | 10 | -------------------------------------------------------------------------------- /py/279. PerfectSquares.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSquares(self, n): 3 | queue = collections.deque([(0, 0)]) 4 | visited = set() 5 | while queue: 6 | val, dis = queue.popleft() 7 | if val == n: 8 | return dis 9 | for i in range(1, n+1): 10 | j = val + i*i 11 | if j > n: 12 | break 13 | if j not in visited: 14 | visited.add(j) 15 | queue.append((j, dis+1)) -------------------------------------------------------------------------------- /py/28. Implement strStr().py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def strStr(self, haystack, needle): 3 | """ 4 | :type haystack: str 5 | :type needle: str 6 | :rtype: int 7 | """ 8 | for i in range(len(haystack)-len(needle) + 1): 9 | if haystack[i:i+len(needle)] == needle: 10 | return i 11 | return -1 12 | -------------------------------------------------------------------------------- /py/283. Move Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def moveZeroes(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: None Do not return anything, modify nums in-place instead. 6 | """ 7 | pos = 0 8 | 9 | for i in range(len(nums)): 10 | el = nums[i] 11 | if el != 0: 12 | nums[pos], nums[i] = nums[i], nums[pos] 13 | pos += 1 14 | -------------------------------------------------------------------------------- /py/29. Divide Two Integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @return an integer 3 | def divide(self, dividend, divisor): 4 | positive = (dividend < 0) is (divisor < 0) 5 | dividend, divisor = abs(dividend), abs(divisor) 6 | res = 0 7 | while dividend >= divisor: 8 | temp, i = divisor, 1 9 | while dividend >= temp: 10 | dividend -= temp 11 | res += i 12 | i <<= 1 13 | temp <<= 1 14 | if not positive: 15 | res = -res 16 | return min(max(-2147483648, res), 2147483647) 17 | -------------------------------------------------------------------------------- /py/3 .Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | if (len(s) == 0): 4 | return 0 5 | longest=s[0] 6 | for i in range(len(s)-1): 7 | ch=s[i] 8 | j=i+1 9 | while (j <= len(s)-1): 10 | if (s[j] not in list(ch)): 11 | ch=ch+s[j] 12 | j+=1 13 | else: 14 | break 15 | if len(ch) > len(longest): 16 | longest=ch 17 | return len(longest) 18 | -------------------------------------------------------------------------------- /py/300. Longest Increasing Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLIS(self, nums): 3 | n=len(nums) 4 | if n==0: 5 | 6 | return 0 7 | l=[1]*n 8 | for i in range(1,n): 9 | for j in range(0,i): 10 | if nums[i]>nums[j] and l[i] None: 3 | i = j = len(nums)-1 4 | while i > 0 and nums[i-1] >= nums[i]: 5 | i -= 1 6 | if i == 0: # nums are in descending order 7 | nums.reverse() 8 | return 9 | k = i - 1 # find the last "ascending" position 10 | while nums[j] <= nums[k]: 11 | j -= 1 12 | nums[k], nums[j] = nums[j], nums[k] 13 | l, r = k+1, len(nums)-1 # reverse the second part 14 | while l < r: 15 | nums[l], nums[r] = nums[r], nums[l] 16 | l +=1 ; r -= 1 -------------------------------------------------------------------------------- /py/34. Find First and Last Position of Element in Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums: List[int], target: int) -> List[int]: 3 | ans = [-1, -1] 4 | start = self.search(nums, target, True) 5 | end = self.search(nums, target, False) 6 | ans[0] = start 7 | ans[1] = end 8 | return ans 9 | 10 | def search(self, nums, target, findFirst=True): 11 | ans = -1 12 | start = 0 13 | end = len(nums)-1 14 | while(start <= end): 15 | mid = start+(end-start)//2 16 | if target < nums[mid]: 17 | end = mid-1 18 | elif target > nums[mid]: 19 | start = mid+1 20 | else: 21 | ans = mid 22 | if(findFirst): 23 | end = mid-1 24 | else: 25 | start = mid+1 26 | return ans 27 | -------------------------------------------------------------------------------- /py/350. Intersection of Two Arrays II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersect(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: List[int] 7 | """ 8 | r = [] 9 | m = Counter(nums1) 10 | 11 | for n in nums2: 12 | if n in m and m[n] > 0: 13 | r.append(n) 14 | m[n] -= 1 15 | 16 | return r 17 | -------------------------------------------------------------------------------- /py/36. Valid Sudoku.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValidSudoku(self, board): 3 | """ 4 | :type board: List[List[str]] 5 | :rtype: bool 6 | """ 7 | big = set() 8 | for i in range(9): 9 | for j in range(9): 10 | if board[i][j] != '.': 11 | cur = board[i][j] 12 | if (i, cur) in big or (cur, j) in big or (i // 3, j // 3, cur) in big: 13 | return False 14 | big.add((i, cur)) 15 | big.add((cur, j)) 16 | big.add((i // 3, j // 3, cur)) 17 | print(big) 18 | return True 19 | -------------------------------------------------------------------------------- /py/37.Sudoku Solver.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def solveSudoku(self, board): 3 | """ 4 | :type board: List[List[str]] 5 | :rtype: void Do not return anything, modify board in-place instead. 6 | """ 7 | #https://leetcode.com/discuss/84831/java-backtracking-stack-20ms 8 | empty = [] 9 | for i in range(9): 10 | for j in range(9): 11 | if board[i][j] == '.': 12 | empty.append(9 * i + j) 13 | self.solve(board, empty) 14 | 15 | def solve(self, board, empty): 16 | if len(empty) == 0: 17 | return True 18 | first_value = empty[-1] 19 | row, col = first_value / 9, first_value % 9 20 | for k in range(1, 10): 21 | if self.is_safe(board, row, col, str(k)): 22 | board[row][col] = str(k) 23 | empty.pop() 24 | if self.solve(board, empty): 25 | return True 26 | board[row][col] = '.' 27 | empty.append(first_value) 28 | return False 29 | 30 | def is_safe(self, board, row, col, ch): 31 | for k in range(9): 32 | if board[k][col] == ch: 33 | return False 34 | if board[row][k] == ch: 35 | return False 36 | start_row, start_col = 3 * (row / 3), 3 * (col / 3) 37 | for i in range(start_row, start_row + 3): 38 | for j in range(start_col, start_col + 3): 39 | if board[i][j] == ch: 40 | return False 41 | return True 42 | 43 | -------------------------------------------------------------------------------- /py/38. Count and Say.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countAndSay(self, n): 3 | """ 4 | :type n: int 5 | :rtype: str 6 | """ 7 | 8 | def makeStr(n): 9 | res = '' 10 | i = 0 11 | j = 1 12 | while i < len(n) and j < len(n): 13 | if n[i] == n[j]: 14 | j += 1 15 | else: 16 | res += str(j - i) + n[i] 17 | i = j 18 | j += 1 19 | res += str(j - i) + n[-1] 20 | return res 21 | 22 | def getCountAndSay(m): 23 | if m <= 1: 24 | return "1" 25 | return makeStr(getCountAndSay(m - 1)) 26 | 27 | res = getCountAndSay(n) 28 | return res 29 | -------------------------------------------------------------------------------- /py/387. First Unique Character in a String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | d = Counter(s) 8 | d = {k:v for k,v in d.items() if v == 1} 9 | res = float("inf") 10 | for k,v in d.items(): 11 | if s.index(k) < res: 12 | res = s.index(k) 13 | return -1 if res == float("inf") else res 14 | -------------------------------------------------------------------------------- /py/4. Median of Two Sorted Arrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 6 | combination = nums1 + nums2 7 | combination.sort() 8 | 9 | length = len(combination) 10 | 11 | if length % 2 == 1: 12 | return combination[length // 2] 13 | else: 14 | median1 = combination[length // 2 - 1] 15 | median2 = combination[length // 2] 16 | return (median1 + median2) / 2 -------------------------------------------------------------------------------- /py/40. Combination Sum II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 3 | 4 | def backtrack(comb, remain, curr, counter, results): 5 | if remain == 0: 6 | # make a deep copy of the current combination 7 | # rather than keeping the reference. 8 | results.append(list(comb)) 9 | return 10 | elif remain < 0: 11 | return 12 | 13 | for next_curr in range(curr, len(counter)): 14 | candidate, freq = counter[next_curr] 15 | 16 | if freq <= 0: 17 | continue 18 | 19 | # add a new element to the current combination 20 | comb.append(candidate) 21 | counter[next_curr] = (candidate, freq-1) 22 | 23 | # continue the exploration with the updated combination 24 | backtrack(comb, remain - candidate, next_curr, counter, results) 25 | 26 | # backtrack the changes, so that we can try another candidate 27 | counter[next_curr] = (candidate, freq) 28 | comb.pop() 29 | 30 | results = [] # container to hold the final combinations 31 | counter = Counter(candidates) 32 | # convert the counter table to a list of (num, count) tuples 33 | counter = [(c, counter[c]) for c in counter] 34 | 35 | backtrack(comb = [], remain = target, curr = 0, 36 | counter = counter, results = results) 37 | 38 | return results 39 | -------------------------------------------------------------------------------- /py/412. FizzBuzz.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | l=[] 4 | for i in range(1,n+1): 5 | if i%3==0 and i%5==0: 6 | l.append("FizzBuzz") 7 | elif i%3==0: 8 | l.append("Fizz") 9 | elif i%5==0: 10 | l.append("Buzz") 11 | else: 12 | l.append(str(i)) 13 | return l 14 | -------------------------------------------------------------------------------- /py/415. Add Strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def addStrings(self, num1, num2): 3 | """ 4 | :type num1: str 5 | :type num2: str 6 | :rtype: str 7 | """ 8 | return str(int(num1) + int(num2)) -------------------------------------------------------------------------------- /py/442. find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDuplicates(self, nums): 3 | set_nums = set() 4 | answer = [] 5 | for num in nums: 6 | if num in set_nums: 7 | answer.append(num) 8 | else: 9 | set_nums.add(num) 10 | return answer 11 | -------------------------------------------------------------------------------- /py/45.Jump_Game_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums): 3 | if len(nums) == 1: 4 | return 0 5 | # number of jumps currently 6 | jump = 0 7 | # max index by current number of jumps 8 | cur = 0 9 | # max index by current + 1 number of jumps 10 | next = 0 11 | for i in range(len(nums)): 12 | if i > cur: 13 | jump += 1 14 | if cur == next: 15 | return -1 16 | cur = next 17 | next = max(next, nums[i] + i) 18 | return jump 19 | -------------------------------------------------------------------------------- /py/48. Rotate Image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | for r in range(len(matrix)): 7 | for c in range(r): 8 | matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c] 9 | 10 | 11 | for r in range(len(matrix)): 12 | matrix[r].reverse() 13 | 14 | 15 | return matrix 16 | -------------------------------------------------------------------------------- /py/5. Longest Palindromic Substring.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution(object): 3 | def longestPalindrome(self, s): 4 | n=len(s) 5 | tmp=[[0 for i in range(n)]for j in range(n)] 6 | i=0 7 | maxlen=1 8 | while imaxlen: 27 | start=i 28 | maxlen=k 29 | i=i+1 30 | k=k+1 31 | 32 | return(s[start:start+maxlen]) 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /py/50. Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | return pow(x,n) 4 | -------------------------------------------------------------------------------- /py/53. Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | copy=[0]*len(nums) 4 | copy[0]=nums[0] 5 | largest=nums[0] 6 | 7 | for i in range(1,len(nums)): 8 | copy[i]=max(copy[i-1]+nums[i],nums[i]) 9 | if copy[i]>largest: 10 | largest=copy[i] 11 | return largest -------------------------------------------------------------------------------- /py/535. Encode and Decode TinyURL.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | class Codec: 4 | 5 | def __init__(self): 6 | self.urls = {} 7 | self.url_base = "http://tinyurl.com/" 8 | 9 | 10 | def encode(self, long_url): 11 | url_enc = long_url.encode('ascii') 12 | url_64_enc = base64.b64encode(url_enc) 13 | url_64_dec = url_64_enc.decode('ascii') 14 | self.urls[url_64_dec] = long_url 15 | return self.url_base + url_64_dec 16 | 17 | 18 | def decode(self, short_url: str) -> str: 19 | url_splited = short_url.split('/', 3) 20 | url_decoded = self.urls[url_splited[-1]] 21 | return url_decoded 22 | -------------------------------------------------------------------------------- /py/55. Jump Game: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | if (len(nums) == 1): 4 | return True 5 | flag = True 6 | for i in range(len(nums) -2, -1, -1): 7 | if (flag and not nums[i]): # we do not process any newly found 0's until proving the previous 0 can be skipped 8 | flag = False # if an 0 is found, set the flag to F until it is proved to be skippable 9 | ind = i # mark the idx of the 0 10 | if (not flag and nums[i] > ind - i): 11 | flag = True # 0 can be skipped, set flag to T 12 | 13 | return flag 14 | -------------------------------------------------------------------------------- /py/62. Unique Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.mem={} 4 | def uniquePaths(self, m: int, n: int) -> int: 5 | key=(m,n) 6 | if m==0 or n==0: return 0 7 | if m==1 and n==1: return 1 8 | if key in self.mem: return self.mem[key] 9 | self.mem[key]=self.uniquePaths(m-1,n)+self.uniquePaths(m,n-1) 10 | return self.mem[key] 11 | -------------------------------------------------------------------------------- /py/64. Minimum Path Sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minPathSum(self, grid): 3 | m=len(grid) 4 | n=len(grid[0]) 5 | arr=[[0 for i in range(n)] for j in range(m)] 6 | s=0 7 | for i in range(m): 8 | 9 | s=s+grid[i][0] 10 | arr[i][0]=s 11 | s1=0 12 | for j in range(n): 13 | s1=s1+grid[0][j] 14 | arr[0][j]=s1 15 | for i in range(1,m): 16 | for j in range(1,n): 17 | arr[i][j]=grid[i][j]+min(arr[i-1][j],arr[i][j-1]) 18 | return arr[-1][-1] 19 | -------------------------------------------------------------------------------- /py/66. Plus One.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def plusOne(self, digits): 3 | """ 4 | :type digits: List[int] 5 | :rtype: List[int] 6 | """ 7 | if digits[-1] == 9: 8 | i = len(digits) - 1 9 | while i >= 0: 10 | if digits[i] + 1 > 9: 11 | digits[i] = 0 12 | i -= 1 13 | else: 14 | digits[i] += 1 15 | break 16 | if i == -1: 17 | digits.insert(0, 1) 18 | else: 19 | digits[-1] += 1 20 | return digits 21 | -------------------------------------------------------------------------------- /py/695. Max Area of Island.py: -------------------------------------------------------------------------------- 1 | def dfs(grid,i,j): 2 | count=0 3 | if(i<0 or j<0 or i>=len(grid) or j>= len(grid[0]) or grid[i][j]==0): 4 | return 0 5 | else: 6 | grid[i][j]=0 7 | count=1 8 | count+=dfs(grid,i+1,j) 9 | count+=dfs(grid,i-1,j) 10 | count+=dfs(grid,i,j+1) 11 | count+=dfs(grid,i,j-1) 12 | 13 | 14 | return count 15 | 16 | class Solution(object): 17 | def maxAreaOfIsland(self, grid): 18 | """ 19 | :type grid: List[List[int]] 20 | :rtype: int 21 | """ 22 | maxi=0 23 | for i in range(len(grid)): 24 | for j in range(len(grid[0])): 25 | if(grid[i][j]==1): 26 | maxi=max(dfs(grid,i,j),maxi) 27 | return maxi -------------------------------------------------------------------------------- /py/7. Reverse Integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverse(self, x): 3 | """ 4 | :type x: int 5 | :rtype: int 6 | """ 7 | res = 0 8 | i = 0 9 | is_negative = True if x < 0 else False 10 | x = abs(x) 11 | while x > 0: 12 | rem = x % 10 13 | res = res * 10 + rem 14 | x = x // 10 15 | i += 1 16 | 17 | res = -res if is_negative else res 18 | if -2 ** 31 >= res or res >= 2 ** 31 - 1: 19 | return 0 20 | return res 21 | -------------------------------------------------------------------------------- /py/70. Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n == 1: 4 | return 1 5 | 6 | res = [0] * n 7 | 8 | res[0] = 1 9 | res[1] = 2 10 | 11 | for i in range(2, n): 12 | res[i] = res[i-1] + res[i-2] 13 | 14 | return res[-1] -------------------------------------------------------------------------------- /py/72. Edit Distance.py: -------------------------------------------------------------------------------- 1 | def find(word1,word2,m,n): 2 | dp=[[0 for x in range (n+1)] for x in range (m+1)] 3 | for i in range (m+1): 4 | for j in range(n+1): 5 | if i==0: 6 | dp[i][j]=j 7 | elif j==0: 8 | dp[i][j]=i 9 | elif word1[i-1]==word2[j-1]: 10 | dp[i][j]=dp[i-1][j-1] 11 | else: 12 | dp[i][j]=1+min(dp[i][j-1],dp[i-1][j],dp[i-1][j-1]) 13 | return dp[m][n] 14 | 15 | 16 | 17 | class Solution(object): 18 | def minDistance(self, word1, word2): 19 | m=len(word1) 20 | n=len(word2) 21 | if m==0: 22 | return n 23 | if n==0: 24 | return m 25 | return find(word1,word2,m,n) 26 | -------------------------------------------------------------------------------- /py/791. Custom Sort String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def customSortString(self, order, str): 3 | """ 4 | :type order: str 5 | :type str: str 6 | :rtype: str 7 | """ 8 | m = Counter(str) 9 | r = '' 10 | for ch in order: 11 | if ch in m: 12 | m[ch] -= 1 13 | r += ch 14 | if m[ch] > 0: 15 | while m[ch] > 0: 16 | r += ch 17 | m[ch] -= 1 18 | 19 | for ch, f in m.items(): 20 | if f > 0: 21 | while f > 0: 22 | r += ch 23 | f -= 1 24 | 25 | return r 26 | -------------------------------------------------------------------------------- /py/8. String to Integer (atoi).py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def myAtoi(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | s = s.lstrip() 8 | if len(s) == 0: 9 | return 0 10 | is_negative = s[0] == '-' 11 | if is_negative: 12 | s=s[1:] 13 | elif s[0] == "+": 14 | s = s[1:] 15 | res = '' 16 | for ch in s: 17 | if ch.isnumeric(): 18 | if ch == '0' and len(res) == 0: 19 | continue 20 | else: 21 | res += ch 22 | elif len(res) == 0: 23 | res = '0' 24 | break 25 | else: 26 | break 27 | 28 | if len(res) == 0: 29 | return 0 30 | res = int(res) 31 | if is_negative: 32 | res = -res 33 | 34 | if res < -2**31: 35 | res = -2**31 36 | elif res > 2**31 - 1: 37 | res = 2**31 - 1 38 | return res 39 | -------------------------------------------------------------------------------- /py/9. Palindrome Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, x): 3 | """ 4 | :type x: int 5 | :rtype: bool 6 | """ 7 | return str(x)==str(x)[::-1] -------------------------------------------------------------------------------- /py/931. Minimum Falling Path Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minFallingPathSum(self, matrix: List[List[int]]) -> int: 3 | n = len(matrix) 4 | d= [[float('inf') for _ in range(n)] for _ in range(n)] 5 | 6 | for i in range(n): 7 | d[0][i] = matrix[0][i] 8 | 9 | for i in range(1, n): 10 | for j in range(n): 11 | if j == 0: 12 | d[i][j] = matrix[i][j] + min(d[i-1][j], d[i-1][j+1]) 13 | elif j == n-1: 14 | d[i][j] = matrix[i][j] + min(d[i-1][j-1], d[i-1][j]) 15 | else: 16 | d[i][j] = matrix[i][j] + min(d[i-1][j-1], d[i-1][j], d[i-1][j+1]) 17 | 18 | return min(d[n-1]) -------------------------------------------------------------------------------- /py/98. Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def isValidBST(self, root): 9 | """ 10 | :type root: TreeNode 11 | :rtype: bool 12 | """ 13 | def validate(node, low=float("-inf"), high=float("inf")): 14 | if not node: 15 | return True 16 | 17 | if node.val <= low or node.val >= high: 18 | return False 19 | 20 | return validate(node.right, node.val, high) and validate(node.left, low, node.val) 21 | 22 | return validate(root) 23 | -------------------------------------------------------------------------------- /sql/176. Second Highest Salary.sql: -------------------------------------------------------------------------------- 1 | select (select distinct salary from Employee order by salary desc limit 1 offset 1) as secondhighestsalary; 2 | -------------------------------------------------------------------------------- /sql/182. Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | SELECT Email 2 | FROM Person 3 | GROUP BY Email 4 | HAVING COUNT(*)>1 ; -------------------------------------------------------------------------------- /sql/185. Department top three salaries: -------------------------------------------------------------------------------- 1 | select d.Name as Department, a. Name as Employee, a. Salary 2 | from ( 3 | select e.*, dense_rank() over (partition by DepartmentId order by Salary desc) as DeptPayRank 4 | from Employee e 5 | ) a 6 | join Department d 7 | on a. DepartmentId = d. Id 8 | where DeptPayRank <=3; 9 | -------------------------------------------------------------------------------- /sql/596. Classes more than 5 students.sql: -------------------------------------------------------------------------------- 1 | -- Question596 2 | -- There is a table courses with columns: student and class 3 | 4 | -- Please list out all classes which have more than or equal to 5 students. 5 | 6 | -- For example, the table: 7 | 8 | -- +---------+------------+ 9 | -- | student | class | 10 | -- +---------+------------+ 11 | -- | A | Math | 12 | -- | B | English | 13 | -- | C | Math | 14 | -- | D | Biology | 15 | -- | E | Math | 16 | -- | F | Computer | 17 | -- | G | Math | 18 | -- | H | Math | 19 | -- | I | Math | 20 | +---------+------------+ 21 | 22 | select class 23 | from courses 24 | group by class 25 | having count(distinct student)>=5 -------------------------------------------------------------------------------- /sql/81.Article views 2.sql: -------------------------------------------------------------------------------- 1 | /* 81. Article views 2 2 | Table: Views 3 | 4 | -- +---------------+---------+ 5 | -- | Column Name | Type | 6 | -- +---------------+---------+ 7 | -- | article_id | int | 8 | -- | author_id | int | 9 | -- | viewer_id | int | 10 | -- | view_date | date | 11 | -- +---------------+---------+ 12 | There is no primary key for this table, it may have duplicate rows. 13 | Each row of this table indicates that some viewer viewed an article (written by some author) on some date. 14 | Note that equal author_id and viewer_id indicate the same person. 15 | 16 | 17 | Write an SQL query to find all the people who viewed more than one article on the same date, sorted in ascending order by their id. 18 | 19 | The query result format is in the following example: 20 | 21 | Views table: 22 | -- +------------+-----------+-----------+------------+ 23 | -- | article_id | author_id | viewer_id | view_date | 24 | -- +------------+-----------+-----------+------------+ 25 | -- | 1 | 3 | 5 | 2019-08-01 | 26 | -- | 3 | 4 | 5 | 2019-08-01 | 27 | -- | 1 | 3 | 6 | 2019-08-02 | 28 | -- | 2 | 7 | 7 | 2019-08-01 | 29 | -- | 2 | 7 | 6 | 2019-08-02 | 30 | -- | 4 | 7 | 1 | 2019-07-22 | 31 | -- | 3 | 4 | 4 | 2019-07-21 | 32 | -- | 3 | 4 | 4 | 2019-07-21 | 33 | -- +------------+-----------+-----------+------------+ 34 | 35 | Result table: 36 | -- +------+ 37 | -- | id | 38 | -- +------+ 39 | -- | 5 | 40 | -- | 6 | 41 | -- +------+ 42 | */ 43 | 44 | select distinct viewer_id as id#, count(distinct article_id) as total 45 | from views 46 | group by viewer_id, view_date 47 | having count(distinct article_id)>1 48 | order by 1 --------------------------------------------------------------------------------