├── 237_Delete_Node_in_a_Linked_List ├── README.md ├── 1920_Build_Array_from_Permutation ├── 1306_Jumping_Game_3 ├── 899_Orderly_Queue ├── 1929_Concatenation_of_Array ├── 20_Valid_Parenthesis ├── 342_Power_Of_Four ├── 441_Arranging_Coins ├── 1010_Pairs_of_Songs_With_Total_Durations_Divisible_by_60 ├── 168_Excel_Sheet_Column_Title ├── 258_Add_Digits ├── 22_generate_parentheses ├── 1480_Running_Sum_of_1d_Array ├── 484_Find_Permutation ├── 236_Lowest_Common_Ancestor_of_a_Binary_Tree ├── 1344_Angle_Between_Hands_of_Clock ├── 389_Find_the_Difference ├── 653_Two_Sum_IV_Input_is_a_BST ├── 157_Read_N_Characters_Given_Read4 ├── 938_Range_Sum_of_BST ├── 16_3Sum_Closest ├── 207_Course_Schedule ├── 461_Hamming_Distance ├── 171_Excel_Sheet_Column_Number ├── 593_Valid_Square ├── 274_H-Index ├── 70_Climbing_Stairs ├── 112_path_sum ├── 701_Insert_into_a_binary_search_tree ├── 1689_Partitioning_Into_Minimum_Number_Of_Deci-Binary_Numbers ├── 1217_Minimum_Cost_to_Move_Chips_to_The_Same_Position ├── 50_pow_x_n ├── 137_SingleNumber-2 ├── 1572_Matrix_Diagonal_Sum ├── 220_Contains_Duplicate_iii ├── 119_Pascal's_Triangle ├── 442_Find_All_Duplicates_in_an_array ├── 23_Merge_k_sorted_lists ├── 260_Single_Number_iii ├── 843_Guess_The_Word ├── 103_BinaryTree_zigzag_Traversal ├── 310_Minimum_Height_Trees ├── 58_Length_of_Last_Word ├── 96_Unique_Binary_Search_Trees ├── 154_Find_Minimum_in_Rotated_Sorted_Array_ii ├── 981_Time_based_key_value_store ├── 153_Find_Minimum_in_Rotated_Sorted_Array ├── 832_Flipping_an_Image ├── 905_Sort_Array_By_Parity ├── 98_Validate_BST ├── 974_Subarray_Sum_Divisible_by_K ├── 66_Plus_One ├── 198_House_Robber ├── 470_Implement_Rand10_Using_Rand7 ├── 881_Boats_to_Save_People ├── 309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown ├── 412_Fizz_Buzz ├── 189_Rotate_Array ├── 1283_Find_the_Smallest_Divisor_Given_Threshold ├── 62_unique_paths ├── 459_Repeated_Substring_Pattern ├── 662_Max_width_of_Binary_tree ├── 140_Word_Break_ii ├── 1446_Consecutive_Characters ├── 222_Count_Complete_Tree_Nodes ├── 695_Max_Area_of_Island ├── 151_Reverse_Words_in_String ├── 1539_Kth_Missing_Positive_Number ├── 279_Perfect_Squares ├── 394_decode_string ├── 520_Detect_Capital ├── 1153_String_Transforms_Into_Another_String ├── 125_valid_palindrome ├── 1103_Distribute_Candies_to_People ├── 60_PermutationSequence ├── 67_Add Binary ├── 134_Gas_Station ├── 287_Find_duplicate_number ├── 797_All_Paths_From_Source_to_Target ├── 409_Longest_Palindrome ├── 437_Path_Sum_iii ├── 1291_Sequential_Digits ├── 264_Ugly_Number_2 ├── 665_Non_decreasing_Array ├── 228_Summary_Ranges ├── 104_Maximum_Depth_of_Binary_Tree ├── 824_Goat_Latin ├── 983_Minimum_Cost_For_Tickets ├── 621_Task_Scheduler ├── 203_Remove_Linked_list_Elements ├── 1290_Convert_Binary_Number_in_a_Linked_List_to_Integer ├── 395 Longest Substring with At Least K Repeating Characters ├── 190_Reverse_Bits ├── 270_Closest_BST_Value ├── 915_Partition_Array_into_Disjoint_Intervals ├── 253_Meeting_Rooms_II ├── 152_Maximum_Product_Subarray ├── 129_Sum_Root_to_Leaf_Numbers ├── 56_Merge_Intervals ├── 526_Beautiful_Arrangement ├── 435_Non-overlapping_Intervals ├── 849_Maximize_Distance_to_Closest_Person ├── 306_Additive_Number ├── 763_Partition_Labels ├── 91_Decode_Ways ├── 126_Word_Ladder_2 ├── 1640_Check_Array_Formation_Through_Concatenation ├── 949_Largest_Time_for_Given_Digits ├── 128_Longest_Consecutive_Sequence ├── 216_Combination_Sum_III ├── 102_Binary_Tree_Level_Order_Traversal ├── 208_Implement_Trie_(Prefix_Tree) ├── 835_Image_Overlap ├── 107_BinaryTree_Level_Order_traversal_ii ├── 967_Numbers_With_Same_Consecutive_Differences ├── 100_Same_Tree ├── 969_Pancake_Sorting ├── 81_Search_in_Rotated_Sorted_Array_II ├── 25_Reverse_Nodes_in_k-Group ├── 174_DungeonGame ├── 57_Insert_Interval ├── 1379_Find_a_Corresponding_Node_of_a_Binary_Tree_in_a_Clone_of_That_Tree ├── 332_Reconstruct_Itinerary ├── 814_Binary_tree_Pruning ├── 359_Logger_rate_Limiter ├── 563_Binary_Tree_Tilt ├── 82_Remove_Duplicates_from_Sorted_List_II ├── 123_Best_Time_to_Buy_and_Sell_Stock_III ├── 1022_Sum_of_Root_To_Leaf_Binary_Numbers ├── 290_Word_Pattern ├── 84_Largest_Rectangle_in_Histogram └── 497_Random_Point_in_Non-overlapping_Rectangles /237_Delete_Node_in_a_Linked_List: -------------------------------------------------------------------------------- 1 | Leetcode 237. Delete Node in a Linked List 2 | Detailed video Explanation : https://youtu.be/ruat4x3OwQc 3 | =================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | void deleteNode(ListNode* node) { 10 | node->val = node->next->val; 11 | node->next = node->next->next; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | ## Solutions to LeetCode Problems 4 | 5 | [LeetCode Problems and Solutions](https://www.youtube.com/playlist?list=PL1w8k37X_6L86f3PUUVFoGYXvZiZHde1S) playlist on youtube. 6 | 7 | [System Design Interview](https://www.youtube.com/playlist?list=PL1w8k37X_6L-ixYtstrwVbB3J1aZuvkg1) playlist. 8 | 9 | ### Visit [Knowledge Center](https://www.youtube.com/c/KnowledgeCenter) channel on Youtube. 10 | -------------------------------------------------------------------------------- /1920_Build_Array_from_Permutation: -------------------------------------------------------------------------------- 1 | Leetcode 1920: Build Array from Permutation 2 | Detailed video explanation: https://youtu.be/vYdhWwFc6YU 3 | ============================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector buildArray(vector& nums) { 11 | int n = nums.size(); 12 | vector result(n, 0); 13 | for(int i = 0; i < n; ++i) 14 | result[i] = nums[nums[i]]; 15 | return result; 16 | } 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /1306_Jumping_Game_3: -------------------------------------------------------------------------------- 1 | // Leetcode 1306 : Jumping Game 3 2 | // Detailed video explanation: https://youtu.be/TsRyidwuNF8 3 | 4 | // C++ 5 | class Solution { 6 | unordered_set visited; 7 | public: 8 | bool canReach(vector& arr, int start) { 9 | if(visited.count(start) || start < 0 || start >= arr.size()) 10 | return false; 11 | if(arr[start] == 0) return true; 12 | visited.insert(start); 13 | return canReach(arr, start + arr[start]) 14 | || canReach(arr, start - arr[start]); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /899_Orderly_Queue: -------------------------------------------------------------------------------- 1 | Leetcode 899: Orderly Queue 2 | Detailed video explanation: https://youtu.be/pzClQP577Bo 3 | ================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | string orderlyQueue(string s, int k) { 10 | if(k > 1){ 11 | sort(s.begin(), s.end()); 12 | return s; 13 | } 14 | string s_min = s; 15 | for(int i = 0; i < s.length(); ++i){ 16 | s = s.substr(1) + s[0]; 17 | s_min = min(s_min, s); 18 | } 19 | return s_min; 20 | } 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /1929_Concatenation_of_Array: -------------------------------------------------------------------------------- 1 | Leetcode 1929: Concatenation of Array 2 | Detailed video explanation: https://youtu.be/Hb6ijYEpz6c 3 | ======================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector getConcatenation(vector& nums) { 11 | int n = nums.size(); 12 | vector result(2*n, 0); 13 | //for(int i = 0; i < 2*n; ++i) 14 | // result[i] = nums[i%n]; 15 | 16 | for(int i = 0; i < n; ++i){ 17 | result[i] = nums[i]; 18 | result[i+n] = nums[i]; 19 | } 20 | return result; 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /20_Valid_Parenthesis: -------------------------------------------------------------------------------- 1 | Leetcode 20 : Valid Parenthesis 2 | 3 | ================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | bool isValid(string s) { 10 | stack S; 11 | unordered_map _map = {{'(', ')'}, {'{', '}'}, {'[', ']'}}; 12 | for(char c: s){ 13 | if(c==')' || c=='}' || c == ']'){ 14 | if(S.empty()) return false; 15 | if(_map[S.top()] != c) return false; 16 | S.pop(); 17 | } else { 18 | S.push(c); 19 | } 20 | } 21 | return S.empty(); 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /342_Power_Of_Four: -------------------------------------------------------------------------------- 1 | Leetcode 342: Power of Four 2 | Detailed video explanation: https://youtu.be/KwtRRZN6loU 3 | ============================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool isPowerOfFour(int num) { 11 | return (num > 0) && ((num & (num-1)) == 0) && ((num & 0xaaaaaaaa) == 0); 12 | 13 | //return (num > 0) && ((num & (num-1)) == 0) && (num % 3 == 1); 14 | 15 | 16 | // Log4(n) 17 | /*if(num < 1) return false; 18 | int n = num, count = 0; 19 | while(n > 1){ 20 | n >>= 2; 21 | count += 2; 22 | } 23 | return (n << count) == num; 24 | */ 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /441_Arranging_Coins: -------------------------------------------------------------------------------- 1 | LeetCode 441 : Arranging Coins 2 | Detailed video explanation can be found here: https://youtu.be/dIL-weWh8To 3 | 4 | C++ 5 | --- 6 | int arrangeCoins(int n) { 7 | long long k = sqrt(2*(long long)n); 8 | long long sum = k*(k+1)/2; 9 | if(sum > n) return k - 1; 10 | return k; 11 | } 12 | 13 | Java: 14 | ---- 15 | public int arrangeCoins(int n) { 16 | long k = (long)Math.sqrt(2*(long)n); 17 | long sum = k*(k+1)/2; 18 | if(sum > n) return (int)k - 1; 19 | return (int)k; 20 | } 21 | 22 | Python3: 23 | -------- 24 | def arrangeCoins(self, n: int) -> int: 25 | k = (int)(sqrt(2*n)) 26 | sum = (int)(k*(k+1)/2) 27 | if sum > n: return k - 1 28 | return k 29 | 30 | -------------------------------------------------------------------------------- /1010_Pairs_of_Songs_With_Total_Durations_Divisible_by_60: -------------------------------------------------------------------------------- 1 | Leetcode 1010 : Pairs of Songs With Total Durations Divisible by 60 2 | Detailed video explanation : https://youtu.be/LBGZbmYgEFE 3 | ================================================================= 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int numPairsDivisibleBy60(vector& time) { 10 | vector counts(60); 11 | for(auto i: time) 12 | counts[i%60] += 1; 13 | int result = 0; 14 | for(int i = 1; i < 30; ++i) 15 | result += counts[i]*counts[60-i]; 16 | result += (counts[0]*(counts[0]-1))/2 + 17 | (counts[30]*(counts[30]-1))/2; 18 | 19 | return result; 20 | } 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /168_Excel_Sheet_Column_Title: -------------------------------------------------------------------------------- 1 | Leetcode 168: Excel Sheet Column Title 2 | Detailed video explanation: https://youtu.be/UcTKk2y_3s4 3 | ================================================ 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | string convertToTitle(int n) { 10 | string result = ""; 11 | while(n){ 12 | char c = 'A' + (n-1) % 26; 13 | result = c + result; 14 | n = (n-1)/26; 15 | } 16 | return result; 17 | } 18 | }; 19 | 20 | 21 | Python3: 22 | -------- 23 | class Solution: 24 | def convertToTitle(self, n: int) -> str: 25 | result = "" 26 | while n > 0: 27 | c = chr(ord('A') + (n-1) % 26) 28 | result = c + result 29 | n = (n-1)//26 30 | 31 | return result 32 | 33 | -------------------------------------------------------------------------------- /258_Add_Digits: -------------------------------------------------------------------------------- 1 | Leetcode 258: Add Digits - O(1) 2 | Detailed video explanation: https://youtu.be/tIjdI-ioXh0 3 | ======================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int addDigits(int num) { 10 | if(num == 0) return 0; 11 | if(num % 9 == 0) return 9; 12 | return (num % 9); 13 | } 14 | }; 15 | 16 | Java: 17 | ----- 18 | class Solution { 19 | public int addDigits(int num) { 20 | if(num == 0) return 0; 21 | if(num % 9 == 0) return 9; 22 | return (num % 9); 23 | } 24 | } 25 | 26 | 27 | Python3: 28 | ------- 29 | class Solution: 30 | def addDigits(self, num: int) -> int: 31 | if num == 0: return 0 32 | if num % 9 == 0: return 9 33 | return (num % 9) 34 | 35 | 36 | -------------------------------------------------------------------------------- /22_generate_parentheses: -------------------------------------------------------------------------------- 1 | Leetcode 22: Generate Parentheses 2 | Detailed video explanation: https://youtu.be/yBXTAfNuOQg 3 | ---------------------------------------------------------- 4 | 5 | C++: 6 | ---- 7 | 8 | class Solution { 9 | void generateParenthesis(vector& result, int open, int close, int n, string curr){ 10 | if(curr.length() == 2*n) 11 | result.push_back(curr); 12 | else{ 13 | if(open < n) 14 | generateParenthesis(result, open+1, close, n, curr+"("); 15 | if(close < open) 16 | generateParenthesis(result, open, close+1, n, curr+")"); 17 | } 18 | } 19 | public: 20 | vector generateParenthesis(int n) { 21 | vector result; 22 | generateParenthesis(result, 0, 0, n, ""); 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /1480_Running_Sum_of_1d_Array: -------------------------------------------------------------------------------- 1 | Leetcode 1480 : Running Sum of 1d Array 2 | Detailed video explanation: https://youtu.be/fFJaIDUKDoA 3 | ==================================== 4 | 5 | 6 | 7 | C++: 8 | ---- 9 | class Solution { 10 | public: 11 | vector runningSum(vector& nums) { 12 | for(int i = 1; i < nums.size(); ++i) 13 | nums[i] += nums[i-1]; 14 | return nums; 15 | } 16 | }; 17 | 18 | 19 | 20 | Java: 21 | ---- 22 | class Solution { 23 | public int[] runningSum(int[] nums) { 24 | for(int i = 1; i < nums.length; ++i) 25 | nums[i] += nums[i-1]; 26 | return nums; 27 | } 28 | } 29 | 30 | 31 | 32 | Python3: 33 | ------- 34 | class Solution: 35 | def runningSum(self, nums: List[int]) -> List[int]: 36 | for i in range(1, len(nums)): 37 | nums[i] += nums[i-1] 38 | return nums 39 | 40 | -------------------------------------------------------------------------------- /484_Find_Permutation: -------------------------------------------------------------------------------- 1 | LC 484. Find Permutation 2 | 3 | n = length of input string 4 | Result should contain unique numbers from 1 to n+1. 5 | Lowest lexicographic permutation that satisfies pattern given by input string. 6 | D = Decrease 7 | I = Increase. 8 | 9 | Example: 10 | Input "DDIIDI" 11 | Output: [3,2,1,4,6,5,7] 12 | 13 | ----------------------- 14 | 15 | C++: 16 | ---- 17 | class Solution { 18 | public: 19 | vector findPermutation(string s) { 20 | vector res(s.length() + 1, 0); 21 | for(int i = 0; i < res.size(); ++i) 22 | res[i] = i+1; 23 | 24 | int i = 1; 25 | while(i <= s.length()){ 26 | int j = i; 27 | while(i <= s.length() && s[i-1] == 'D') ++i; 28 | reverse(res.begin() + j-1, res.begin() + i); 29 | i++; 30 | } 31 | return res; 32 | } 33 | }; 34 | 35 | -------------------------------------------------------------------------------- /236_Lowest_Common_Ancestor_of_a_Binary_Tree: -------------------------------------------------------------------------------- 1 | Leetcode 236: Lowest Common Ancestor of a Binary Tree 2 | Detailed video Explanation : 3 | ====================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 20 | if(!root) return nullptr; 21 | if(root->val == p->val || root->val == q->val) return root; 22 | TreeNode* left = lowestCommonAncestor(root->left, p, q); 23 | TreeNode* right = lowestCommonAncestor(root->right, p, q); 24 | if(left && right) return root; 25 | return (!left)?right : left; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /1344_Angle_Between_Hands_of_Clock: -------------------------------------------------------------------------------- 1 | Leetcode 1344: Angle Between Hands of a Clock 2 | Detailed video explanation: https://youtu.be/FK_wnA0ERBQ 3 | 4 | C++: 5 | ---- 6 | double angleClock(int hour, int minutes) { 7 | float h = (hour%12 + (float)minutes/60)*30; 8 | float m = minutes*6; 9 | float angle = fabs(h-m); 10 | if(angle > 180) angle = 360-angle; 11 | return angle; 12 | } 13 | 14 | 15 | Java: 16 | ----- 17 | public double angleClock(int hour, int minutes) { 18 | float h = (hour%12 + (float)minutes/60)*30; 19 | float m = minutes*6; 20 | float angle = Math.abs(h-m); 21 | if(angle > 180) angle = 360-angle; 22 | return angle; 23 | } 24 | 25 | 26 | Python3: 27 | ------- 28 | def angleClock(self, hour: int, minutes: int) -> float: 29 | h = (hour%12 + minutes/60)*30 30 | m = minutes*6 31 | angle = abs(h-m) 32 | if angle > 180: angle = 360-angle 33 | return angle 34 | 35 | 36 | -------------------------------------------------------------------------------- /389_Find_the_Difference: -------------------------------------------------------------------------------- 1 | Leetcode 389: Find the Difference 2 | Detailed video explanation: https://youtu.be/sRwElQ_TOr8 3 | ============================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | char findTheDifference(string s, string t) { 11 | char c = 0; 12 | for(char cs: s) c ^= cs; 13 | for(char ct: t) c ^= ct; 14 | return c; 15 | } 16 | }; 17 | 18 | 19 | Java: 20 | ----- 21 | class Solution { 22 | public char findTheDifference(String s, String t) { 23 | char c = 0; 24 | for(char cs: s.toCharArray()) c ^= cs; 25 | for(char ct: t.toCharArray()) c ^= ct; 26 | return c; 27 | } 28 | } 29 | 30 | 31 | Python3: 32 | -------- 33 | class Solution: 34 | def findTheDifference(self, s: str, t: str) -> str: 35 | c = 0 36 | for cs in s: c ^= ord(cs) 37 | for ct in t: c ^= ord(ct) 38 | return chr(c) 39 | 40 | -------------------------------------------------------------------------------- /653_Two_Sum_IV_Input_is_a_BST: -------------------------------------------------------------------------------- 1 | Leetcode 653 : Two Sum IV - Input is a BST 2 | Detailed explanation video : https://youtu.be/RL708FLB76k 3 | ============================================================ 4 | 5 | C++: 6 | ---- 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | * }; 17 | */ 18 | class Solution { 19 | unordered_set visited; 20 | public: 21 | bool findTarget(TreeNode* root, int k) { 22 | if(!root) return false; 23 | if(visited.count(k-root->val)) return true; 24 | visited.insert(root->val); 25 | return findTarget(root->left, k) || findTarget(root->right, k); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /157_Read_N_Characters_Given_Read4: -------------------------------------------------------------------------------- 1 | 157. Read N Characters Given Read4 2 | 3 | C++: 4 | ---- 5 | /** 6 | * The read4 API is defined in the parent class Reader4. 7 | * int read4(char *buf4); 8 | */ 9 | 10 | class Solution { 11 | public: 12 | /** 13 | * @param buf Destination buffer 14 | * @param n Number of characters to read 15 | * @return The number of actual characters read 16 | */ 17 | int read(char *buf, int n) { 18 | int copiedChars = 0, readChars = 4; 19 | char buf4[4]; 20 | 21 | while (copiedChars < n && readChars == 4) { 22 | readChars = read4(buf4); 23 | 24 | for (int i = 0; i < readChars; ++i) { 25 | if (copiedChars == n) 26 | return copiedChars; 27 | buf[copiedChars] = buf4[i]; 28 | ++copiedChars; 29 | } 30 | } 31 | return copiedChars; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /938_Range_Sum_of_BST: -------------------------------------------------------------------------------- 1 | Leetcode 938 : Range Sum of BST 2 | Detailed video explanation : https://youtu.be/KUVXwUGmY3k 3 | =================================================== 4 | 5 | C++ 6 | --- 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | int rangeSumBST(TreeNode* root, int low, int high) { 21 | if(!root) return 0; 22 | int result = 0; 23 | if(root->val <= high && root->val >= low) 24 | result += root->val; 25 | result += rangeSumBST(root->left, low, high); 26 | result += rangeSumBST(root->right, low, high); 27 | return result; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /16_3Sum_Closest: -------------------------------------------------------------------------------- 1 | Leetcode 16: 3Sum Closest 2 | Detailed video explanation: https://youtu.be/TjB9eCUh9KA 3 | ----------------------------------------------- 4 | 5 | C++: 6 | --- 7 | class Solution { 8 | public: 9 | int threeSumClosest(vector& nums, int target) { 10 | int min_diff = INT_MAX; 11 | int closest_sum = 0; 12 | int n = nums.size(); 13 | sort(nums.begin(), nums.end()); 14 | for(int p1 = 0; p1 < n-2; ++p1){ 15 | int p2 = p1+1, p3 = n-1; 16 | while(p2 < p3){ 17 | int sum = nums[p1] + nums[p2] + nums[p3]; 18 | if(sum > target) p3--; 19 | else if(sum < target) p2++; 20 | else return sum; 21 | int diff = abs(sum - target); 22 | if(diff < min_diff){ 23 | min_diff = diff; 24 | closest_sum = sum; 25 | } 26 | } 27 | } 28 | return closest_sum; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /207_Course_Schedule: -------------------------------------------------------------------------------- 1 | Leetcode 207 : Course Schedule 2 | 3 | ========================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | bool dfs(int s, vector>& adj, vector& visited){ 9 | visited[s] = 1; 10 | for(auto u: adj[s]){ 11 | if(visited[u] == 1) return true; 12 | else if(visited[u] == 0){ 13 | if(dfs(u, adj, visited)) return true; 14 | } 15 | } 16 | visited[s] = 2; 17 | return false; 18 | } 19 | public: 20 | bool canFinish(int numCourses, vector>& prerequisites) { 21 | vector> adj(numCourses, vector()); 22 | for(auto edge: prerequisites) 23 | adj[edge[1]].push_back(edge[0]); 24 | vector visited(numCourses, 0); 25 | for(int i = 0; i < numCourses; ++i){ 26 | if(!visited[i] && dfs(i, adj, visited)) return false; 27 | } 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /461_Hamming_Distance: -------------------------------------------------------------------------------- 1 | Leetcode 461: Hamming Distance 2 | Detailed video explanation: https://youtu.be/5UKMvO5bXPI 3 | 4 | C++: 5 | ---- 6 | int hammingDistance(int x, int y) { 7 | return bitset<32>(x^y).count(); 8 | } 9 | int hammingDistance(int x, int y) { 10 | int result = x^y; 11 | int count = 0; 12 | while(result > 0){ 13 | count += 1 & result; 14 | result >>= 1; 15 | } 16 | return count; 17 | } 18 | 19 | 20 | Java: 21 | ----- 22 | public int hammingDistance(int x, int y) { 23 | int result = x^y; 24 | int count = 0; 25 | while(result>0){ 26 | count += result & 1; 27 | result >>= 1; 28 | } 29 | return count; 30 | } 31 | 32 | 33 | Python3: 34 | ------- 35 | def hammingDistance(self, x: int, y: int) -> int: 36 | result, count = x^y, 0 37 | while result>0: 38 | count += result & 1 39 | result >>= 1 40 | 41 | return count 42 | 43 | 44 | -------------------------------------------------------------------------------- /171_Excel_Sheet_Column_Number: -------------------------------------------------------------------------------- 1 | Leetcode 171: Excel Sheet Column Number 2 | Detailed video explanation: https://youtu.be/g-l4UpF62x0 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int titleToNumber(string s) { 11 | int result = 0; 12 | for(char c : s){ 13 | int d = c - 'A' + 1; 14 | result = result*26 + d; 15 | } 16 | return result; 17 | } 18 | }; 19 | 20 | 21 | Java: 22 | ----- 23 | class Solution { 24 | public int titleToNumber(String s) { 25 | int result = 0; 26 | for(char c : s.toCharArray()){ 27 | int d = c - 'A' + 1; 28 | result = result*26 + d; 29 | } 30 | return result; 31 | } 32 | } 33 | 34 | 35 | 36 | Python3: 37 | ------- 38 | class Solution: 39 | def titleToNumber(self, s: str) -> int: 40 | result = 0 41 | for c in s: 42 | d = ord(c) - ord('A') + 1 43 | result = result*26 + d 44 | return result 45 | 46 | 47 | -------------------------------------------------------------------------------- /593_Valid_Square: -------------------------------------------------------------------------------- 1 | Leetcode 593: Valid Square 2 | Detailed video explanation: https://youtu.be/B51j1jjTVWk 3 | ========================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | int get_length(vector& a, vector& b){ 10 | return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]); 11 | } 12 | public: 13 | bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { 14 | vector sides = { 15 | get_length(p1, p2), 16 | get_length(p1, p3), 17 | get_length(p1, p4), 18 | get_length(p2, p3), 19 | get_length(p2, p4), 20 | get_length(p3, p4), 21 | }; 22 | 23 | unordered_map m; 24 | for(auto& s: sides){ 25 | if(!m.count(s)) m.insert({s, 1}); 26 | else m[s]++; 27 | } 28 | 29 | if(m.size() != 2) return false; 30 | for(auto& p: m) return (p.second == 4) || (p.second == 2); 31 | return false; 32 | } 33 | }; 34 | 35 | -------------------------------------------------------------------------------- /274_H-Index: -------------------------------------------------------------------------------- 1 | Leetcode 274: H-Index 2 | Detailed video explanation: https://youtu.be/zzTUtpBQh4k 3 | ======================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int hIndex(vector& citations) { 10 | sort(citations.begin(), citations.end()); 11 | int n = citations.size(), i; 12 | for(i = 1; i <= n; ++i) 13 | if(citations[n-i] < i) break; 14 | return i-1; 15 | } 16 | }; 17 | 18 | 19 | Java: 20 | ----- 21 | class Solution { 22 | public int hIndex(int[] citations) { 23 | Arrays.sort(citations); 24 | int n = citations.length, i; 25 | for(i = 1; i <= n; ++i) 26 | if(citations[n-i] < i) break; 27 | return i-1; 28 | } 29 | } 30 | 31 | 32 | Python3: 33 | ------- 34 | class Solution: 35 | def hIndex(self, citations: List[int]) -> int: 36 | citations.sort() 37 | n, i = len(citations), 1 38 | while i <= n: 39 | if citations[n-i] < i: break 40 | i += 1 41 | return i-1 42 | 43 | -------------------------------------------------------------------------------- /70_Climbing_Stairs: -------------------------------------------------------------------------------- 1 | Leetcode 70: Climbing Stairs 2 | Detailed video explanation: https://youtu.be/AWezsCJDHSk 3 | =================================================== 4 | 5 | C++: 6 | --- 7 | class Solution { 8 | public: 9 | int climbStairs(int n) { 10 | if(n <= 2) return n; 11 | int x = 1, y = 2; 12 | for(int i = 3; i < n; ++i){ 13 | int tmp = y; 14 | y += x; 15 | x = tmp; 16 | } 17 | return (x+y); 18 | } 19 | }; 20 | 21 | 22 | Java: 23 | ---- 24 | class Solution { 25 | public: 26 | int climbStairs(int n) { 27 | if(n <= 2) return n; 28 | int x = 1, y = 2; 29 | for(int i = 3; i < n; ++i){ 30 | int tmp = y; 31 | y += x; 32 | x = tmp; 33 | } 34 | return (x+y); 35 | } 36 | }; 37 | 38 | 39 | Python3: 40 | ------- 41 | class Solution: 42 | def climbStairs(self, n: int) -> int: 43 | if n <= 2: return n 44 | x, y = 1, 2 45 | for i in range(3,n): 46 | x, y = y, x+y 47 | return x+y 48 | 49 | -------------------------------------------------------------------------------- /112_path_sum: -------------------------------------------------------------------------------- 1 | Leetcode 112 : Path Sum 2 | Detailed video explanation : https://youtu.be/7gsJjnnV_8E 3 | ------------------------------------------------------------ 4 | 5 | C++: 6 | ---- 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool hasPathSum(TreeNode* root, int targetSum) { 22 | if(!root) return false; 23 | if(!root->left && !root->right) return (targetSum == root->val); 24 | bool pathSumExists = false; 25 | if(root->left) pathSumExists = hasPathSum(root->left, targetSum-root->val); 26 | if(root->right) pathSumExists = pathSumExists || hasPathSum(root->right, targetSum-root->val); 27 | 28 | return pathSumExists; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /701_Insert_into_a_binary_search_tree: -------------------------------------------------------------------------------- 1 | Leetcode 701 : Insert into a Binary Search Tree 2 | Detailed video explanation : https://youtu.be/XYjQ8EB7yik 3 | ============================================================== 4 | 5 | 6 | C++ 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode* insertIntoBST(TreeNode* root, int val) { 22 | if(!root) 23 | return new TreeNode(val); 24 | if(root->val < val) 25 | root->right = root->right ? insertIntoBST(root->right, val) : new TreeNode(val); 26 | else 27 | root->left = root->left ? insertIntoBST(root->left, val) : new TreeNode(val); 28 | return root; 29 | } 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /1689_Partitioning_Into_Minimum_Number_Of_Deci-Binary_Numbers: -------------------------------------------------------------------------------- 1 | Leetcode 1689 : Partitioning Into Minimum Number Of Deci-Binary Numbers 2 | Detailed video explanation : https://youtu.be/uBZY0VIRwlg 3 | ====================================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int minPartitions(string n) { 11 | 12 | int max_ = 0; 13 | for(auto c: n){ 14 | max_ = max(max_, c-'0'); 15 | } 16 | return max_; 17 | 18 | //return *max_element(n.begin(), n.end()) - '0'; 19 | } 20 | }; 21 | 22 | 23 | 24 | Java: 25 | ----- 26 | class Solution { 27 | public int minPartitions(String n) { 28 | int max_ = 0; 29 | for(int i = 0; i < n.length(); ++i){ 30 | max_ = Math.max(max_, n.charAt(i)-'0'); 31 | } 32 | return max_; 33 | } 34 | } 35 | 36 | 37 | 38 | 39 | Python3: 40 | -------- 41 | class Solution: 42 | def minPartitions(self, n: str) -> int: 43 | max_ = 0 44 | for c in n: 45 | max_ = max(max_, ord(c)-ord('0')) 46 | 47 | return max_ 48 | 49 | -------------------------------------------------------------------------------- /1217_Minimum_Cost_to_Move_Chips_to_The_Same_Position: -------------------------------------------------------------------------------- 1 | Leetcode 1217: Minimum Cost to Move Chips to The Same Position 2 | Detailed video explanation: https://youtu.be/BLYLGcYhcn8 3 | ============================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int minCostToMoveChips(vector& position) { 10 | int even = 0, odd = 0; 11 | for(int i: position){ 12 | if(i%2) ++odd; 13 | else ++even; 14 | } 15 | return min(odd, even); 16 | } 17 | }; 18 | 19 | 20 | Java: 21 | ----- 22 | class Solution { 23 | public int minCostToMoveChips(int[] position) { 24 | int even = 0, odd = 0; 25 | for(int i: position){ 26 | if(i%2 == 1) ++odd; 27 | else ++even; 28 | } 29 | return Math.min(odd, even); 30 | } 31 | } 32 | 33 | 34 | 35 | Python3: 36 | -------- 37 | class Solution: 38 | def minCostToMoveChips(self, position: List[int]) -> int: 39 | even, odd = 0, 0 40 | for i in position: 41 | if i%2 == 1: odd += 1 42 | else: even += 1 43 | 44 | return min(odd, even) 45 | 46 | -------------------------------------------------------------------------------- /50_pow_x_n: -------------------------------------------------------------------------------- 1 | Leetcode 50: Pow(x, n) 2 | Detailed video explanation: https://youtu.be/snOaKR2xgZg 3 | ======================================================= 4 | 5 | C++: 6 | ---- 7 | double pow_util(double x, long n){ 8 | if(n == 0) return 1.0; 9 | if(n == 1) return x; 10 | if(n < 0) return pow_util(1/x, -n); 11 | double result = pow_util(x*x, n/2); 12 | if(n%2) result *= x; 13 | return result; 14 | } 15 | 16 | double myPow(double x, int n) { 17 | return pow_util(x,n); 18 | } 19 | 20 | 21 | Java: 22 | ----- 23 | private double pow_util(double x, long n){ 24 | if(n == 0) return 1.0; 25 | if(n == 1) return x; 26 | if(n < 0) return pow_util(1/x, -n); 27 | double result = pow_util(x*x, n/2); 28 | if(n%2 == 1) result *= x; 29 | return result; 30 | } 31 | public double myPow(double x, int n) { 32 | return pow_util(x, n); 33 | } 34 | 35 | 36 | Python3: 37 | -------- 38 | def myPow(self, x: float, n: int) -> float: 39 | if n == 0: return 1.0 40 | if n == 1: return x 41 | if n < 0: return self.myPow(1/x, -n) 42 | result = self.myPow(x, n//2) 43 | result *= result 44 | if n%2 == 1: result *= x 45 | return result 46 | 47 | -------------------------------------------------------------------------------- /137_SingleNumber-2: -------------------------------------------------------------------------------- 1 | // C++: 2 | 3 | int singleNumber(vector& nums) { 4 | int ones = 0, twos = 0, thrice = 0; 5 | for(int n : nums){ 6 | twos = twos | (ones & n); 7 | ones = ones ^ n; 8 | thrice = ones & twos; 9 | ones &= ~thrice; 10 | twos &= ~thrice; 11 | } 12 | return ones; 13 | } 14 | // Java: 15 | 16 | public int singleNumber(int[] nums) { 17 | int ones = 0, twos = 0, thrice = 0; 18 | for(int n : nums){ 19 | twos = twos | (ones & n); 20 | ones = ones ^ n; 21 | thrice = ones & twos; 22 | ones &= ~thrice; 23 | twos &= ~thrice; 24 | } 25 | return ones; 26 | } 27 | 28 | ## Python3: 29 | 30 | def singleNumber(self, nums: List[int]) -> int: 31 | ones, twos, thrice = 0, 0, 0 32 | for n in nums: 33 | twos = twos | (ones & n) 34 | ones = ones ^ n 35 | thrice = ones & twos 36 | ones &= ~thrice 37 | twos &= ~thrice 38 | 39 | return ones 40 | 41 | Detailed Video Explanation is available here: https://youtu.be/ZbTXZ2_YAgI 42 | -------------------------------------------------------------------------------- /1572_Matrix_Diagonal_Sum: -------------------------------------------------------------------------------- 1 | Leetcode 1572: Matrix Diagonal Sum 2 | Detailed video explanation: https://youtu.be/5yF2HkQXuSo 3 | ============================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int diagonalSum(vector>& mat) { 11 | int n = mat.size(); 12 | int sum = 0; 13 | for(int i = 0; i < n; ++i) 14 | sum += mat[i][i] + mat[i][n-i-1]; 15 | if(n % 2) sum -= mat[n/2][n/2]; 16 | 17 | return sum; 18 | } 19 | }; 20 | 21 | 22 | 23 | Java: 24 | ----- 25 | class Solution { 26 | public int diagonalSum(int[][] mat) { 27 | int n = mat.length; 28 | int sum = 0; 29 | for(int i = 0; i < n; ++i) 30 | sum += mat[i][i] + mat[i][n-i-1]; 31 | if(n % 2 == 1) sum -= mat[n/2][n/2]; 32 | 33 | return sum; 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | Python3: 41 | ------- 42 | class Solution: 43 | def diagonalSum(self, mat: List[List[int]]) -> int: 44 | n, sum = len(mat), 0 45 | for i in range(n): 46 | sum += mat[i][i] + mat[i][n-i-1] 47 | if n % 2 == 1: sum -= mat[n//2][n//2] 48 | 49 | return sum 50 | 51 | -------------------------------------------------------------------------------- /220_Contains_Duplicate_iii: -------------------------------------------------------------------------------- 1 | Leetcode 220: Contains Duplicate III 2 | Detailed video Explanation:https://youtu.be/jRKEp4IYY3E 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 11 | int n = nums.size(); 12 | set ss(nums.begin(), nums.end()); 13 | if( t == 0 && n == ss.size()) return false; 14 | 15 | for(int i = 0; i < n; ++i){ 16 | for(int j = i+1; j < i+1+k; ++j){ 17 | if(j >= n) break; 18 | if(abs((long long)nums[i] - nums[j]) <= t) return true; 19 | } 20 | } 21 | return false; 22 | } 23 | }; 24 | 25 | 26 | Python3: 27 | ------- 28 | class Solution: 29 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: 30 | n = len(nums) 31 | if t == 0 and n == len(set(nums)): return False 32 | 33 | for i in range(n): 34 | for j in range(i+1, i+1+k): 35 | if j >= n: break 36 | if abs(nums[i] - nums[j]) <= t: return True 37 | return False 38 | 39 | 40 | -------------------------------------------------------------------------------- /119_Pascal's_Triangle: -------------------------------------------------------------------------------- 1 | Leetcode 119: Pascal's Triangle II 2 | Detailed video explanation: https://youtu.be/IWXZAvBIuyE 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector getRow(int rowIndex) { 11 | vector result(rowIndex+1, 1); 12 | for(int i = 1; i < rowIndex; ++i){ 13 | for(int j = i; j > 0; --j) 14 | result[j] += result[j-1]; 15 | } 16 | return result; 17 | } 18 | }; 19 | 20 | 21 | Java: 22 | ----- 23 | class Solution { 24 | public List getRow(int rowIndex) { 25 | List result = new ArrayList(); 26 | for(int i = 0; i < rowIndex+1; ++i) result.add(1); 27 | for(int i = 1; i < rowIndex; ++i) 28 | for(int j = i; j > 0; --j) result.set(j, result.get(j) + result.get(j-1)); 29 | return result; 30 | } 31 | } 32 | 33 | 34 | 35 | Python3: 36 | ------- 37 | class Solution: 38 | def getRow(self, rowIndex: int) -> List[int]: 39 | result = [1]*(rowIndex + 1) 40 | for i in range(1, rowIndex): 41 | for j in range(i, 0, -1): 42 | result[j] += result[j-1] 43 | return result 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /442_Find_All_Duplicates_in_an_array: -------------------------------------------------------------------------------- 1 | Leetcode 442: Find all Duplicates in an Array 2 | Detailed video Explanation: https://youtu.be/8ci8WfQ6cns 3 | ========================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector findDuplicates(vector& nums) { 11 | vector result; 12 | for(int n : nums){ 13 | n = abs(n); 14 | if(nums[n-1] > 0) nums[n-1] *= -1; 15 | else result.push_back(n); 16 | } 17 | return result; 18 | } 19 | }; 20 | 21 | 22 | Java: 23 | ----- 24 | class Solution { 25 | public List findDuplicates(int[] nums) { 26 | List result = new ArrayList(); 27 | for(int n: nums){ 28 | n = Math.abs(n); 29 | if(nums[n-1] > 0) nums[n-1] *= -1; 30 | else result.add(n); 31 | } 32 | return result; 33 | } 34 | } 35 | 36 | 37 | Python3: 38 | ------- 39 | class Solution: 40 | def findDuplicates(self, nums: List[int]) -> List[int]: 41 | result = [] 42 | for n in nums: 43 | n = abs(n) 44 | if nums[n-1] > 0: nums[n-1] *= -1 45 | else: result.append(n) 46 | return result 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /23_Merge_k_sorted_lists: -------------------------------------------------------------------------------- 1 | Leetcode 23 : Merge k Sorted Lists 2 | Detailed video explanation: https://youtu.be/QG7AVdPbgb4 3 | ======================================================== 4 | 5 | C++: 6 | --- 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode() : val(0), next(nullptr) {} 13 | * ListNode(int x) : val(x), next(nullptr) {} 14 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | ListNode* mergeKLists(vector& lists) { 20 | auto cmp = [](ListNode *a, ListNode *b){ return a->val > b->val; }; 21 | std::priority_queue, decltype(cmp)> PQ(cmp); 22 | for(auto l : lists) 23 | if(l) PQ.push(l); 24 | if(PQ.empty()) return nullptr; 25 | ListNode *head = PQ.top(); 26 | PQ.pop(); 27 | if(head->next) PQ.push(head->next); 28 | ListNode *curr = head; 29 | while(!PQ.empty()){ 30 | ListNode *n = PQ.top(); 31 | PQ.pop(); 32 | curr->next = n; 33 | curr = n; 34 | if(n->next) PQ.push(n->next); 35 | } 36 | return head; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /260_Single_Number_iii: -------------------------------------------------------------------------------- 1 | Leetcode 260: Single Number III 2 | Detailed video explanation: https://youtu.be/L-EaPf5tD5A 3 | ============================================ 4 | 5 | C++: 6 | ---- 7 | vector singleNumber(vector& nums) { 8 | int xy = 0; 9 | for(int n: nums) xy ^= n; 10 | xy &= -xy; 11 | vector result = {0, 0}; 12 | for(int n: nums){ 13 | if(xy & n) result[0] ^= n; 14 | else result[1] ^= n; 15 | } 16 | return result; 17 | } 18 | 19 | 20 | Java: 21 | ----- 22 | class Solution { 23 | public int[] singleNumber(int[] nums) { 24 | int xy = 0; 25 | for(int n: nums) xy ^= n; 26 | xy &= -xy; 27 | int[] result = new int[2]; 28 | for(int n: nums){ 29 | if((xy & n) == 0) result[0] ^= n; 30 | else result[1] ^= n; 31 | } 32 | return result; 33 | } 34 | } 35 | 36 | 37 | Python3: 38 | ------- 39 | class Solution: 40 | def singleNumber(self, nums: List[int]) -> List[int]: 41 | xy = 0 42 | for n in nums: xy ^= n 43 | xy &= -xy 44 | result = [0]*2 45 | for n in nums: 46 | if (xy & n) == 0: result[0] ^= n 47 | else: result[1] ^= n 48 | return result 49 | -------------------------------------------------------------------------------- /843_Guess_The_Word: -------------------------------------------------------------------------------- 1 | Leetcode 843 : Guess the Word 2 | Detailed video explanation : https://youtu.be/COnrhAabeos 3 | =============================================== 4 | 5 | C++: 6 | ---- 7 | /** 8 | * // This is the Master's API interface. 9 | * // You should not implement it, or speculate about its implementation 10 | * class Master { 11 | * public: 12 | * int guess(string word); 13 | * }; 14 | */ 15 | class Solution { 16 | int findMatches(string w1, string w2){ 17 | int count = 0; 18 | for(int i =0; i < 6; ++i) 19 | if(w1[i] == w2[i]) count++; 20 | return count; 21 | } 22 | public: 23 | void findSecretWord(vector& words, Master& master) { 24 | srand(time(0)); 25 | vector candidates; 26 | for(int i =0; i < words.size(); ++i) 27 | candidates.push_back(words[i]); 28 | 29 | while(!candidates.empty()){ 30 | string word = candidates[rand()%candidates.size()]; 31 | int match = master.guess(word); 32 | if(match == 6) return; 33 | vector temp; 34 | for(string w: candidates) 35 | if(findMatches(w, word) == match) temp.push_back(w); 36 | candidates = temp; 37 | } 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /103_BinaryTree_zigzag_Traversal: -------------------------------------------------------------------------------- 1 | Leetcode 103: Binary Tree Zigzag Level Order Traversal 2 | Detailed video explanation: https://youtu.be/mvQj-L0wEx0 3 | ================================ 4 | 5 | C++: 6 | ---- 7 | vector> zigzagLevelOrder(TreeNode* root) { 8 | if(!root) return {}; 9 | vector> result; 10 | deque Q; 11 | Q.push_front(root); 12 | bool reverse = true; 13 | while(!Q.empty()){ 14 | int count = Q.size(); 15 | vector level_nodes; 16 | deque dQ; 17 | for(int i = 0; i < count; ++i){ 18 | TreeNode* n = Q.front(); 19 | level_nodes.push_back(n->val); 20 | Q.pop_front(); 21 | if(reverse){ 22 | if(n->left) dQ.push_front(n->left); 23 | if(n->right) dQ.push_front(n->right); 24 | } else { 25 | if(n->right) dQ.push_front(n->right); 26 | if(n->left) dQ.push_front(n->left); 27 | } 28 | } 29 | Q.insert(Q.end(), dQ.begin(), dQ.end()); 30 | result.push_back(level_nodes); 31 | reverse = !reverse; 32 | } 33 | return result; 34 | } 35 | -------------------------------------------------------------------------------- /310_Minimum_Height_Trees: -------------------------------------------------------------------------------- 1 | Leetcode 310: Minimum Height Trees 2 | Detailed video explanation: https://youtu.be/qbpP8GIZiqQ 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector findMinHeightTrees(int n, vector>& edges) { 11 | if(n == 1) return {0}; 12 | vector> adj(n); 13 | for(auto& e: edges){ 14 | adj[e[0]].insert(e[1]); 15 | adj[e[1]].insert(e[0]); 16 | } 17 | 18 | queue Q; 19 | for(int i = 0; i < adj.size(); ++i) 20 | if(adj[i].size() == 1) Q.push(i); 21 | 22 | while(n > 2){ 23 | int len = Q.size(); 24 | n = n-len; 25 | for(int i = 0; i < len; ++i){ 26 | int node = Q.front(); 27 | Q.pop(); 28 | for(auto& a: adj[node]){ 29 | adj[a].erase(node); 30 | if(adj[a].size() == 1) 31 | Q.push(a); 32 | } 33 | } 34 | } 35 | vector result; 36 | while(!Q.empty()){ 37 | result.push_back(Q.front()); 38 | Q.pop(); 39 | } 40 | return result; 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /58_Length_of_Last_Word: -------------------------------------------------------------------------------- 1 | Leetcode 58: Length of Last Word 2 | Detailed video explanation: https://youtu.be/E8r1N8wNR0A 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int lengthOfLastWord(string s) { 11 | /* 12 | stringstream ss(s); 13 | string word; 14 | while(ss >> word){} 15 | return word.length(); 16 | */ 17 | int n = s.length(), result = 0; 18 | while(n > 0){ 19 | if(s[--n] != ' ') result++; 20 | else if(result > 0) return result; 21 | } 22 | return result; 23 | } 24 | }; 25 | 26 | 27 | 28 | Java: 29 | ---- 30 | class Solution { 31 | public int lengthOfLastWord(String s) { 32 | int n = s.length(), result = 0; 33 | while(n > 0){ 34 | if(s.charAt(--n) != ' ') result++; 35 | else if(result > 0) return result; 36 | } 37 | return result; 38 | } 39 | } 40 | 41 | 42 | 43 | 44 | Python3: 45 | ------- 46 | class Solution: 47 | def lengthOfLastWord(self, s: str) -> int: 48 | n, result = len(s), 0 49 | while n > 0: 50 | n -= 1 51 | if s[n] != ' ': result += 1 52 | elif result > 0: return result 53 | return result 54 | 55 | 56 | -------------------------------------------------------------------------------- /96_Unique_Binary_Search_Trees: -------------------------------------------------------------------------------- 1 | // LeetCode 96: Unique Binary Search Trees 2 | // Detailed Explanation is available here: https://youtu.be/4s7r3bO0hoU 3 | 4 | // C++: 5 | 6 | int numTrees(int n) { 7 | if(n < 2) return 1; 8 | vector sol(n+1, 0); 9 | sol[0] = 1, sol[1] = 1; 10 | for(int i = 2; i <= n; ++i){ 11 | for(int j = 0; j < i; ++j){ 12 | sol[i] += sol[j]*sol[i-1-j]; 13 | } 14 | } 15 | return sol[n]; 16 | } 17 | 18 | // Java: 19 | 20 | public int numTrees(int n) { 21 | if(n < 2) return 1; 22 | int[] sol = new int[n+1]; 23 | sol[0] = 1; sol[1] = 1; 24 | for(int i = 2; i <= n; ++i){ 25 | for(int j = 0; j < i; ++j){ 26 | sol[i] += sol[j]*sol[i-1-j]; 27 | } 28 | } 29 | return sol[n]; 30 | } 31 | 32 | 33 | # Python3: 34 | 35 | def numTrees(self, n: int) -> int: 36 | if(n < 2): return 1 37 | sol = [0]*(n+1) 38 | sol[0], sol[1] = 1, 1 39 | for i in range(2, n+1): 40 | for j in range(0, i): 41 | sol[i] += sol[j]*sol[i-1-j] 42 | return sol[n] 43 | 44 | ***** Please Like, Share and Subscribe Knowledge Center : https://www.youtube.com/c/KnowledgeCenter ***** 45 | -------------------------------------------------------------------------------- /154_Find_Minimum_in_Rotated_Sorted_Array_ii: -------------------------------------------------------------------------------- 1 | Leetcode 154: Find Minimum in Rotated Sorted Array ii 2 | Detailed video explanation: https://youtu.be/K0PjrikGKK4 3 | =================================================== 4 | 5 | C++: 6 | --- 7 | int findMin(vector& nums) { 8 | int l = 0, r = nums.size()-1; 9 | while(l < r){ 10 | int mid = l + (r-l)/2; 11 | if(nums[mid] > nums[r]) l = mid+1; 12 | else if(nums[mid] < nums[r]) r = mid; 13 | else r--; 14 | } 15 | return nums[l]; 16 | } 17 | 18 | 19 | Java: 20 | ----- 21 | class Solution { 22 | public int findMin(int[] nums) { 23 | int l = 0, r = nums.length-1; 24 | while(l < r){ 25 | int mid = l + (r-l)/2; 26 | if(nums[mid] > nums[r]) l = mid+1; 27 | else if(nums[mid] < nums[r]) r = mid; 28 | else r--; 29 | } 30 | return nums[l]; 31 | } 32 | } 33 | 34 | 35 | Python3: 36 | ------- 37 | class Solution: 38 | def findMin(self, nums: List[int]) -> int: 39 | l, r = 0, len(nums)-1 40 | while l < r: 41 | mid = l + (r-l)//2 42 | if nums[mid] > nums[r]: l = mid+1 43 | elif nums[mid] < nums[r]: r = mid 44 | else: r -= 1 45 | return nums[l] 46 | 47 | 48 | -------------------------------------------------------------------------------- /981_Time_based_key_value_store: -------------------------------------------------------------------------------- 1 | Leetcode 981 : Time Based Key-value Store 2 | Detailed video explanation: https://youtu.be/Y6ZtxsrnJEs 3 | ------------------------------------------------------------ 4 | 5 | C++: 6 | ---- 7 | 8 | class TimeMap { 9 | unordered_map>> _map; 10 | public: 11 | TimeMap() { 12 | 13 | } 14 | 15 | void set(string key, string value, int timestamp) { 16 | _map[key].push_back({timestamp, value}); 17 | } 18 | 19 | string get(string key, int timestamp) { 20 | int n = _map[key].size(); 21 | int l = 0, r = n-1; 22 | while(l <= r){ 23 | int mid = l + (r-l)/2; 24 | if(_map[key][mid].first < timestamp){ 25 | if(mid == r || _map[key][mid+1].first > timestamp) 26 | return _map[key][mid].second; 27 | l = mid + 1; 28 | } else if(_map[key][mid].first > timestamp) 29 | r = mid-1; 30 | else 31 | return _map[key][mid].second; 32 | } 33 | return ""; 34 | } 35 | }; 36 | 37 | /** 38 | * Your TimeMap object will be instantiated and called as such: 39 | * TimeMap* obj = new TimeMap(); 40 | * obj->set(key,value,timestamp); 41 | * string param_2 = obj->get(key,timestamp); 42 | */ 43 | -------------------------------------------------------------------------------- /153_Find_Minimum_in_Rotated_Sorted_Array: -------------------------------------------------------------------------------- 1 | Leetcode 153: Find Minimum in Rotated Sorted Array 2 | Detailed video explanation: https://youtu.be/OXkLNPalfRs 3 | =================================================== 4 | 5 | C++: 6 | --- 7 | int findMin(vector& nums) { 8 | int l = 0, r = nums.size()-1; 9 | while(l < r){ 10 | int mid = l + (r-l)/2; 11 | if(nums[mid] > nums[r]) l = mid+1; 12 | else if(nums[mid] < nums[r]) r = mid; 13 | else return nums[r]; 14 | } 15 | return nums[l]; 16 | } 17 | 18 | Java: 19 | ----- 20 | class Solution { 21 | public int findMin(int[] nums) { 22 | int l = 0, r = nums.length-1; 23 | while(l < r){ 24 | int mid = l + (r-l)/2; 25 | if(nums[mid] > nums[r]) l = mid+1; 26 | else if(nums[mid] < nums[r]) r = mid; 27 | else return nums[r]; 28 | } 29 | return nums[l]; 30 | } 31 | } 32 | 33 | Python3: 34 | ------- 35 | class Solution: 36 | def findMin(self, nums: List[int]) -> int: 37 | l, r = 0, len(nums) - 1 38 | while l < r: 39 | mid = l + (r-l)//2 40 | if nums[mid] > nums[r]: l = mid+1 41 | elif nums[mid] < nums[r]: r = mid 42 | else: return nums[r] 43 | 44 | return nums[l] 45 | -------------------------------------------------------------------------------- /832_Flipping_an_Image: -------------------------------------------------------------------------------- 1 | Leetcode 832: Flipping an Image 2 | Detailed video explanation: https://youtu.be/sEpxwhzSIis 3 | =============================================== 4 | 5 | C++: 6 | --- 7 | class Solution { 8 | public: 9 | vector> flipAndInvertImage(vector>& A) { 10 | int c = A[0].size(); 11 | for(auto& row: A){ 12 | for(int i = 0; i < (c+1)/2; ++i){ 13 | int tmp = row[i]; 14 | row[i] = 1 - row[c-1-i]; 15 | row[c-1-i] = 1 - tmp; 16 | } 17 | } 18 | return A; 19 | } 20 | }; 21 | 22 | 23 | Java: 24 | ----- 25 | class Solution { 26 | public int[][] flipAndInvertImage(int[][] A) { 27 | int c = A[0].length; 28 | for(int[] row: A){ 29 | for(int i = 0; i < (c+1)/2; ++i){ 30 | int tmp = row[i]; 31 | row[i] = 1 - row[c-1-i]; 32 | row[c-1-i] = 1 - tmp; 33 | } 34 | } 35 | return A; 36 | } 37 | } 38 | 39 | 40 | 41 | Python3: 42 | ------- 43 | class Solution: 44 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 45 | c = len(A[0]) 46 | for row in A: 47 | for i in range((c+1)//2): 48 | row[i], row[c-1-i] = 1-row[c-1-i], 1-row[i] 49 | 50 | return A; 51 | 52 | 53 | -------------------------------------------------------------------------------- /905_Sort_Array_By_Parity: -------------------------------------------------------------------------------- 1 | Leetcode 905: Sort Array By Parity 2 | Detailed video Explanation: https://youtu.be/H19zVrrpn5E 3 | ======================================================== 4 | 5 | 6 | C++: 7 | --- 8 | class Solution { 9 | public: 10 | vector sortArrayByParity(vector& A) { 11 | int l = 0, r = A.size()-1; 12 | while(l < r){ 13 | while(l < r && A[l] % 2 == 0) l++; 14 | while(l < r && A[r] % 2 == 1) r--; 15 | int tmp = A[l]; 16 | A[l] = A[r]; 17 | A[r] = tmp; 18 | } 19 | return A; 20 | } 21 | }; 22 | 23 | 24 | Java: 25 | ----- 26 | class Solution { 27 | public int[] sortArrayByParity(int[] A) { 28 | int l = 0, r = A.length-1; 29 | while(l < r){ 30 | while(l < r && A[l] % 2 == 0) l++; 31 | while(l < r && A[r] % 2 == 1) r--; 32 | int tmp = A[l]; 33 | A[l] = A[r]; 34 | A[r] = tmp; 35 | } 36 | return A; 37 | } 38 | } 39 | 40 | 41 | Python3: 42 | ------- 43 | class Solution: 44 | def sortArrayByParity(self, A: List[int]) -> List[int]: 45 | l, r = 0, len(A)-1 46 | while l < r: 47 | while l < r and A[l] % 2 == 0: l += 1 48 | while l < r and A[r] % 2 == 1: r -= 1 49 | A[l], A[r] = A[r], A[l] 50 | return A 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /98_Validate_BST: -------------------------------------------------------------------------------- 1 | Leetcode 98 : Validate Binary Search tree 2 | Detailed explanation video : https://youtu.be/IjQhjyihnQ4 3 | ================================================ 4 | 5 | C++: 6 | ---- 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | * }; 17 | */ 18 | class Solution { 19 | bool isValid(TreeNode* root, int& _max, int& _min) { 20 | _max = _min = root->val; 21 | if(root->left){ 22 | int m1 = INT_MIN, m2 = INT_MAX; 23 | if(!isValid(root->left, m1, m2)) return false; 24 | if(m1 >= root->val) return false; 25 | _min = std::min(_min, m2); 26 | } 27 | if(root->right){ 28 | int m1 = INT_MIN, m2 = INT_MAX; 29 | if(!isValid(root->right, m1, m2)) return false; 30 | if(m2 <= root->val) return false; 31 | _max = std::max(_max, m1); 32 | } 33 | return true; 34 | } 35 | public: 36 | bool isValidBST(TreeNode* root) { 37 | int m1 = INT_MIN, m2 = INT_MAX; 38 | return isValid(root, m1, m2); 39 | } 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /974_Subarray_Sum_Divisible_by_K: -------------------------------------------------------------------------------- 1 | Leetcode 974: Subarray Sum Divisible By K 2 | Detailed video Explanation: https://youtu.be/u9m-hnlcydk 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int subarraysDivByK(vector& A, int K) { 11 | vector counts(K, 0); 12 | int sum = 0; 13 | for(int x: A){ 14 | sum += (x%K + K)%K; 15 | counts[sum % K]++; 16 | } 17 | int result = counts[0]; 18 | for(int c : counts) 19 | result += (c*(c-1))/2; 20 | return result; 21 | } 22 | }; 23 | 24 | 25 | Java: 26 | ----- 27 | class Solution { 28 | public int subarraysDivByK(int[] A, int K) { 29 | int[] counts = new int[K]; 30 | int sum = 0; 31 | for(int x: A){ 32 | sum += (x%K + K)%K; 33 | counts[sum % K]++; 34 | } 35 | int result = counts[0]; 36 | for(int c : counts) 37 | result += (c*(c-1))/2; 38 | return result; 39 | } 40 | } 41 | 42 | 43 | Python3: 44 | ------- 45 | class Solution: 46 | def subarraysDivByK(self, A: List[int], K: int) -> int: 47 | counts = [0]*K 48 | sum = 0 49 | for x in A: 50 | sum += x%K 51 | counts[sum % K] += 1 52 | result = counts[0] 53 | for c in counts: 54 | result += (c*(c-1))//2 55 | return result 56 | 57 | 58 | -------------------------------------------------------------------------------- /66_Plus_One: -------------------------------------------------------------------------------- 1 | LeetCode 66: Plus One 2 | Detailed video explanation is available here on KnowledgeCenter Channel: https://youtu.be/yzlQj0LR7m8 3 | 4 | C++: 5 | ---- 6 | vector plusOne(vector& digits) { 7 | int idx = digits.size()-1; 8 | while(idx >= 0){ 9 | if(digits[idx] == 9) 10 | digits[idx] = 0; 11 | else{ 12 | digits[idx] += 1; 13 | return digits; 14 | } 15 | idx--; 16 | } 17 | digits.insert(digits.begin(), 1); 18 | return digits; 19 | } 20 | 21 | 22 | Java: 23 | ---- 24 | public int[] plusOne(int[] digits) { 25 | int idx = digits.length-1; 26 | while(idx >= 0){ 27 | if(digits[idx] == 9) 28 | digits[idx] = 0; 29 | else{ 30 | digits[idx] += 1; 31 | return digits; 32 | } 33 | idx--; 34 | } 35 | int[] result = new int[digits.length + 1]; 36 | result[0] = 1; 37 | return result; 38 | } 39 | 40 | 41 | Python3: 42 | ------- 43 | def plusOne(self, digits: List[int]) -> List[int]: 44 | idx = len(digits) - 1 45 | while idx >= 0: 46 | if digits[idx] == 9: 47 | digits[idx] = 0 48 | else: 49 | digits[idx] += 1 50 | return digits 51 | idx -= 1 52 | 53 | return [1] + digits 54 | -------------------------------------------------------------------------------- /198_House_Robber: -------------------------------------------------------------------------------- 1 | Leetcode 198: House Robber 2 | Detailed video explanation: https://youtu.be/jzpsHKJy00c 3 | ========================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int rob(vector& nums) { 11 | int n = nums.size(); 12 | if(n == 0) return 0; 13 | if(n == 1) return nums[0]; 14 | int v1 = nums[0], v2 = max(v1, nums[1]); 15 | for(int i = 2; i < n; ++i){ 16 | int tmp = v2; 17 | v2 = max(v2, v1 + nums[i]); 18 | v1 = tmp; 19 | } 20 | return v2; 21 | } 22 | }; 23 | 24 | 25 | 26 | Java: 27 | ---- 28 | class Solution { 29 | public int rob(int[] nums) { 30 | int n = nums.length; 31 | if(n == 0) return 0; 32 | if(n == 1) return nums[0]; 33 | int v1 = nums[0], v2 = Math.max(v1, nums[1]); 34 | for(int i = 2; i < n; ++i){ 35 | int tmp = v2; 36 | v2 = Math.max(v2, v1 + nums[i]); 37 | v1 = tmp; 38 | } 39 | return v2; 40 | } 41 | } 42 | 43 | 44 | 45 | Python3: 46 | ------- 47 | class Solution: 48 | def rob(self, nums: List[int]) -> int: 49 | n = len(nums) 50 | if n == 0: return 0 51 | if n == 1: return nums[0] 52 | v1, v2 = nums[0], max(nums[0], nums[1]) 53 | for i in range(2, n): 54 | tmp = v2; 55 | v2 = max(v2, v1 + nums[i]) 56 | v1 = tmp 57 | return v2 58 | 59 | 60 | -------------------------------------------------------------------------------- /470_Implement_Rand10_Using_Rand7: -------------------------------------------------------------------------------- 1 | Leetcode 470: Implement Rand10() Using Rand7() 2 | Detailed video explanation: https://youtu.be/BvYd6KSW4nQ 3 | ================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | // The rand7() API is already defined for you. 9 | // int rand7(); 10 | // @return a random integer in the range 1 to 7 11 | 12 | class Solution { 13 | public: 14 | int rand10() { 15 | int v1 = rand7(), v2 = rand7(); 16 | while(v1 > 5) v1 = rand7(); 17 | while(v2 == 7) v2 = rand7(); 18 | return (v2 <= 3)?v1:v1+5; 19 | } 20 | }; 21 | 22 | 23 | 24 | Java: 25 | ----- 26 | /** 27 | * The rand7() API is already defined in the parent class SolBase. 28 | * public int rand7(); 29 | * @return a random integer in the range 1 to 7 30 | */ 31 | class Solution extends SolBase { 32 | public int rand10() { 33 | int v1 = rand7(), v2 = rand7(); 34 | while(v1 > 5) v1 = rand7(); 35 | while(v2 == 7) v2 = rand7(); 36 | return (v2 <= 3)?v1:v1+5; 37 | } 38 | } 39 | 40 | 41 | 42 | Python3: 43 | ------- 44 | # The rand7() API is already defined for you. 45 | # def rand7(): 46 | # @return a random integer in the range 1 to 7 47 | 48 | class Solution: 49 | def rand10(self): 50 | """ 51 | :rtype: int 52 | """ 53 | v1, v2 = rand7(), rand7() 54 | while v1 > 5: v1 = rand7() 55 | while v2 == 7: v2 = rand7() 56 | return v1 if (v2 <= 3) else (v1+5) 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /881_Boats_to_Save_People: -------------------------------------------------------------------------------- 1 | Leetcode 881: Boats to Save People 2 | Detailed video explanation: https://youtu.be/MTStYiAJrKk 3 | ==================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int numRescueBoats(vector& people, int limit) { 10 | sort(people.begin(), people.end()); 11 | int i = 0, j = people.size() - 1; 12 | int boats = 0; 13 | 14 | while(i <= j){ 15 | if(people[i] + people[j] <= limit) 16 | i++; 17 | j--; 18 | boats++; 19 | } 20 | return boats; 21 | } 22 | }; 23 | 24 | 25 | 26 | 27 | Java: 28 | ----- 29 | class Solution { 30 | public int numRescueBoats(int[] people, int limit) { 31 | Arrays.sort(people); 32 | int i = 0, j = people.length - 1; 33 | int boats = 0; 34 | 35 | while(i <= j){ 36 | if(people[i] + people[j] <= limit) 37 | i++; 38 | j--; 39 | boats++; 40 | } 41 | return boats; 42 | } 43 | } 44 | 45 | 46 | 47 | 48 | Python3: 49 | -------- 50 | class Solution: 51 | def numRescueBoats(self, people: List[int], limit: int) -> int: 52 | people.sort() 53 | i, j = 0, len(people) - 1 54 | boats = 0 55 | 56 | while i <= j: 57 | if (people[i] + people[j]) <= limit: 58 | i = i+1 59 | j -= 1 60 | boats += 1 61 | 62 | return boats 63 | 64 | 65 | -------------------------------------------------------------------------------- /309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown: -------------------------------------------------------------------------------- 1 | Leetcode 309: Best Time to Buy and Sell Stock with Cooldown 2 | Detailed video explanation: https://youtu.be/pkiJyNijgBw 3 | ============================================================= 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int maxProfit(vector& prices) { 10 | if(prices.size() <= 1) return 0; 11 | int A = 0, B = -prices[0], C = 0; 12 | for(int i = 1; i < prices.size(); ++i){ 13 | int tmp = A; 14 | A = max(A, C); 15 | C = B + prices[i]; 16 | B = max(B, tmp - prices[i]); 17 | } 18 | return max(A, C); 19 | } 20 | }; 21 | 22 | 23 | Java: 24 | ---- 25 | class Solution { 26 | public int maxProfit(int[] prices) { 27 | if(prices.length <= 1) return 0; 28 | int A = 0, B = -prices[0], C = 0; 29 | for(int i = 1; i < prices.length; ++i){ 30 | int tmp = A; 31 | A = Math.max(A, C); 32 | C = B + prices[i]; 33 | B = Math.max(B, tmp - prices[i]); 34 | } 35 | return Math.max(A, C); 36 | } 37 | } 38 | 39 | 40 | Python3: 41 | ------- 42 | class Solution: 43 | def maxProfit(self, prices: List[int]) -> int: 44 | if len(prices) <= 1: return 0 45 | A, B, C = 0, -prices[0], 0 46 | for i in range(1, len(prices)): 47 | tmp = A 48 | A = max(A, C) 49 | C = B + prices[i] 50 | B = max(B, tmp - prices[i]) 51 | 52 | return max(A, C) 53 | -------------------------------------------------------------------------------- /412_Fizz_Buzz: -------------------------------------------------------------------------------- 1 | Leetcode 412: Fizz Buzz 2 | Detailed video explanation: https://youtu.be/13gtlfrR6L8 3 | =========================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector fizzBuzz(int n) { 11 | vector result(n, ""); 12 | for(int i = 1; i < n+1; ++i){ 13 | if(i % 15 == 0) result[i-1] = "FizzBuzz"; 14 | else if (i % 5 == 0) result[i-1] = "Buzz"; 15 | else if (i % 3 == 0) result[i-1] = "Fizz"; 16 | else result[i-1] = to_string(i); 17 | } 18 | return result; 19 | } 20 | }; 21 | 22 | 23 | Java: 24 | ----- 25 | class Solution { 26 | public List fizzBuzz(int n) { 27 | String[] result = new String[n]; 28 | for(int i = 1; i < n+1; ++i){ 29 | if(i % 15 == 0) result[i-1] = "FizzBuzz"; 30 | else if (i % 5 == 0) result[i-1] = "Buzz"; 31 | else if (i % 3 == 0) result[i-1] = "Fizz"; 32 | else result[i-1] = Integer.toString(i); 33 | } 34 | return Arrays.asList(result); 35 | } 36 | } 37 | 38 | 39 | Python3: 40 | ------- 41 | class Solution: 42 | def fizzBuzz(self, n: int) -> List[str]: 43 | result = [None]*n 44 | for i in range(1, n+1): 45 | if i % 15 == 0: result[i-1] = "FizzBuzz" 46 | elif i % 5 == 0: result[i-1] = "Buzz" 47 | elif i % 3 == 0: result[i-1] = "Fizz" 48 | else: result[i-1] = str(i) 49 | 50 | return result 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /189_Rotate_Array: -------------------------------------------------------------------------------- 1 | Leetocde 189: Rotate Array 2 | Detailed video Explanation: https://youtu.be/5D9OrHsw3M0 3 | ======================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | void rotate(vector& nums, int k) { 11 | int n = nums.size(); 12 | k %= n; 13 | reverse(nums.begin(), nums.begin()+n-k); 14 | reverse(nums.begin() + n - k, nums.end()); 15 | reverse(nums.begin(), nums.end()); 16 | } 17 | }; 18 | 19 | 20 | 21 | Java: 22 | ----- 23 | class Solution { 24 | public void reverse(int[] nums, int l, int r){ 25 | while(l < r){ 26 | int temp = nums[l]; 27 | nums[l] = nums[r]; 28 | nums[r] = temp; 29 | l++; 30 | r--; 31 | } 32 | } 33 | public void rotate(int[] nums, int k) { 34 | int n = nums.length; 35 | k %= n; 36 | reverse(nums, 0, n-k-1); 37 | reverse(nums, n - k, n - 1); 38 | reverse(nums, 0, n-1); 39 | } 40 | } 41 | 42 | 43 | 44 | Python3: 45 | -------- 46 | class Solution: 47 | def reverse(self, nums, l, r): 48 | while l < r: 49 | nums[l], nums[r] = nums[r], nums[l] 50 | l += 1 51 | r -= 1 52 | 53 | def rotate(self, nums: List[int], k: int) -> None: 54 | """ 55 | Do not return anything, modify nums in-place instead. 56 | """ 57 | n = len(nums) 58 | k %= n 59 | self.reverse(nums, 0, n-k-1) 60 | self.reverse(nums, n - k, n - 1) 61 | self.reverse(nums, 0, n-1) 62 | 63 | -------------------------------------------------------------------------------- /1283_Find_the_Smallest_Divisor_Given_Threshold: -------------------------------------------------------------------------------- 1 | Leetcode 1283: Find the Smallest Divisor Given a Threshold 2 | Detailed video explanation: https://youtu.be/6b_YFPOYJEk 3 | =========================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | long compute_sum(vector& nums, int x){ 10 | long sum = 0; 11 | for(int n: nums) 12 | sum += n/x + (n%x == 0?0:1); 13 | return sum; 14 | } 15 | public: 16 | int smallestDivisor(vector& nums, int threshold) { 17 | int end = 2; 18 | while(compute_sum(nums, end) > threshold) end <<= 1; 19 | 20 | int start = end >> 1; 21 | while(start < end){ 22 | int mid = start + (end-start)/2; 23 | if(compute_sum(nums, mid) > threshold) start = mid+1; 24 | else end = mid; 25 | } 26 | return start; 27 | } 28 | }; 29 | 30 | 31 | 32 | Java: 33 | ----- 34 | class Solution { 35 | private long compute_sum(int[] nums, int x){ 36 | long sum = 0; 37 | for(int n: nums) 38 | sum += n/x + (n%x == 0?0:1); 39 | return sum; 40 | } 41 | 42 | public int smallestDivisor(int[] nums, int threshold) { 43 | int end = 2; 44 | while(compute_sum(nums, end) > threshold) end <<= 1; 45 | 46 | int start = end >> 1; 47 | while(start < end){ 48 | int mid = start + (end-start)/2; 49 | if(compute_sum(nums, mid) > threshold) start = mid+1; 50 | else end = mid; 51 | } 52 | return start; 53 | } 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /62_unique_paths: -------------------------------------------------------------------------------- 1 | Leetcode 62: Unique Paths 2 | Detailed Explanation can be found here: https://youtu.be/-fS1pS1mxQc 3 | 4 | C++ 5 | class Solution { 6 | public: 7 | int uniquePaths(int m, int n) { 8 | vector> paths(n, vector(m)); 9 | for(int c = 0; c < m; ++c) 10 | paths[n-1][c] = 1; 11 | for(int r = 0; r < n; ++r) 12 | paths[r][m-1] = 1; 13 | for(int r = n-2; r >= 0; --r){ 14 | for(int c = m-2; c >= 0; --c){ 15 | paths[r][c] = paths[r][c+1] + paths[r+1][c]; 16 | } 17 | } 18 | return paths[0][0]; 19 | } 20 | }; 21 | Java 22 | class Solution { 23 | public int uniquePaths(int m, int n) { 24 | int[][] paths = new int[n][m]; 25 | for(int c = 0; c < m; ++c) 26 | paths[n-1][c] = 1; 27 | for(int r = 0; r < n; ++r) 28 | paths[r][m-1] = 1; 29 | for(int r = n-2; r >= 0; --r){ 30 | for(int c = m-2; c >= 0; --c){ 31 | paths[r][c] = paths[r][c+1] + paths[r+1][c]; 32 | } 33 | } 34 | return paths[0][0]; 35 | } 36 | } 37 | Python3 38 | class Solution: 39 | def uniquePaths(self, m: int, n: int) -> int: 40 | paths = [[0]*m for i in range(n)] 41 | for c in range(m): 42 | paths[n-1][c] = 1 43 | for r in range(n): 44 | paths[r][m-1] = 1 45 | for r in range(n-2, -1, -1): 46 | for c in range(m-2, -1, -1): 47 | paths[r][c] = paths[r][c+1] + paths[r+1][c] 48 | 49 | return paths[0][0] 50 | 51 | 52 | -------------------------------------------------------------------------------- /459_Repeated_Substring_Pattern: -------------------------------------------------------------------------------- 1 | Leetcode 459: Repeated Substring Pattern 2 | Detailed video Explanation: https://youtu.be/p92_kEjyJAo 3 | ============================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool repeatedSubstringPattern(string s) { 11 | int n = s.length(); 12 | vector lps(n, 0); 13 | for(int i = 1; i < n; ++i){ 14 | int j = lps[i-1]; 15 | while(j > 0 && s[i] != s[j]) j = lps[j-1]; 16 | if(s[i] == s[j]) ++j; 17 | lps[i] = j; 18 | } 19 | int l = lps[n-1]; 20 | return (l != 0) && (l % (n-l) == 0); 21 | } 22 | }; 23 | 24 | 25 | 26 | Java: 27 | ----- 28 | class Solution { 29 | public boolean repeatedSubstringPattern(String s) { 30 | int n = s.length(); 31 | int[] lps = new int[n]; 32 | for(int i = 1; i < n; ++i){ 33 | int j = lps[i-1]; 34 | while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j-1]; 35 | if(s.charAt(i) == s.charAt(j)) ++j; 36 | lps[i] = j; 37 | } 38 | int l = lps[n-1]; 39 | return (l != 0) && (l % (n-l) == 0); 40 | } 41 | } 42 | 43 | 44 | 45 | Python3: 46 | -------- 47 | class Solution: 48 | def repeatedSubstringPattern(self, s: str) -> bool: 49 | n = len(s) 50 | lps = [0]*n 51 | for i in range(1, n): 52 | j = lps[i-1] 53 | while j > 0 and s[i] != s[j]: j = lps[j-1] 54 | if s[i] == s[j]: j += 1 55 | lps[i] = j 56 | l = lps[n-1] 57 | return l != 0 and (l % (n-l) == 0) 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /662_Max_width_of_Binary_tree: -------------------------------------------------------------------------------- 1 | Leetcode 662: Maximum width of Binary Tree 2 | Detailed video explanation: https://youtu.be/le-ZZSQRebw 3 | 4 | C++: 5 | ---- 6 | int widthOfBinaryTree(TreeNode* root) { 7 | if(!root) return 0; 8 | int result = 1; 9 | queue> Q; 10 | Q.push({root, 0}); 11 | while(!Q.empty()){ 12 | int count = Q.size(); 13 | int start = Q.front().second; 14 | int end = Q.back().second; 15 | result = max(result, end-start+1); 16 | for(int i = 0; i < count; ++i){ 17 | pair p = Q.front(); 18 | int idx = p.second - start; 19 | Q.pop(); 20 | if(p.first->left) Q.push({p.first->left, 2*idx+1}); 21 | if(p.first->right) Q.push({p.first->right, 2*idx+2}); 22 | } 23 | 24 | } 25 | return result; 26 | } 27 | 28 | 29 | Python3: 30 | ------- 31 | def widthOfBinaryTree(self, root: TreeNode) -> int: 32 | if root == None: return 0 33 | result = 1 34 | Q = [[root, 0]] 35 | while len(Q) > 0: 36 | count = len(Q) 37 | start = Q[0][1] 38 | end = Q[-1][1] 39 | result = max(result, end-start+1) 40 | for i in range(count): 41 | p = Q[0] 42 | idx = p[1] - start 43 | Q.pop(0) 44 | if (p[0].left != None): Q.append([p[0].left, 2*idx+1]) 45 | if p[0].right != None: Q.append([p[0].right, 2*idx+2]) 46 | 47 | return result 48 | -------------------------------------------------------------------------------- /140_Word_Break_ii: -------------------------------------------------------------------------------- 1 | Leetcode 140: Word Break ii 2 | Detailed video explanation: https://youtu.be/9-grHHGUVls 3 | ======================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | unordered_map> dp; 9 | public: 10 | vector wordBreak(string s, vector& wordDict) { 11 | if(dp.find(s) != dp.end()) return dp[s]; 12 | vector result; 13 | for(string w : wordDict){ 14 | if(s.substr(0, w.length()) == w){ 15 | if(w.length() == s.length()) 16 | result.push_back(w); 17 | else{ 18 | vector tmp = wordBreak(s.substr(w.length()), wordDict); 19 | for(string t : tmp) 20 | result.push_back(w + " " + t); 21 | } 22 | } 23 | } 24 | dp[s] = result; 25 | return result; 26 | } 27 | }; 28 | 29 | 30 | Python3: 31 | -------- 32 | class Solution: 33 | def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: 34 | dp = {} 35 | def word_break(s): 36 | if s in dp: return dp[s] 37 | result = [] 38 | for w in wordDict: 39 | if s[:len(w)] == w: 40 | if len(w) == len(s): result.append(w) 41 | else: 42 | tmp = word_break(s[len(w):]) 43 | for t in tmp: 44 | result.append(w + " " + t) 45 | dp[s] = result 46 | return result 47 | 48 | return word_break(s) 49 | 50 | 51 | -------------------------------------------------------------------------------- /1446_Consecutive_Characters: -------------------------------------------------------------------------------- 1 | Leetcode 1446: Consecutive Characters 2 | Detailed video explanation: https://youtu.be/TlAvNEo1IIc 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int maxPower(string s) { 11 | int count = 1, max_count = 1; 12 | char prev = s[0]; 13 | for(int i = 1; i < s.length(); ++i){ 14 | if(s[i] == prev){ 15 | count++; 16 | max_count = max(max_count, count); 17 | } else { 18 | count = 1; 19 | prev = s[i]; 20 | } 21 | } 22 | return max_count; 23 | } 24 | }; 25 | 26 | 27 | 28 | Java: 29 | ----- 30 | class Solution { 31 | public int maxPower(String s) { 32 | int count = 1, max_count = 1; 33 | char prev = s.charAt(0); 34 | for(int i = 1; i < s.length(); ++i){ 35 | if(s.charAt(i) == prev){ 36 | count++; 37 | max_count = Math.max(max_count, count); 38 | } else { 39 | count = 1; 40 | prev = s.charAt(i); 41 | } 42 | } 43 | return max_count; 44 | } 45 | } 46 | 47 | 48 | 49 | 50 | Python3: 51 | -------- 52 | class Solution: 53 | def maxPower(self, s: str) -> int: 54 | count, max_count = 1, 1 55 | prev = s[0] 56 | for i in range(1, len(s)): 57 | if s[i] == prev: 58 | count += 1 59 | max_count = max(max_count, count) 60 | else: 61 | count = 1 62 | prev = s[i] 63 | return max_count 64 | 65 | 66 | -------------------------------------------------------------------------------- /222_Count_Complete_Tree_Nodes: -------------------------------------------------------------------------------- 1 | // LeetCode 222: Count Complete Tree Nodes 2 | // Detailed Explanation available here: https://youtu.be/i_r2uKbwHCU 3 | 4 | // C++: 5 | int countNodes(TreeNode* root) { 6 | if(!root) return 0; 7 | TreeNode *left = root, *right = root; 8 | int h_l = 0, h_r = 0; 9 | while(left){ 10 | h_l++; 11 | left = left->left; 12 | } 13 | while(right){ 14 | h_r++; 15 | right = right->right; 16 | } 17 | if(h_l == h_r) return (1<left) + countNodes(root->right); 20 | } 21 | 22 | // Java: 23 | public int countNodes(TreeNode root) { 24 | if(root == null) return 0; 25 | TreeNode left = root, right = root; 26 | int h_l = 0, h_r = 0; 27 | while(left != null){ 28 | h_l++; 29 | left = left.left; 30 | } 31 | while(right != null){ 32 | h_r++; 33 | right = right.right; 34 | } 35 | if(h_l == h_r) return (1< int: 42 | if root == None: return 0 43 | left, right = root, root 44 | h_l, h_r = 0, 0 45 | while left != None: 46 | h_l += 1 47 | left = left.left 48 | 49 | while right != None: 50 | h_r += 1 51 | right = right.right 52 | 53 | if h_l == h_r: return (1<>& grid, int i, int j){ 10 | int r = grid.size(); 11 | int c = grid[0].size(); 12 | if(i < 0 || j < 0 || i >= r || j >= c || grid[i][j] != 1) 13 | return 0; 14 | grid[i][j] = 2; 15 | return (1 + dfs(grid, i+1, j) + dfs(grid, i-1, j) + dfs(grid, i, j+1) + dfs(grid, i, j-1)); 16 | } 17 | public: 18 | int maxAreaOfIsland(vector>& grid) { 19 | int r = grid.size(); 20 | int c = grid[0].size(); 21 | int result = 0; 22 | for(int i = 0; i < r; ++i){ 23 | for(int j = 0; j < c; ++j) 24 | if(grid[i][j] == 1) result = max(result, dfs(grid, i, j)); 25 | } 26 | return result; 27 | } 28 | }; 29 | 30 | 31 | 32 | Python3: 33 | ------- 34 | class Solution: 35 | def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 36 | r, c = len(grid), len(grid[0]) 37 | 38 | def dfs(grid, i, j): 39 | if i < 0 or j < 0 or i >= r or j >= c or grid[i][j] != 1: 40 | return 0 41 | grid[i][j] = 2 42 | return (1 + dfs(grid, i+1, j) + dfs(grid, i-1, j) + dfs(grid, i, j+1) + dfs(grid, i, j-1)) 43 | 44 | result = 0 45 | for i in range(r): 46 | for j in range(c): 47 | if grid[i][j] == 1: result = max(result, dfs(grid, i, j)) 48 | 49 | return result 50 | 51 | 52 | -------------------------------------------------------------------------------- /151_Reverse_Words_in_String: -------------------------------------------------------------------------------- 1 | Leetcode 151: Reverse Words in a String 2 | Detailed video explanation link: https://youtu.be/vhnRAaJybpA 3 | 4 | C++: 5 | ---- 6 | string reverseWords(string s) { 7 | string result; 8 | int i = 0; 9 | int n = s.length(); 10 | 11 | while(i < n){ 12 | while(i < n && s[i] == ' ') i++; 13 | if(i >= n) break; 14 | int j = i + 1; 15 | while(j < n && s[j] != ' ') j++; 16 | string sub = s.substr(i, j-i); 17 | if(result.length() == 0) result = sub; 18 | else result = sub + " " + result; 19 | i = j+1; 20 | } 21 | return result; 22 | } 23 | 24 | 25 | Java: 26 | ---- 27 | public String reverseWords(String s) { 28 | String result = new String(); 29 | int i = 0; 30 | int n = s.length(); 31 | 32 | while(i < n){ 33 | while(i < n && s.charAt(i) == ' ') i++; 34 | if(i >= n) break; 35 | int j = i + 1; 36 | while(j < n && s.charAt(j) != ' ') j++; 37 | String sub = s.substring(i, j); 38 | if(result.length() == 0) result = sub; 39 | else result = sub + " " + result; 40 | i = j+1; 41 | } 42 | return result; 43 | } 44 | 45 | 46 | Python3: 47 | ------- 48 | def reverseWords(self, s: str) -> str: 49 | result = "" 50 | i = 0 51 | n = len(s) 52 | 53 | while i < n: 54 | while i < n and s[i] == ' ': i += 1 55 | if i >= n: break 56 | j = i + 1 57 | while j < n and s[j] != ' ': j += 1 58 | sub = s[i:j] 59 | if len(result) == 0: result = sub 60 | else: result = sub + " " + result 61 | i = j+1 62 | 63 | return result 64 | 65 | 66 | -------------------------------------------------------------------------------- /1539_Kth_Missing_Positive_Number: -------------------------------------------------------------------------------- 1 | Leetcode 1539: Kth Missing Positive Number 2 | Detailed video explanation: 3 | ==================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int findKthPositive(vector& arr, int k) { 11 | int next_int = 1; 12 | for(int a: arr){ 13 | if(a == next_int) 14 | next_int++; 15 | else{ 16 | int gap = a - next_int; 17 | if(gap >= k) return next_int + k -1; 18 | k -= gap; 19 | next_int = a+1; 20 | } 21 | } 22 | return next_int + k -1; 23 | } 24 | }; 25 | 26 | 27 | 28 | Java: 29 | ----- 30 | class Solution { 31 | public int findKthPositive(int[] arr, int k) { 32 | int next_int = 1; 33 | for(int a: arr){ 34 | if(a == next_int) 35 | next_int++; 36 | else{ 37 | int gap = a - next_int; 38 | if(gap >= k) return next_int + k -1; 39 | k -= gap; 40 | next_int = a+1; 41 | } 42 | } 43 | return next_int + k -1; 44 | } 45 | } 46 | 47 | 48 | 49 | 50 | Python3: 51 | -------- 52 | class Solution: 53 | def findKthPositive(self, arr: List[int], k: int) -> int: 54 | next_int = 1 55 | for a in arr: 56 | if a == next_int: 57 | next_int += 1 58 | else: 59 | gap = a - next_int 60 | if gap >= k: return next_int + k -1 61 | k -= gap 62 | next_int = a+1 63 | return next_int + k -1 64 | 65 | 66 | -------------------------------------------------------------------------------- /279_Perfect_Squares: -------------------------------------------------------------------------------- 1 | Leetcode 279: Perfect Squares 2 | -------------------------------------- 3 | Detailed Explanation can be found here: https://youtu.be/dOOzOsfj31I 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int numSquares(int n) { 10 | vector dp(n+1, 0); 11 | for(int x = 1; x <= n; ++x){ 12 | int min_val = x; 13 | int y = 1, sq = 1; 14 | while(sq <= x){ 15 | min_val = min(min_val, 1 + dp[x-sq]); 16 | y++; 17 | sq = y*y; 18 | } 19 | dp[x] = min_val; 20 | } 21 | return dp[n]; 22 | } 23 | }; 24 | 25 | Java: 26 | ----- 27 | class Solution { 28 | public int numSquares(int n) { 29 | int[] dp = new int[n+1]; 30 | for(int x = 1; x <= n; ++x){ 31 | int min_val = x; 32 | int y = 1, sq = 1; 33 | while(sq <= x){ 34 | min_val = Math.min(min_val, 1 + dp[x-sq]); 35 | y++; 36 | sq = y*y; 37 | } 38 | dp[x] = min_val; 39 | } 40 | return dp[n]; 41 | } 42 | } 43 | 44 | Python3: 45 | -------- 46 | class Solution: 47 | def numSquares(self, n: int) -> int: 48 | dp = [0]*(n+1) 49 | for x in range(1, n+1): 50 | min_val = x; 51 | y, sq = 1, 1 52 | while sq <= x: 53 | min_val = min(min_val, 1 + dp[x-sq]) 54 | y += 1 55 | sq = y*y 56 | 57 | dp[x] = min_val 58 | 59 | return dp[n] 60 | 61 | 62 | ****** Please Subscribe Knowledge Center: http://youtube.com/c/KnowledgeCenter ******** 63 | -------------------------------------------------------------------------------- /394_decode_string: -------------------------------------------------------------------------------- 1 | Leetcode 394: Decode String 2 | Detailed video explanation: https://youtu.be/yaCRdWMq4A4 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | string decodeString(string& s, int& i) { 10 | string result; 11 | while(i < s.length() && s[i] != ']'){ 12 | if(isdigit(s[i])){ 13 | int k = 0; 14 | while(i < s.length() && isdigit(s[i])) 15 | k = k*10 + s[i++] - '0'; 16 | i++; 17 | string r = decodeString(s, i); 18 | while(k-- > 0) 19 | result += r; 20 | i++; 21 | } else 22 | result += s[i++]; 23 | } 24 | return result; 25 | } 26 | public: 27 | string decodeString(string s) { 28 | int i = 0; 29 | return decodeString(s, i); 30 | } 31 | }; 32 | 33 | 34 | 35 | Java: 36 | ----- 37 | class Solution { 38 | int i = 0; 39 | public String decodeString(String s) { 40 | StringBuilder result = new StringBuilder(); 41 | while(i < s.length() && s.charAt(i) != ']'){ 42 | if(Character.isDigit(s.charAt(i))){ 43 | int k = 0; 44 | while(i < s.length() && Character.isDigit(s.charAt(i))) 45 | k = k*10 + s.charAt(i++) - '0'; 46 | i++; 47 | String r = decodeString(s); 48 | while(k-- > 0) 49 | result.append(r); 50 | i++; 51 | } else 52 | result.append(s.charAt(i++)); 53 | } 54 | return result.toString(); 55 | } 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /520_Detect_Capital: -------------------------------------------------------------------------------- 1 | Leetcode 520: Detect Capital 2 | Detailed video explanation: https://youtu.be/qNJYp8aOpHQ 3 | ================================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool detectCapitalUse(string word) { 11 | if(word.length() < 2) return true; 12 | if(isupper(word[0]) && isupper(word[1])){ 13 | for(int i = 2; i < word.length(); ++i) 14 | if(islower(word[i])) return false; 15 | } else { 16 | for(int i = 1; i < word.length(); ++i) 17 | if(isupper(word[i])) return false; 18 | } 19 | return true; 20 | } 21 | }; 22 | 23 | 24 | Java: 25 | ----- 26 | class Solution { 27 | public boolean detectCapitalUse(String word) { 28 | if(word.length() < 2) return true; 29 | if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))){ 30 | for(int i = 2; i < word.length(); ++i) 31 | if(Character.isLowerCase(word.charAt(i))) return false; 32 | } else { 33 | for(int i = 1; i < word.length(); ++i) 34 | if(Character.isUpperCase(word.charAt(i))) return false; 35 | } 36 | return true; 37 | } 38 | } 39 | 40 | 41 | Python3: 42 | ------- 43 | class Solution: 44 | def detectCapitalUse(self, word: str) -> bool: 45 | if len(word) < 2: return True 46 | if word[0].isupper() and word[1].isupper(): 47 | for i in range(2, len(word)): 48 | if word[i].islower(): return False 49 | else: 50 | for i in range(1, len(word)): 51 | if word[i].isupper(): return False 52 | return True 53 | 54 | 55 | -------------------------------------------------------------------------------- /1153_String_Transforms_Into_Another_String: -------------------------------------------------------------------------------- 1 | Leetcode 1153: String Transforms Into Another String 2 | Detailed video explanation: https://youtu.be/BjJHV0rmfXY 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool canConvert(string str1, string str2) { 11 | if(str1 == str2) return true; 12 | unordered_map dp; 13 | for(int i = 0; i < str1.length(); ++i){ 14 | if(dp.count(str1[i]) && dp[str1[i]] != str2[i]) 15 | return false; 16 | dp[str1[i]] = str2[i]; 17 | } 18 | return set(str2.begin(), str2.end()).size() < 26; 19 | } 20 | }; 21 | 22 | 23 | 24 | Java: 25 | ----- 26 | class Solution { 27 | public boolean canConvert(String str1, String str2) { 28 | if(str1.equals(str2)) return true; 29 | Map dp = new HashMap(); 30 | for(int i = 0; i < str1.length(); ++i){ 31 | char c1 = str1.charAt(i), c2 = str2.charAt(i); 32 | if(dp.containsKey(str1.charAt(i)) && dp.get(str1.charAt(i)) != str2.charAt(i)) 33 | return false; 34 | dp.put(str1.charAt(i), str2.charAt(i)); 35 | } 36 | return new HashSet(dp.values()).size() < 26; 37 | } 38 | } 39 | 40 | 41 | 42 | Python3: 43 | -------- 44 | class Solution: 45 | def canConvert(self, str1: str, str2: str) -> bool: 46 | if str1 == str2: return True 47 | dp = {} 48 | for i in range(len(str1)): 49 | if str1[i] in dp and dp[str1[i]] != str2[i]: 50 | return False 51 | dp[str1[i]] = str2[i] 52 | 53 | return len(set(str2)) < 26 54 | 55 | 56 | -------------------------------------------------------------------------------- /125_valid_palindrome: -------------------------------------------------------------------------------- 1 | Leetcode 125: Valid Palindrome 2 | Detailed video explanation: https://youtu.be/028pTf2kBFI 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool isPalindrome(string s) { 11 | if(s.length() <= 1) return true; 12 | int st = 0, en = s.length()-1; 13 | while(st < en){ 14 | while(st < en && !isalnum(s[st])) st++; 15 | while(st < en && !isalnum(s[en])) en--; 16 | if(st < en && tolower(s[st]) != tolower(s[en])) return false; 17 | st++; 18 | en--; 19 | } 20 | return true; 21 | } 22 | }; 23 | 24 | 25 | Java: 26 | ---- 27 | class Solution { 28 | public boolean isPalindrome(String s) { 29 | if(s.length() <= 1) return true; 30 | int st = 0, en = s.length()-1; 31 | while(st < en){ 32 | while(st < en && !Character.isLetterOrDigit(s.charAt(st))) st++; 33 | while(st < en && !Character.isLetterOrDigit(s.charAt(en))) en--; 34 | if(st < en && Character.toLowerCase(s.charAt(st)) != Character.toLowerCase(s.charAt(en))) return false; 35 | st++; 36 | en--; 37 | } 38 | return true; 39 | } 40 | } 41 | 42 | 43 | Python3: 44 | -------- 45 | class Solution: 46 | def isPalindrome(self, s: str) -> bool: 47 | if len(s) <= 1: return True 48 | st, en = 0, len(s)-1 49 | while st < en: 50 | while st < en and not s[st].isalnum(): st += 1 51 | while st < en and not s[en].isalnum(): en -= 1 52 | if st < en and s[st].lower() != s[en].lower(): return False 53 | st, en = st+1, en-1 54 | return True 55 | 56 | -------------------------------------------------------------------------------- /1103_Distribute_Candies_to_People: -------------------------------------------------------------------------------- 1 | Leetcode 1103: Distribute Candies to People 2 | Detailed video explanation: https://youtu.be/bNllLSJgApM 3 | =================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector distributeCandies(int candies, int num_people) { 11 | vector result(num_people, 0); 12 | int idx = 0, candies_count = 1; 13 | while(candies){ 14 | result[idx++] += candies_count; 15 | candies -= candies_count++; 16 | if(idx == num_people) idx = 0; 17 | if(candies_count > candies) candies_count = candies; 18 | } 19 | return result; 20 | } 21 | }; 22 | 23 | 24 | Java: 25 | ----- 26 | class Solution { 27 | public int[] distributeCandies(int candies, int num_people) { 28 | int[] result = new int[num_people]; 29 | int idx = 0, candies_count = 1; 30 | while(candies > 0){ 31 | result[idx++] += candies_count; 32 | candies -= candies_count++; 33 | if(idx == num_people) idx = 0; 34 | if(candies_count > candies) candies_count = candies; 35 | } 36 | return result; 37 | } 38 | } 39 | 40 | 41 | Python3: 42 | ------- 43 | class Solution: 44 | def distributeCandies(self, candies: int, num_people: int) -> List[int]: 45 | result = [0]*num_people 46 | idx, candies_count = 0, 1 47 | while candies > 0: 48 | result[idx] += candies_count 49 | candies -= candies_count 50 | idx, candies_count = idx+1, candies_count+1 51 | if idx == num_people: idx = 0 52 | if candies_count > candies: candies_count = candies 53 | return result 54 | 55 | 56 | -------------------------------------------------------------------------------- /60_PermutationSequence: -------------------------------------------------------------------------------- 1 | // C++ : 60. Permutation Sequence 2 | 3 | class Solution { 4 | public: 5 | string getPermutation(int n, int k) { 6 | vector fact(n,1); 7 | vector digits(n,1); 8 | for(int i = 1; i < n; ++i){ 9 | fact[i] = (i+1)*fact[i-1]; 10 | digits[i] = i+1; 11 | } 12 | 13 | string result = ""; 14 | while(result.size() < n-1){ 15 | int repeat = fact[fact.size() - 2]; 16 | int next_digit = (k-1)/repeat; 17 | result += to_string(digits[next_digit]); 18 | fact.pop_back(); 19 | digits.erase(digits.begin() + next_digit); 20 | k = k % repeat; 21 | if(k == 0){ 22 | for (int i = digits.size()-1; i>=0; --i) 23 | result += to_string(digits[i]); 24 | } 25 | } 26 | if(result.size() < n){ 27 | result += to_string(digits[0]); 28 | } 29 | return result; 30 | } 31 | }; 32 | 33 | 34 | ## Python3 35 | 36 | class Solution: 37 | def getPermutation(self, n: int, k: int) -> str: 38 | fact, digits = [1]*n, [1]*n 39 | for i in range(1, n): 40 | fact[i] = (i+1)*fact[i-1] 41 | digits[i] = i+1 42 | 43 | result = '' 44 | while len(result) < n-1: 45 | repeat = fact[-2] 46 | next_digit = (k-1)//repeat 47 | result += str(digits[next_digit]) 48 | fact = fact[:-1] 49 | digits.pop(next_digit) 50 | k = k % repeat 51 | if k == 0: 52 | for i in range(len(digits)-1, -1, -1): 53 | result += str(digits[i]) 54 | 55 | if len(result) < n: result += str(digits[0]) 56 | return result 57 | -------------------------------------------------------------------------------- /67_Add Binary: -------------------------------------------------------------------------------- 1 | Leetcode 67 : Add Binary 2 | Detailed video explanation: https://youtu.be/SwPXgTiv8Ag 3 | ================================================== 4 | 5 | C++: 6 | class Solution { 7 | public: 8 | string addBinary(string a, string b) { 9 | string result; 10 | int i = a.length()-1, j = b.length()-1; 11 | int carry = 0; 12 | while(i >= 0 || j >= 0){ 13 | int sum = carry; 14 | if(i >= 0) sum += a[i--] - '0'; 15 | if(j >= 0) sum += b[j--] - '0'; 16 | carry = sum > 1 ? 1 : 0; 17 | result += to_string(sum%2); 18 | } 19 | if(carry) result += to_string(carry); 20 | reverse(result.begin(), result.end()); 21 | return result; 22 | } 23 | }; 24 | Java: 25 | public String addBinary(String a, String b) { 26 | StringBuilder result = new StringBuilder(); 27 | int i = a.length()-1, j = b.length()-1; 28 | int carry = 0; 29 | while(i >= 0 || j >= 0){ 30 | int sum = carry; 31 | if(i >= 0) sum += a.charAt(i--) - '0'; 32 | if(j >= 0) sum += b.charAt(j--) - '0'; 33 | carry = sum > 1 ? 1 : 0; 34 | result.append(sum%2); 35 | } 36 | if(carry != 0) result.append(carry); 37 | return result.reverse().toString(); 38 | } 39 | Python3: 40 | def addBinary(self, a: str, b: str) -> str: 41 | result = "" 42 | i, j, carry = len(a) - 1, len(b) - 1, 0 43 | while i >= 0 or j >= 0: 44 | sum = carry 45 | if i >= 0: sum += ord(a[i]) - ord('0') 46 | if j >= 0: sum += ord(b[j]) - ord('0') 47 | i, j = i-1, j-1 48 | carry = 1 if sum > 1 else 0 49 | result += str(sum%2) 50 | 51 | if carry != 0: result += str(carry) 52 | return result[::-1] 53 | 54 | -------------------------------------------------------------------------------- /134_Gas_Station: -------------------------------------------------------------------------------- 1 | Leetcode 134: Gas Station 2 | Detailed video Explanation: https://youtu.be/xmJZSYSvgfE 3 | ======================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int canCompleteCircuit(vector& gas, vector& cost) { 11 | int n = gas.size(); 12 | int total_surplus = 0; 13 | int surplus = 0; 14 | int S = 0; 15 | 16 | for(int i = 0; i < n; ++i){ 17 | total_surplus += gas[i] - cost[i]; 18 | surplus += gas[i] - cost[i]; 19 | if(surplus < 0){ 20 | surplus = 0; 21 | S = i+1; 22 | } 23 | } 24 | return (total_surplus < 0) ? -1 : S; 25 | } 26 | }; 27 | 28 | 29 | 30 | 31 | Java: 32 | ----- 33 | class Solution { 34 | public int canCompleteCircuit(int[] gas, int[] cost) { 35 | int n = gas.length; 36 | int total_surplus = 0; 37 | int surplus = 0; 38 | int S = 0; 39 | 40 | for(int i = 0; i < n; ++i){ 41 | total_surplus += gas[i] - cost[i]; 42 | surplus += gas[i] - cost[i]; 43 | if(surplus < 0){ 44 | surplus = 0; 45 | S = i+1; 46 | } 47 | } 48 | return (total_surplus < 0) ? -1 : S; 49 | } 50 | } 51 | 52 | 53 | 54 | 55 | Python3: 56 | -------- 57 | class Solution: 58 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 59 | n, total_surplus, surplus, S = len(gas), 0, 0, 0 60 | 61 | for i in range(n): 62 | total_surplus += gas[i] - cost[i] 63 | surplus += gas[i] - cost[i] 64 | if surplus < 0: 65 | surplus = 0 66 | S = i+1 67 | return -1 if (total_surplus < 0) else S 68 | 69 | 70 | -------------------------------------------------------------------------------- /287_Find_duplicate_number: -------------------------------------------------------------------------------- 1 | // Leetcode 287: Find the Duplicate Number 2 | // Detailed Explanation is available here: https://youtu.be/GOYMcrvg-Ck 3 | 4 | // C++ 5 | 6 | class Solution { 7 | public: 8 | int findDuplicate(vector& nums) { 9 | int n = nums.size(); 10 | int idx = 0; 11 | int curr_max = 0; 12 | for(int i = 0; i < n; ++i){ 13 | int id = nums[i] % n; 14 | nums[id] += n; 15 | } 16 | for(int i = 0; i < n; ++i){ 17 | if(nums[i] > curr_max){ 18 | curr_max = nums[i]; 19 | idx = i; 20 | } 21 | nums[i] %= n; 22 | } 23 | return idx; 24 | } 25 | }; 26 | 27 | // Java: 28 | class Solution { 29 | public int findDuplicate(int[] nums) { 30 | int n = nums.length; 31 | int idx = 0; 32 | int curr_max = 0; 33 | for(int i = 0; i < n; ++i){ 34 | int id = nums[i] % n; 35 | nums[id] += n; 36 | } 37 | for(int i = 0; i < n; ++i){ 38 | if(nums[i] > curr_max){ 39 | curr_max = nums[i]; 40 | idx = i; 41 | } 42 | nums[i] %= n; 43 | } 44 | return idx; 45 | } 46 | } 47 | 48 | # Python3: 49 | class Solution: 50 | def findDuplicate(self, nums: List[int]) -> int: 51 | n = len(nums) 52 | idx = 0 53 | curr_max = 0 54 | for i in range(n): 55 | id = nums[i] % n 56 | nums[id] += n 57 | 58 | for i in range(n): 59 | if nums[i] > curr_max: 60 | curr_max = nums[i] 61 | idx = i 62 | nums[i] %= n 63 | 64 | return idx 65 | 66 | ***** Please LIKE, SHARE and SUBSCRIBE Knowledge Center channel: https://www.youtube.com/c/KnowledgeCenter ****** 67 | -------------------------------------------------------------------------------- /797_All_Paths_From_Source_to_Target: -------------------------------------------------------------------------------- 1 | Leetcode 797: All Paths From Source to Target 2 | Detailed video explanation: https://youtu.be/SZ3zpzQk2jg 3 | ======================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | void dfs(vector>& graph, vector>& result, vector& path, int u){ 9 | path.push_back(u); 10 | if(u == graph.size()-1) result.push_back(path); 11 | else 12 | for(int v: graph[u]) dfs(graph, result, path, v); 13 | path.pop_back(); 14 | } 15 | public: 16 | vector> allPathsSourceTarget(vector>& graph) { 17 | vector> result; 18 | vector path; 19 | dfs(graph, result, path, 0); 20 | return result; 21 | } 22 | }; 23 | 24 | Java: 25 | ----- 26 | class Solution { 27 | private void dfs(int[][] graph, List> result, List path, int u){ 28 | path.add(u); 29 | if(u == graph.length-1) result.add(new ArrayList(path)); 30 | else 31 | for(int v: graph[u]) dfs(graph, result, path, v); 32 | path.remove(path.size()-1); 33 | } 34 | 35 | public List> allPathsSourceTarget(int[][] graph) { 36 | List> result = new ArrayList(); 37 | List path = new ArrayList(); 38 | dfs(graph, result, path, 0); 39 | return result; 40 | } 41 | } 42 | 43 | Python3: 44 | -------- 45 | class Solution: 46 | def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 47 | result = [] 48 | 49 | def dfs(path, u): 50 | if u == len(graph)-1: result.append(path + [u]) 51 | else: 52 | for v in graph[u]: dfs(path + [u], v) 53 | 54 | dfs([], 0) 55 | return result 56 | 57 | 58 | -------------------------------------------------------------------------------- /409_Longest_Palindrome: -------------------------------------------------------------------------------- 1 | Leetcode 409: Longest Palindrome 2 | Detailed video Explanation: https://youtu.be/J_Di2LmeLBQ 3 | ================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int longestPalindrome(string s) { 11 | unordered_map counts; 12 | for(char c: s) counts[c]++; 13 | 14 | int result = 0; 15 | bool odd_found = false; 16 | for(auto& c: counts){ 17 | if(c.second % 2 == 0) result += c.second; 18 | else{ 19 | odd_found = true; 20 | result += c.second - 1; 21 | } 22 | } 23 | if(odd_found) result++; 24 | return result; 25 | } 26 | }; 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public int longestPalindrome(String s) { 33 | Map counts = new HashMap(); 34 | for(char c: s.toCharArray()) 35 | counts.put(c, counts.getOrDefault(c, 0) + 1); 36 | 37 | int result = 0; 38 | boolean odd_found = false; 39 | for(int c: counts.values()){ 40 | if(c % 2 == 0) result += c; 41 | else{ 42 | odd_found = true; 43 | result += c - 1; 44 | } 45 | } 46 | if(odd_found) result++; 47 | return result; 48 | } 49 | } 50 | 51 | 52 | Python3: 53 | -------- 54 | class Solution: 55 | def longestPalindrome(self, s: str) -> int: 56 | counts = {} 57 | for c in s: counts[c] = counts.get(c, 0) + 1 58 | 59 | result, odd_found = 0, False 60 | for _, c in counts.items(): 61 | if c % 2 == 0: result += c 62 | else: 63 | odd_found = True 64 | result += c - 1 65 | if odd_found: result += 1 66 | return result 67 | 68 | -------------------------------------------------------------------------------- /437_Path_Sum_iii: -------------------------------------------------------------------------------- 1 | Leetcode 437: Path Sum III 2 | Detailed video explanation: https://youtu.be/Vam9gldRapY 3 | ============================================ 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | int pathSum_a(TreeNode* root, int sum){ 9 | if(root == nullptr) return 0; 10 | int res = 0; 11 | if(root->val == sum) res++; 12 | res += pathSum_a(root->left, sum-root->val); 13 | res += pathSum_a(root->right, sum-root->val); 14 | return res; 15 | } 16 | public: 17 | int pathSum(TreeNode* root, int sum) { 18 | if(root == nullptr) return 0; 19 | return pathSum(root->left, sum) + pathSum_a(root, sum) + pathSum(root->right, sum); 20 | } 21 | }; 22 | 23 | 24 | Java: 25 | ---- 26 | class Solution { 27 | private int pathSum_a(TreeNode root, int sum){ 28 | if(root == null) return 0; 29 | int res = 0; 30 | if(root.val == sum) res++; 31 | res += pathSum_a(root.left, sum-root.val); 32 | res += pathSum_a(root.right, sum-root.val); 33 | return res; 34 | } 35 | public int pathSum(TreeNode root, int sum) { 36 | if(root == null) return 0; 37 | return pathSum(root.left, sum) + pathSum_a(root, sum) + pathSum(root.right, sum); 38 | } 39 | } 40 | 41 | 42 | Python3: 43 | ------- 44 | class Solution: 45 | def pathSum(self, root: TreeNode, sum: int) -> int: 46 | 47 | def pathSum_a(root, sum): 48 | if root == None: return 0 49 | res = 0 50 | if root.val == sum: res += 1 51 | res += pathSum_a(root.left, sum-root.val); 52 | res += pathSum_a(root.right, sum-root.val); 53 | return res 54 | 55 | if root == None: return 0 56 | return self.pathSum(root.left, sum) + pathSum_a(root, sum) + self.pathSum(root.right, sum) 57 | 58 | 59 | -------------------------------------------------------------------------------- /1291_Sequential_Digits: -------------------------------------------------------------------------------- 1 | Leetcode 1291: Sequential Digits 2 | Detailed video explanation: https://youtu.be/sFt3KVGyeWw 3 | =========================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector sequentialDigits(int low, int high) { 11 | string digits = "123456789"; 12 | vector result; 13 | int nl = to_string(low).length(); 14 | int nh = to_string(high).length(); 15 | 16 | for(int i = nl; i <= nh; ++i){ 17 | for(int j = 0; j < 10-i; ++j){ 18 | int num = stoi(digits.substr(j, i)); 19 | if(num >= low && num <= high) result.push_back(num); 20 | } 21 | } 22 | return result; 23 | } 24 | }; 25 | 26 | 27 | 28 | Java: 29 | ----- 30 | class Solution { 31 | public List sequentialDigits(int low, int high) { 32 | String digits = "123456789"; 33 | List result = new ArrayList(); 34 | int nl = String.valueOf(low).length(); 35 | int nh = String.valueOf(high).length(); 36 | 37 | for(int i = nl; i <= nh; ++i){ 38 | for(int j = 0; j < 10-i; ++j){ 39 | int num = Integer.parseInt(digits.substring(j, j+i)); 40 | if(num >= low && num <= high) result.add(num); 41 | } 42 | } 43 | return result; 44 | } 45 | } 46 | 47 | 48 | 49 | 50 | Python3: 51 | -------- 52 | class Solution: 53 | def sequentialDigits(self, low: int, high: int) -> List[int]: 54 | digits = "123456789" 55 | result = [] 56 | nl, nh = len(str(low)), len(str(high)) 57 | 58 | for i in range(nl, nh+1): 59 | for j in range(0, 10-i): 60 | num = int(digits[j: j+i]) 61 | if num >= low and num <= high: result.append(num) 62 | return result 63 | 64 | -------------------------------------------------------------------------------- /264_Ugly_Number_2: -------------------------------------------------------------------------------- 1 | LeetCode 264: Ugly Number II 2 | Detailed video Explanation is here: https://youtu.be/kSDI_iOiGQY 3 | 4 | C++: 5 | ---- 6 | int nthUglyNumber(int n) { 7 | int ugly[n]; 8 | ugly[0] = 1; 9 | int count = 1; 10 | int idx2 = 0, idx3 = 0, idx5 = 0; 11 | while(count < n){ 12 | int val2 = ugly[idx2]*2; 13 | int val3 = ugly[idx3]*3; 14 | int val5 = ugly[idx5]*5; 15 | int val = min({val2, val3, val5}); 16 | if(val == val2) idx2++; 17 | if(val == val3) idx3++; 18 | if(val == val5) idx5++; 19 | ugly[count++] = val; 20 | } 21 | return ugly[n-1]; 22 | } 23 | 24 | 25 | Java: 26 | ----- 27 | public int nthUglyNumber(int n) { 28 | int ugly[] = new int[n]; 29 | ugly[0] = 1; 30 | int count = 1; 31 | int idx2 = 0, idx3 = 0, idx5 = 0; 32 | while(count < n){ 33 | int val2 = ugly[idx2]*2; 34 | int val3 = ugly[idx3]*3; 35 | int val5 = ugly[idx5]*5; 36 | int val = Math.min(val2, Math.min(val3, val5)); 37 | if(val == val2) idx2++; 38 | if(val == val3) idx3++; 39 | if(val == val5) idx5++; 40 | ugly[count++] = val; 41 | } 42 | return ugly[n-1]; 43 | } 44 | 45 | 46 | Python3: 47 | ------- 48 | def nthUglyNumber(self, n: int) -> int: 49 | ugly = [1]*n 50 | count = 1 51 | idx2, idx3, idx5 = 0, 0, 0 52 | while count < n: 53 | val2 = ugly[idx2]*2 54 | val3 = ugly[idx3]*3 55 | val5 = ugly[idx5]*5 56 | val = min(val2, val3, val5) 57 | if val == val2: idx2 += 1 58 | if val == val3: idx3 += 1 59 | if val == val5: idx5 += 1 60 | ugly[count] = val 61 | count += 1 62 | 63 | return ugly[n-1] 64 | 65 | 66 | -------------------------------------------------------------------------------- /665_Non_decreasing_Array: -------------------------------------------------------------------------------- 1 | Leetcode 665: Non-decreasing Array 2 | Detailed video explanation: https://youtu.be/KNeYi11859M 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool checkPossibility(vector& nums) { 11 | int n = nums.size(); 12 | if(n == 1) return true; 13 | int idx = 0; 14 | for(int i = 1; i < n; ++i){ 15 | if(nums[i] < nums[i-1]){ 16 | if(idx != 0) return false; 17 | idx = i; 18 | } 19 | } 20 | if(idx == 0 || idx == 1 || idx == n-1) return true; 21 | if((nums[idx-1] > nums[idx+1]) && (nums[idx-2] > nums[idx])) return false; 22 | return true; 23 | } 24 | }; 25 | 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public boolean checkPossibility(int[] nums) { 33 | int n = nums.length; 34 | if(n == 1) return true; 35 | int idx = 0; 36 | for(int i = 1; i < n; ++i){ 37 | if(nums[i] < nums[i-1]){ 38 | if(idx != 0) return false; 39 | idx = i; 40 | } 41 | } 42 | if(idx == 0 || idx == 1 || idx == n-1) return true; 43 | if((nums[idx-1] > nums[idx+1]) && (nums[idx-2] > nums[idx])) return false; 44 | return true; 45 | } 46 | } 47 | 48 | 49 | 50 | 51 | Python3: 52 | ------- 53 | class Solution: 54 | def checkPossibility(self, nums: List[int]) -> bool: 55 | n, idx = len(nums), 0 56 | if n == 1: return True 57 | for i in range(1, n): 58 | if nums[i] < nums[i-1]: 59 | if idx != 0: return False 60 | idx = i 61 | if (idx == 0 or idx == 1 or idx == n-1): return True 62 | if ((nums[idx-1] > nums[idx+1]) and (nums[idx-2] > nums[idx])): return False 63 | return True 64 | 65 | 66 | -------------------------------------------------------------------------------- /228_Summary_Ranges: -------------------------------------------------------------------------------- 1 | Leetcode 228: Summary Ranges 2 | Detailed video explanation: https://youtu.be/AjE4x3Yh9xc 3 | ======================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector summaryRanges(vector& nums) { 11 | vector result; 12 | int n = nums.size(); 13 | if(n == 0) return result; 14 | int a = nums[0]; 15 | for(int i = 0; i < n; ++i){ 16 | if(i == n-1 || nums[i]+1 != nums[i+1]){ 17 | if(nums[i] != a) result.push_back(to_string(a) + "->" + to_string(nums[i])); 18 | else result.push_back(to_string(a)); 19 | if(i != n-1) a = nums[i+1]; 20 | } 21 | } 22 | return result; 23 | } 24 | }; 25 | 26 | 27 | 28 | Java: 29 | ----- 30 | class Solution { 31 | public List summaryRanges(int[] nums) { 32 | List result = new ArrayList(); 33 | int n = nums.length; 34 | if(n == 0) return result; 35 | int a = nums[0]; 36 | for(int i = 0; i < n; ++i){ 37 | if(i == n-1 || nums[i]+1 != nums[i+1]){ 38 | if(nums[i] != a) result.add(a + "->" + nums[i]); 39 | else result.add(a + ""); 40 | if(i != n-1) a = nums[i+1]; 41 | } 42 | } 43 | return result; 44 | } 45 | } 46 | 47 | 48 | 49 | Python3: 50 | ------- 51 | class Solution: 52 | def summaryRanges(self, nums: List[int]) -> List[str]: 53 | result, n = [], len(nums) 54 | if n == 0: return result 55 | a = nums[0] 56 | for i in range(n): 57 | if i == n-1 or nums[i]+1 != nums[i+1]: 58 | if nums[i] != a: result.append(str(a) + "->" + str(nums[i])) 59 | else: result.append(str(a)) 60 | if i != n-1: a = nums[i+1] 61 | 62 | return result 63 | -------------------------------------------------------------------------------- /104_Maximum_Depth_of_Binary_Tree: -------------------------------------------------------------------------------- 1 | Leetcode 104: Maximum Depth of Binary Tree 2 | Detailed video Explanation: https://youtu.be/UDifXyZp0dQ 3 | ============================================= 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int maxDepth(TreeNode* root) { 22 | if(!root) return 0; 23 | return 1 + max(maxDepth(root->left), maxDepth(root->right)); 24 | } 25 | }; 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | /** 32 | * Definition for a binary tree node. 33 | * public class TreeNode { 34 | * int val; 35 | * TreeNode left; 36 | * TreeNode right; 37 | * TreeNode() {} 38 | * TreeNode(int val) { this.val = val; } 39 | * TreeNode(int val, TreeNode left, TreeNode right) { 40 | * this.val = val; 41 | * this.left = left; 42 | * this.right = right; 43 | * } 44 | * } 45 | */ 46 | class Solution { 47 | public int maxDepth(TreeNode root) { 48 | if(root == null) return 0; 49 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 50 | } 51 | } 52 | 53 | 54 | 55 | Python3: 56 | -------- 57 | # Definition for a binary tree node. 58 | # class TreeNode: 59 | # def __init__(self, val=0, left=None, right=None): 60 | # self.val = val 61 | # self.left = left 62 | # self.right = right 63 | class Solution: 64 | def maxDepth(self, root: TreeNode) -> int: 65 | if root == None: return 0 66 | return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 67 | 68 | 69 | -------------------------------------------------------------------------------- /824_Goat_Latin: -------------------------------------------------------------------------------- 1 | Leetcode 824: Goat Latin 2 | Detailed video Explanation: https://youtu.be/4EC9U8lvWB8 3 | ====================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | string toGoatLatin(string S) { 11 | stringstream ss(S); 12 | string result, word, suffix; 13 | unordered_set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 14 | 15 | while(ss >> word){ 16 | suffix += 'a'; 17 | if(vowels.find(word[0]) == vowels.end()) 18 | word = word.substr(1) + word[0]; 19 | result += word + "ma" + suffix + ' '; 20 | } 21 | result.pop_back(); 22 | return result; 23 | } 24 | }; 25 | 26 | 27 | Java: 28 | ---- 29 | class Solution { 30 | public String toGoatLatin(String S) { 31 | StringBuilder sb = new StringBuilder(); 32 | String suffix = ""; 33 | Character[] vowelsarr = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 34 | Set vowels = new HashSet(Arrays.asList(vowelsarr)); 35 | 36 | for(String word: S.split(" ")){ 37 | suffix += 'a'; 38 | if(!vowels.contains(word.charAt(0))) 39 | word = word.substring(1) + word.charAt(0); 40 | sb.append(word).append("ma").append(suffix).append(' '); 41 | } 42 | sb.deleteCharAt(sb.length()-1); 43 | return sb.toString(); 44 | } 45 | } 46 | 47 | 48 | Python3: 49 | ------- 50 | class Solution: 51 | def toGoatLatin(self, S: str) -> str: 52 | vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} 53 | result, suffix = "", "" 54 | for word in S.split(): 55 | suffix += 'a' 56 | if not word[0] in vowels: 57 | word = word[1:] + word[0] 58 | result += word + "ma" + suffix + ' ' 59 | return result[:-1] 60 | 61 | 62 | -------------------------------------------------------------------------------- /983_Minimum_Cost_For_Tickets: -------------------------------------------------------------------------------- 1 | Leetcode 983: Minimum Cost For Tickets 2 | Detailed video explanation: https://youtu.be/HyN5hdD1JU4 3 | =========================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int mincostTickets(vector& days, vector& costs) { 11 | int n = days.size(); 12 | vector dp(n+1, 365*costs[0]); 13 | dp[n] = 0; 14 | 15 | for(int i = n-1; i >= 0; --i){ 16 | int d7 = i, d30 = i; 17 | while(d7 < n && days[d7] < days[i] + 7) ++d7; 18 | while(d30 < n && days[d30] < days[i] + 30) ++d30; 19 | dp[i] = min({costs[0] + dp[i+1], costs[1] + dp[d7], costs[2] + dp[d30]}); 20 | } 21 | return dp[0]; 22 | } 23 | }; 24 | 25 | 26 | Java: 27 | ---- 28 | class Solution { 29 | public int mincostTickets(int[] days, int[] costs) { 30 | int n = days.length; 31 | int[] dp = new int[n+1]; 32 | for(int i = 0; i < n; ++i) dp[i] = 365*costs[0]; 33 | 34 | for(int i = n-1; i >= 0; --i){ 35 | int d7 = i, d30 = i; 36 | while(d7 < n && days[d7] < days[i] + 7) ++d7; 37 | while(d30 < n && days[d30] < days[i] + 30) ++d30; 38 | dp[i] = Math.min(costs[0] + dp[i+1], Math.min(costs[1] + dp[d7], costs[2] + dp[d30])); 39 | } 40 | return dp[0]; 41 | } 42 | } 43 | 44 | 45 | Python3: 46 | -------- 47 | class Solution: 48 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 49 | n = len(days) 50 | dp = [365*costs[0]] * (n+1) 51 | dp[n] = 0 52 | 53 | for i in range(n-1, -1, -1): 54 | d7, d30 = i, i 55 | while d7 < n and days[d7] < days[i] + 7: d7 += 1 56 | while d30 < n and days[d30] < days[i] + 30: d30 += 1 57 | dp[i] = min(costs[0] + dp[i+1], costs[1] + dp[d7], costs[2] + dp[d30]) 58 | 59 | return dp[0] 60 | 61 | -------------------------------------------------------------------------------- /621_Task_Scheduler: -------------------------------------------------------------------------------- 1 | Leetcode 621: Task Scheduler 2 | Detailed video explanation: https://youtu.be/tGw5GbDekTU 3 | ============================================ 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int leastInterval(vector& tasks, int n) { 10 | unordered_map counts; 11 | for(char t: tasks) 12 | counts[t]++; 13 | priority_queue pq; 14 | for(auto c: counts) 15 | pq.push(c.second); 16 | 17 | int result = 0; 18 | while(!pq.empty()){ 19 | int time = 0; 20 | vector tmp; 21 | for(int i = 0; i < n+1; ++i){ 22 | if(!pq.empty()){ 23 | tmp.push_back(pq.top() - 1); 24 | pq.pop(); 25 | time++; 26 | } 27 | } 28 | for(auto t: tmp) 29 | if(t) pq.push(t); 30 | result += pq.empty() ? time : n+1; 31 | } 32 | return result; 33 | } 34 | }; 35 | 36 | 37 | Java: 38 | ---- 39 | class Solution { 40 | public int leastInterval(char[] tasks, int n) { 41 | Map counts = new HashMap(); 42 | for(char t: tasks) 43 | counts.put(t, counts.getOrDefault(t, 0) + 1); 44 | PriorityQueue pq = new PriorityQueue(counts.size(), Collections.reverseOrder()); 45 | pq.addAll(counts.values()); 46 | 47 | int result = 0; 48 | while(!pq.isEmpty()){ 49 | int time = 0; 50 | List tmp = new ArrayList(); 51 | for(int i = 0; i < n+1; ++i){ 52 | if(!pq.isEmpty()){ 53 | tmp.add(pq.remove() - 1); 54 | time++; 55 | } 56 | } 57 | for(int t: tmp) 58 | if(t > 0) pq.add(t); 59 | result += pq.isEmpty() ? time : n+1; 60 | } 61 | return result; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /203_Remove_Linked_list_Elements: -------------------------------------------------------------------------------- 1 | Leetcode 203: Remove Linked List Elements 2 | Detailed video explanation: https://youtu.be/YIng7Pf6oa4 3 | ============================================== 4 | 5 | C++: 6 | ==== 7 | Iterative: 8 | ---------- 9 | ListNode* removeElements(ListNode* head, int val) { 10 | if(!head) return head; 11 | ListNode *prev = nullptr, *curr = head; 12 | while(curr){ 13 | if(curr->val == val){ 14 | if(!prev) 15 | head = curr->next; 16 | else 17 | prev->next = curr->next; 18 | }else 19 | prev = curr; 20 | curr = curr->next; 21 | } 22 | return head; 23 | } 24 | 25 | Recursive: 26 | --------- 27 | ListNode* removeElements(ListNode* head, int val) { 28 | if(!head) return head; 29 | ListNode * h = removeElements(head->next, val); 30 | if(head->val == val) return h; 31 | head->next = h; 32 | return head; 33 | } 34 | 35 | 36 | Java: 37 | ==== 38 | public ListNode removeElements(ListNode head, int val) { 39 | if(head == null) return head; 40 | ListNode prev = null, curr = head; 41 | while(curr != null){ 42 | if(curr.val == val){ 43 | if(prev == null) 44 | head = curr.next; 45 | else 46 | prev.next = curr.next; 47 | }else 48 | prev = curr; 49 | curr = curr.next; 50 | } 51 | return head; 52 | } 53 | 54 | 55 | Python3: 56 | ======= 57 | def removeElements(self, head: ListNode, val: int) -> ListNode: 58 | if head == None: return head 59 | prev, curr = None, head 60 | while curr != None: 61 | if curr.val == val: 62 | if prev == None: head = curr.next 63 | else: prev.next = curr.next 64 | else:prev = curr 65 | curr = curr.next 66 | return head 67 | 68 | -------------------------------------------------------------------------------- /1290_Convert_Binary_Number_in_a_Linked_List_to_Integer: -------------------------------------------------------------------------------- 1 | Leetcode 1290: Convert Binary Number in a Linked List to Integer 2 | Detailed video explanation: https://youtu.be/CyxbuJwA-0g 3 | ========================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | int getDecimalValue(ListNode* head) { 21 | int result = head->val; 22 | while(head->next){ 23 | result = result*2 + head->next->val; 24 | head = head->next;; 25 | } 26 | return result; 27 | } 28 | }; 29 | 30 | 31 | 32 | Java: 33 | ----- 34 | /** 35 | * Definition for singly-linked list. 36 | * public class ListNode { 37 | * int val; 38 | * ListNode next; 39 | * ListNode() {} 40 | * ListNode(int val) { this.val = val; } 41 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 42 | * } 43 | */ 44 | class Solution { 45 | public int getDecimalValue(ListNode head) { 46 | int result = head.val; 47 | while(head.next != null){ 48 | result = result*2 + head.next.val; 49 | head = head.next;; 50 | } 51 | return result; 52 | } 53 | } 54 | 55 | 56 | 57 | Python3: 58 | -------- 59 | # Definition for singly-linked list. 60 | # class ListNode: 61 | # def __init__(self, val=0, next=None): 62 | # self.val = val 63 | # self.next = next 64 | class Solution: 65 | def getDecimalValue(self, head: ListNode) -> int: 66 | result = head.val 67 | while head.next != None: 68 | result = result*2 + head.next.val 69 | head = head.next 70 | 71 | return result 72 | 73 | 74 | -------------------------------------------------------------------------------- /395 Longest Substring with At Least K Repeating Characters: -------------------------------------------------------------------------------- 1 | Leetcode 395: Longest Substring with At Least K Repeating Characters 2 | Detailed Video Explanation: https://youtu.be/bHZkCAcj3dc 3 | =================================================================== 4 | 5 | C++: 6 | ---- 7 | int longestSubstring(string s, int k) { 8 | int n = s.length(); 9 | if(n == 0 || n < k) return 0; 10 | if(k <= 1) return n; 11 | 12 | unordered_map counts; 13 | for(char c: s) counts[c] += 1; 14 | 15 | int l = 0; 16 | while(l < n && counts[s[l]] >= k) l++; 17 | if(l >= n-1) return l; 18 | 19 | int ls1 = longestSubstring(s.substr(0, l), k); 20 | while(l < n && counts[s[l]] < k) l++; 21 | int ls2 = (l < n) ? longestSubstring(s.substr(l), k) : 0; 22 | return max(ls1, ls2); 23 | } 24 | 25 | 26 | Java: 27 | ----- 28 | public int longestSubstring(String s, int k) { 29 | int n = s.length(); 30 | if(n == 0 || n < k) return 0; 31 | if(k <= 1) return n; 32 | 33 | Map counts = new HashMap(); 34 | for(char c: s.toCharArray()) 35 | counts.put(c, counts.getOrDefault(c, 0) + 1); 36 | 37 | int l = 0; 38 | while(l < n && counts.get(s.charAt(l)) >= k) l++; 39 | if(l >= n-1) return l; 40 | 41 | int ls1 = longestSubstring(s.substring(0, l), k); 42 | while(l < n && counts.get(s.charAt(l)) < k) l++; 43 | int ls2 = (l < n) ? longestSubstring(s.substring(l), k) : 0; 44 | return Math.max(ls1, ls2); 45 | } 46 | 47 | 48 | Python3: 49 | ------- 50 | def longestSubstring(self, s: str, k: int) -> int: 51 | n = len(s) 52 | if n == 0 or n < k: return 0 53 | if k <= 1: return n 54 | 55 | counts = Counter(s) 56 | 57 | l = 0 58 | while l < n and counts[s[l]] >= k: l += 1 59 | if l >= n-1: return l 60 | 61 | ls1 = self.longestSubstring(s[0:l], k) 62 | while l < n and counts[s[l]] < k: l += 1 63 | ls2 = self.longestSubstring(s[l:], k) if l>= 1; 14 | } 15 | return result; 16 | } 17 | 18 | Method 2: 19 | -------- 20 | uint32_t reverseBits(uint32_t n) { 21 | n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16); 22 | n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); 23 | n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4); 24 | n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2); 25 | n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); 26 | return n; 27 | } 28 | 29 | 30 | Java: 31 | ===== 32 | Method 1: 33 | --------- 34 | public int reverseBits(int n) { 35 | int result = 0; 36 | for(int i = 0; i < 32; ++i){ 37 | result <<= 1; 38 | if ((n&1) > 0) result++; 39 | n >>= 1; 40 | } 41 | return result; 42 | 43 | Method 2: 44 | -------- 45 | public int reverseBits(int n) { 46 | return Integer.reverse(n); 47 | } 48 | 49 | 50 | Python3: 51 | ======== 52 | Method 1: 53 | -------- 54 | def reverseBits(self, n: int) -> int: 55 | result = 0 56 | for i in range(32): 57 | result <<= 1 58 | if n&1: result += 1 59 | n >>= 1 60 | return result 61 | 62 | Method 2: 63 | -------- 64 | def reverseBits(self, n: int) -> int: 65 | n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16) 66 | n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8) 67 | n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4) 68 | n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2) 69 | n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1) 70 | return n 71 | 72 | 73 | -------------------------------------------------------------------------------- /270_Closest_BST_Value: -------------------------------------------------------------------------------- 1 | Leetcode 270: Closest Binary Search Tree Value 2 | Detailed video explanation: https://youtu.be/lIKZB_rhFNM 3 | ================================================= 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int closestValue(TreeNode* root, double target) { 10 | if(root->val > target && root->left) { 11 | int l = closestValue(root->left, target); 12 | if(abs(l-target) < abs(root->val-target)) return l; 13 | return root->val; 14 | } 15 | if(root->val < target && root->right) { 16 | int r = closestValue(root->right, target); 17 | if(abs(r-target) < abs(root->val-target)) return r; 18 | return root->val; 19 | } 20 | return root->val; 21 | } 22 | }; 23 | 24 | 25 | Java: 26 | ---- 27 | class Solution { 28 | public int closestValue(TreeNode root, double target) { 29 | if(root.val > target && root.left != null) { 30 | int l = closestValue(root.left, target); 31 | if(Math.abs(l-target) < Math.abs(root.val-target)) return l; 32 | return root.val; 33 | } 34 | if(root.val < target && root.right != null) { 35 | int r = closestValue(root.right, target); 36 | if(Math.abs(r-target) < Math.abs(root.val-target)) return r; 37 | return root.val; 38 | } 39 | return root.val; 40 | } 41 | } 42 | 43 | 44 | Python3: 45 | ------- 46 | class Solution: 47 | def closestValue(self, root: TreeNode, target: float) -> int: 48 | if root.val > target and root.left != None: 49 | l = self.closestValue(root.left, target) 50 | if abs(l-target) < abs(root.val-target): return l 51 | return root.val 52 | if root.val < target and root.right != None: 53 | r = self.closestValue(root.right, target) 54 | if abs(r-target) < abs(root.val-target): return r 55 | return root.val 56 | return root.val 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /915_Partition_Array_into_Disjoint_Intervals: -------------------------------------------------------------------------------- 1 | Leetcode 915 : Partition Array into Disjoint Intervals 2 | Detailed video explanation : https://youtu.be/LvS4FcrGnD8 3 | ======================================================== 4 | 5 | 6 | C++: 7 | ----- 8 | class Solution { 9 | public: 10 | int partitionDisjoint(vector& nums) { 11 | int n = nums.size(); 12 | vector min_arr(n, nums[n-1]); 13 | vector max_arr(n, nums[0]); 14 | for(int i = 1; i < n; ++i){ 15 | max_arr[i] = max(max_arr[i-1], nums[i]); 16 | min_arr[n-1-i] = min(min_arr[n-i], nums[n-1-i]); 17 | } 18 | 19 | for(int i = 0; i < n; ++i){ 20 | if(max_arr[i] <= min_arr[i+1]) 21 | return i+1; 22 | } 23 | return 0; 24 | } 25 | }; 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public int partitionDisjoint(int[] nums) { 33 | int n = nums.length; 34 | int[] min_arr = new int[n]; 35 | min_arr[n-1] = nums[n-1]; 36 | int[] max_arr = new int[n]; 37 | max_arr[0] = nums[0]; 38 | for(int i = 1; i < n; ++i){ 39 | max_arr[i] = Math.max(max_arr[i-1], nums[i]); 40 | min_arr[n-1-i] = Math.min(min_arr[n-i], nums[n-1-i]); 41 | } 42 | 43 | for(int i = 0; i < n; ++i){ 44 | if(max_arr[i] <= min_arr[i+1]) 45 | return i+1; 46 | } 47 | return 0; 48 | } 49 | } 50 | 51 | 52 | 53 | 54 | Python3: 55 | -------- 56 | class Solution: 57 | def partitionDisjoint(self, nums: List[int]) -> int: 58 | n = len(nums) 59 | min_arr = [nums[n-1]]*n 60 | max_arr = [nums[0]]*n 61 | 62 | for i in range(1, n): 63 | max_arr[i] = max(max_arr[i-1], nums[i]) 64 | min_arr[n-1-i] = min(min_arr[n-i], nums[n-1-i]) 65 | 66 | for i in range(n): 67 | if max_arr[i] <= min_arr[i+1]: 68 | return i+1 69 | 70 | return 0 71 | 72 | -------------------------------------------------------------------------------- /253_Meeting_Rooms_II: -------------------------------------------------------------------------------- 1 | Leetcode 253 : Meeting Rooms II 2 | 3 | -------------------------------------- 4 | 5 | Description 6 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.) 7 | 8 | (0,8),(8,10) is not conflict at 8 9 | 10 | Example 11 | Example1 12 | 13 | Input: intervals = [(0,30),(5,10),(15,20)] 14 | Output: 2 15 | Explanation: 16 | We need two meeting rooms 17 | room1: (0,30) 18 | room2: (5,10),(15,20) 19 | Example2 20 | 21 | Input: intervals = [(2,7)] 22 | Output: 1 23 | Explanation: 24 | Only need one meeting room 25 | 26 | ----------------- 27 | 28 | Solution: 29 | 30 | C++: 31 | ---- 32 | /** 33 | * Definition of Interval: 34 | * class Interval { 35 | * public: 36 | * int start, end; 37 | * Interval(int start, int end) { 38 | * this->start = start; 39 | * this->end = end; 40 | * } 41 | * } 42 | */ 43 | 44 | class Solution { 45 | public: 46 | /** 47 | * @param intervals: an array of meeting time intervals 48 | * @return: the minimum number of conference rooms required 49 | */ 50 | int minMeetingRooms(vector &intervals) { 51 | // Write your code here 52 | // your code will replace this placeholder return statement 53 | int n = intervals.size(); 54 | vector start, end; 55 | for(auto it: intervals){ 56 | start.push_back(it.start); 57 | end.push_back(it.end); 58 | } 59 | sort(start.begin(), start.end()); 60 | sort(end.begin(), end.end()); 61 | int active_rooms = 0, max_rooms = 0; 62 | int i = 0, j = 0; 63 | while(i < n && j < n){ 64 | if(start[i] < end[j]){ 65 | active_rooms++; 66 | i++; 67 | } else{ 68 | active_rooms--; 69 | j++; 70 | } 71 | max_rooms = max(max_rooms, active_rooms); 72 | } 73 | 74 | return max_rooms; 75 | } 76 | }; 77 | -------------------------------------------------------------------------------- /152_Maximum_Product_Subarray: -------------------------------------------------------------------------------- 1 | Leetcode 152: Maximum Product Subarray 2 | Detailed video Explanation: https://youtu.be/hJ_Uy2DzE08 3 | ========================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int maxProduct(vector& nums) { 11 | int max_overall = nums[0]; 12 | int max_ending_here = nums[0], min_ending_here = nums[0]; 13 | 14 | for(int i = 1; i < nums.size(); ++i){ 15 | int tmp = max_ending_here; 16 | max_ending_here = max({nums[i], nums[i]*max_ending_here, nums[i]*min_ending_here}); 17 | min_ending_here = min({nums[i], nums[i]*tmp, nums[i]*min_ending_here}); 18 | max_overall = max(max_overall, max_ending_here); 19 | } 20 | return max_overall; 21 | } 22 | }; 23 | 24 | 25 | 26 | Java: 27 | ----- 28 | class Solution { 29 | public int maxProduct(int[] nums) { 30 | int max_overall = nums[0]; 31 | int max_ending_here = nums[0], min_ending_here = nums[0]; 32 | 33 | for(int i = 1; i < nums.length; ++i){ 34 | int tmp = max_ending_here; 35 | max_ending_here = Math.max(nums[i], Math.max(nums[i]*max_ending_here, nums[i]*min_ending_here)); 36 | min_ending_here = Math.min(nums[i], Math.min(nums[i]*tmp, nums[i]*min_ending_here)); 37 | max_overall = Math.max(max_overall, max_ending_here); 38 | } 39 | return max_overall; 40 | } 41 | } 42 | 43 | 44 | 45 | 46 | Python3: 47 | ------- 48 | class Solution: 49 | def maxProduct(self, nums: List[int]) -> int: 50 | max_overall = nums[0] 51 | max_ending_here, min_ending_here = nums[0], nums[0] 52 | 53 | for i in range(1, len(nums)): 54 | tmp = max_ending_here 55 | max_ending_here = max({nums[i], nums[i]*max_ending_here, nums[i]*min_ending_here}) 56 | min_ending_here = min({nums[i], nums[i]*tmp, nums[i]*min_ending_here}) 57 | max_overall = max(max_overall, max_ending_here) 58 | 59 | return max_overall 60 | 61 | 62 | -------------------------------------------------------------------------------- /129_Sum_Root_to_Leaf_Numbers: -------------------------------------------------------------------------------- 1 | Leetcode 129: Sum Root to Leaf Numbers 2 | -------------------------------------- 3 | Detailed Explanation can be found here: https://youtu.be/tanL9EJVfrU 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int sumNumbers(TreeNode* root) { 10 | if(!root) return 0; 11 | int result = 0; 12 | findsum(root, 0, result); 13 | return result; 14 | } 15 | void findsum(TreeNode* root, int val, int& result) { 16 | int curr = val*10 + root->val; 17 | if(!root->left && !root->right){ 18 | result += curr; 19 | return; 20 | } 21 | if(root->left) findsum(root->left, curr, result); 22 | if(root->right) findsum(root->right, curr, result); 23 | } 24 | }; 25 | 26 | Java: 27 | ----- 28 | class Solution { 29 | private int result; 30 | private void findsum(TreeNode root, int val) { 31 | int curr = val*10 + root.val; 32 | if(root.left == null && root.right == null){ 33 | result += curr; 34 | return; 35 | } 36 | if(root.left != null) findsum(root.left, curr); 37 | if(root.right != null) findsum(root.right, curr); 38 | } 39 | 40 | public int sumNumbers(TreeNode root) { 41 | if(root == null) return 0; 42 | result = 0; 43 | findsum(root, 0); 44 | return result; 45 | } 46 | } 47 | 48 | Python3: 49 | -------- 50 | class Solution: 51 | def sumNumbers(self, root: TreeNode) -> int: 52 | if root == None: return 0 53 | self.result = 0 54 | self.findsum(root, 0) 55 | return self.result 56 | 57 | def findsum(self, root, val): 58 | curr = val*10 + root.val 59 | if root.left == None and root.right == None: 60 | self.result += curr 61 | return 62 | 63 | if root.left != None: self.findsum(root.left, curr) 64 | if root.right != None: self.findsum(root.right, curr) 65 | 66 | 67 | ****** Please Subscribe Knowledge Center: http://youtube.com/c/KnowledgeCenter ******** 68 | -------------------------------------------------------------------------------- /56_Merge_Intervals: -------------------------------------------------------------------------------- 1 | Leetcode 56: Merge Intervals 2 | Detailed video explanation: https://youtu.be/hK_qN5UAAo4 3 | ============================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector> merge(vector>& intervals) { 11 | sort(intervals.begin(), intervals.end()); 12 | vector> result; 13 | int start = intervals[0][0], end = intervals[0][1]; 14 | for(auto& i : intervals){ 15 | if(i[0] > end){ // no overlap 16 | result.push_back({start, end}); 17 | start = i[0]; 18 | end = i[1]; 19 | } else // overlap 20 | end = max(end, i[1]); 21 | } 22 | result.push_back({start, end}); 23 | return result; 24 | } 25 | }; 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public int[][] merge(int[][] intervals) { 33 | Arrays.sort(intervals, (a,b)->Integer.compare(a[0], b[0])); 34 | List result = new ArrayList(); 35 | int start = intervals[0][0], end = intervals[0][1]; 36 | for(int[] i : intervals){ 37 | if(i[0] > end){ // no overlap 38 | result.add(new int[]{start, end}); 39 | start = i[0]; 40 | end = i[1]; 41 | } else // overlap 42 | end = Math.max(end, i[1]); 43 | } 44 | result.add(new int[]{start, end}); 45 | return result.toArray(new int[result.size()][2]); 46 | } 47 | } 48 | 49 | 50 | 51 | Python3: 52 | -------- 53 | class Solution: 54 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 55 | intervals.sort() 56 | result = [] 57 | start, end = intervals[0][0], intervals[0][1] 58 | for i in intervals: 59 | if i[0] > end: # no overlap 60 | result.append([start, end]) 61 | start, end = i[0], i[1] 62 | else: # overlap 63 | end = max(end, i[1]) 64 | result.append([start, end]); 65 | return result 66 | -------------------------------------------------------------------------------- /526_Beautiful_Arrangement: -------------------------------------------------------------------------------- 1 | Leetcode 526: Beautiful Arrangement 2 | Detailed video Explanation: https://youtu.be/vhHrUeSdFGU 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | void calculate(int n, int pos, vector& visited, int& count){ 10 | if(pos > n) count++; 11 | for(int i = 1; i <= n; ++i){ 12 | if(!visited[i] && (pos % i == 0 || i%pos == 0)){ 13 | visited[i] = true; 14 | calculate(n, pos+1, visited, count); 15 | visited[i] = false; 16 | } 17 | } 18 | } 19 | public: 20 | int countArrangement(int n) { 21 | vector visited(n+1, false); 22 | int count = 0; 23 | calculate(n, 1, visited, count); 24 | return count; 25 | } 26 | }; 27 | 28 | 29 | 30 | Java: 31 | ----- 32 | class Solution { 33 | private int count = 0; 34 | private void calculate(int n, int pos, boolean[] visited){ 35 | if(pos > n) count++; 36 | for(int i = 1; i <= n; ++i){ 37 | if(!visited[i] && (pos % i == 0 || i%pos == 0)){ 38 | visited[i] = true; 39 | calculate(n, pos+1, visited); 40 | visited[i] = false; 41 | } 42 | } 43 | } 44 | 45 | public int countArrangement(int n) { 46 | boolean[] visited = new boolean[n+1]; 47 | calculate(n, 1, visited); 48 | return count; 49 | } 50 | } 51 | 52 | 53 | 54 | 55 | Python3: 56 | -------- 57 | class Solution: 58 | def countArrangement(self, n: int) -> int: 59 | self.visited = [False]*(n+1) 60 | self.count = 0 61 | 62 | def calculate(n, pos): 63 | if pos > n: self.count += 1 64 | for i in range(1, n+1): 65 | if not self.visited[i] and (pos % i == 0 or i%pos == 0): 66 | self.visited[i] = True 67 | calculate(n, pos+1) 68 | self.visited[i] = False 69 | 70 | calculate(n, 1) 71 | return self.count 72 | 73 | 74 | -------------------------------------------------------------------------------- /435_Non-overlapping_Intervals: -------------------------------------------------------------------------------- 1 | Leetcode 435: Non-overlapping Intervals 2 | Detailed video explanation: https://youtu.be/BW7LeuJIMhE 3 | =============================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | int eraseOverlapIntervals(vector>& intervals) { 10 | if(intervals.size() < 2) return 0; 11 | sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){ 12 | return a[0] < b[0]; 13 | }); 14 | int count = 0, last_included = 0; 15 | for(int i = 1; i < intervals.size(); ++i){ 16 | if(intervals[i][0] < intervals[last_included][1]){ // Overlap 17 | count++; 18 | if(intervals[i][1] < intervals[last_included][1]) last_included = i; 19 | } else 20 | last_included = i; 21 | } 22 | return count; 23 | } 24 | }; 25 | 26 | 27 | Java: 28 | ---- 29 | class Solution { 30 | public int eraseOverlapIntervals(int[][] intervals) { 31 | if(intervals.length < 2) return 0; 32 | Arrays.sort(intervals, (a, b)->(a[0] - b[0])); 33 | int count = 0, last_included = 0; 34 | for(int i = 1; i < intervals.length; ++i){ 35 | if(intervals[i][0] < intervals[last_included][1]){ // Overlap 36 | count++; 37 | if(intervals[i][1] < intervals[last_included][1]) last_included = i; 38 | } else 39 | last_included = i; 40 | } 41 | return count; 42 | } 43 | } 44 | 45 | 46 | Python3: 47 | ------- 48 | class Solution: 49 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 50 | if len(intervals) < 2: return 0 51 | intervals.sort() 52 | count, last_included = 0, 0 53 | for i in range(1, len(intervals)): 54 | if intervals[i][0] < intervals[last_included][1]: # Overlap 55 | count += 1 56 | if intervals[i][1] < intervals[last_included][1]: last_included = i 57 | else: 58 | last_included = i 59 | return count 60 | 61 | -------------------------------------------------------------------------------- /849_Maximize_Distance_to_Closest_Person: -------------------------------------------------------------------------------- 1 | Leetcode 849: Maximize Distance to Closest Person 2 | Detailed video explanation: https://youtu.be/JtpGVqbiegQ 3 | ================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int maxDistToClosest(vector& seats) { 11 | int n = seats.size(); 12 | int empty = 0; 13 | int result = 0; 14 | int idx1 = -1, idx2 = -1; 15 | 16 | for(int i = 0; i < n; ++i){ 17 | if(seats[i] == 1){ 18 | empty = 0; 19 | if(idx1 == -1) idx1 = i; 20 | idx2 = i; 21 | } else { 22 | empty++; 23 | result = max(result, (empty+1)/2); 24 | } 25 | } 26 | result = max({result, idx1, n-1-idx2}); 27 | return result; 28 | } 29 | }; 30 | 31 | 32 | Java: 33 | ----- 34 | class Solution { 35 | public int maxDistToClosest(int[] seats) { 36 | int n = seats.length; 37 | int empty = 0; 38 | int result = 0; 39 | int idx1 = -1, idx2 = -1; 40 | 41 | for(int i = 0; i < n; ++i){ 42 | if(seats[i] == 1){ 43 | empty = 0; 44 | if(idx1 == -1) idx1 = i; 45 | idx2 = i; 46 | } else { 47 | empty++; 48 | result = Math.max(result, (empty+1)/2); 49 | } 50 | } 51 | result = Math.max(result, Math.max(idx1, n-1-idx2)); 52 | return result; 53 | } 54 | } 55 | 56 | 57 | Python3: 58 | ------- 59 | class Solution: 60 | def maxDistToClosest(self, seats: List[int]) -> int: 61 | n = len(seats) 62 | empty, result, idx1, idx2 = 0, 0, -1, -1 63 | 64 | for i in range(n): 65 | if seats[i] == 1: 66 | empty = 0 67 | if idx1 == -1: idx1 = i 68 | idx2 = i 69 | else: 70 | empty += 1 71 | result = max(result, (empty+1)//2) 72 | result = max(result, idx1, n-1-idx2) 73 | return result 74 | 75 | -------------------------------------------------------------------------------- /306_Additive_Number: -------------------------------------------------------------------------------- 1 | LeetCode 306: Additive Number 2 | Detailed Explanation video is available here: https://youtu.be/pKXsbH8-8-w 3 | 4 | C++ 5 | --- 6 | class Solution { 7 | bool find_rec(long long n1, long long n2, string s, bool found){ 8 | if (s.length() == 0 && found) 9 | return true; 10 | string n3 = to_string(n1 + n2); 11 | int idx = min(n3.length(), s.length()); 12 | if(s.substr(0, idx) == n3) 13 | return find_rec(n2, stol(n3), s.substr(idx), true); 14 | return false; 15 | } 16 | public: 17 | 18 | bool isAdditiveNumber(string num) { 19 | for (int i = 1; i < num.length() - 1; ++ i){ 20 | long long n1 = stol(num.substr(0, i)); 21 | if(to_string(n1) != num.substr(0, i)) 22 | break; 23 | for(int j = i+1; j < num.length(); ++j){ 24 | long long n2 = stol(num.substr(i, j-i)); 25 | if(to_string(n2) != num.substr(i, j-i)) 26 | break; 27 | bool found = find_rec(n1, n2, num.substr(j), false); 28 | if(found) 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | }; 35 | 36 | 37 | Python3: 38 | ------- 39 | class Solution: 40 | def find_rec(self, n1, n2, s, found): 41 | if s == "" and found: 42 | return True 43 | n3 = str(n1 + n2) 44 | idx = min(len(n3),len(s)) 45 | if s[:idx] == n3: 46 | return self.find_rec(n2, int(n3), s[idx:], True) 47 | return False 48 | 49 | def isAdditiveNumber(self, num: str) -> bool: 50 | for i in range(1, len(num)-1): 51 | n1 = int(num[:i]) 52 | if str(n1) != num[:i]: 53 | break 54 | for j in range(i+1, len(num)): 55 | n2 = int(num[i:j]) 56 | if str(n2) != num[i:j]: 57 | break 58 | found = self.find_rec(n1, n2, num[j:], False) 59 | if found: 60 | return True 61 | return False 62 | -------------------------------------------------------------------------------- /763_Partition_Labels: -------------------------------------------------------------------------------- 1 | Leetcode 763: Partition Labels 2 | Detailed video explanation: https://youtu.be/kS4P0vXbGmc 3 | ============================================ 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector partitionLabels(string S) { 11 | vector end_idx(26, 0); 12 | for(int i = 0; i < S.length(); ++i) 13 | end_idx[S[i] - 'a'] = i; 14 | 15 | vector result; 16 | int start = 0, end = 0; 17 | for(int i = 0; i < S.length(); ++i){ 18 | end = max(end, end_idx[S[i] - 'a']); 19 | if(i == end){ // all the characters of current partition included 20 | result.push_back(i - start + 1); 21 | start = i + 1; 22 | } 23 | } 24 | return result; 25 | } 26 | }; 27 | 28 | 29 | 30 | Java: 31 | ----- 32 | class Solution { 33 | public List partitionLabels(String S) { 34 | int[] end_idx = new int[26]; 35 | for(int i = 0; i < S.length(); ++i) 36 | end_idx[S.charAt(i) - 'a'] = i; 37 | 38 | List result = new ArrayList(); 39 | int start = 0, end = 0; 40 | for(int i = 0; i < S.length(); ++i){ 41 | end = Math.max(end, end_idx[S.charAt(i) - 'a']); 42 | if(i == end){ // all the characters of current partition included 43 | result.add(i - start + 1); 44 | start = i + 1; 45 | } 46 | } 47 | return result; 48 | } 49 | } 50 | 51 | 52 | 53 | 54 | Python3: 55 | ------- 56 | class Solution: 57 | def partitionLabels(self, S: str) -> List[int]: 58 | end_idx = [0]*26 59 | for i in range(len(S)): 60 | end_idx[ord(S[i]) - ord('a')] = i 61 | 62 | result = [] 63 | start, end = 0, 0 64 | for i in range(len(S)): 65 | end = max(end, end_idx[ord(S[i]) - ord('a')]); 66 | if i == end: # all the characters of current partition included 67 | result.append(i - start + 1) 68 | start = i + 1 69 | return result 70 | 71 | 72 | -------------------------------------------------------------------------------- /91_Decode_Ways: -------------------------------------------------------------------------------- 1 | // LeetCode 91: Decode Ways 2 | // Detailed Explanation is available here: https://youtu.be/o1i7JYWbwOE 3 | 4 | // C++ 5 | class Solution { 6 | public: 7 | int numDecodings(string s) { 8 | if(s.length() == 0 || s[0] == '0') return 0; 9 | if(s.length() == 1) return 1; 10 | 11 | int count1 = 1, count2 = 1; 12 | for(int i = 1; i < s.length(); ++i){ 13 | int d = s[i] - '0'; 14 | int dd = (s[i-1] - '0')*10 + d; 15 | int count = 0; 16 | if(d > 0) count += count2; 17 | if(dd >= 10 && dd <= 26) count += count1; 18 | count1 = count2; // prev to prev 19 | count2 = count; // count2 prev sol 20 | } 21 | return count2; 22 | } 23 | }; 24 | 25 | // Java 26 | class Solution { 27 | public int numDecodings(String s) { 28 | if(s.length() == 0 || s.charAt(0) == '0') return 0; 29 | if(s.length() == 1) return 1; 30 | 31 | int count1 = 1, count2 = 1; 32 | for(int i = 1; i < s.length(); ++i){ 33 | int d = s.charAt(i) - '0'; 34 | int dd = (s.charAt(i-1) - '0')*10 + d; 35 | int count = 0; 36 | if(d > 0) count += count2; 37 | if(dd >= 10 && dd <= 26) count += count1; 38 | count1 = count2; // prev to prev 39 | count2 = count; // count2 prev sol 40 | } 41 | return count2; 42 | } 43 | } 44 | 45 | # Python3 46 | class Solution: 47 | def numDecodings(self, s: str) -> int: 48 | if len(s) == 0 or s[0] == '0': return 0; 49 | if len(s) == 1: return 1; 50 | 51 | count1, count2 = 1,1 52 | for i in range(1, len(s)): 53 | d = ord(s[i]) - ord('0') 54 | dd = (ord(s[i-1]) - ord('0'))*10 + d 55 | count = 0 56 | if d > 0: count += count2 57 | if dd >= 10 and dd <= 26: count += count1 58 | count1 = count2 # prev to prev 59 | count2 = count # count2 prev sol 60 | 61 | return count2 62 | 63 | **** Please Like, Share and Subscribe 'Knowledge Center: https://www.youtube.com/c/KnowledgeCenter **** 64 | -------------------------------------------------------------------------------- /126_Word_Ladder_2: -------------------------------------------------------------------------------- 1 | Leetcode 126 : Word Ladder II 2 | Detailed video explanation : https://youtu.be/ZkmKsxls0Rs 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | vector findNeighbors(string word, unordered_set& wordList){ 10 | vector neighbors; 11 | for(int i = 0; i < word.size(); ++i){ 12 | int s = word[i]; 13 | for(char c = 'a'; c <= 'z'; ++c){ 14 | word[i] = c; 15 | if(wordList.find(word) != wordList.end()) 16 | neighbors.push_back(word); 17 | } 18 | word[i] = s; 19 | } 20 | return neighbors; 21 | } 22 | public: 23 | vector> findLadders(string beginWord, string endWord, vector& wordList) { 24 | unordered_set word_list(wordList.begin(), wordList.end()); 25 | vector> result; 26 | 27 | queue> Q; 28 | Q.push({beginWord}); 29 | bool reached_end = false; 30 | unordered_set visited; 31 | 32 | while(!Q.empty()){ 33 | int n = Q.size(); 34 | for(int i = 0; i < n; ++i){ 35 | vector path = Q.front(); // running path 36 | Q.pop(); 37 | vector neighbors = findNeighbors(path.back(), word_list); 38 | for(int j = 0; j < neighbors.size(); ++j){ 39 | vector new_path(path.begin(), path.end()); 40 | new_path.push_back(neighbors[j]); 41 | visited.insert(neighbors[j]); 42 | Q.push(new_path); 43 | if(neighbors[j] == endWord){ 44 | result.push_back(new_path); 45 | reached_end = true; 46 | } 47 | } 48 | } 49 | if(reached_end) break; 50 | for(auto it = visited.begin(); it != visited.end(); ++it) 51 | word_list.erase(*it); 52 | visited.clear(); 53 | } 54 | return result; 55 | } 56 | }; 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /1640_Check_Array_Formation_Through_Concatenation: -------------------------------------------------------------------------------- 1 | Leetcode 1640: Check Array Formation Through Concatenation 2 | Detailed video Explanation: https://youtu.be/1Q4N98UQnuc 3 | ========================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool canFormArray(vector& arr, vector>& pieces) { 11 | unordered_map> _map; 12 | for(auto p: pieces) 13 | _map.insert({p[0], p}); 14 | 15 | int idx = 0; 16 | while(idx < arr.size()){ 17 | if(_map.count(arr[idx])){ 18 | auto piece = _map[arr[idx]]; 19 | for(int p: piece){ 20 | if(p != arr[idx]) return false; 21 | else idx++; 22 | } 23 | } else 24 | return false; 25 | } 26 | return true; 27 | } 28 | }; 29 | 30 | 31 | 32 | Java: 33 | ----- 34 | class Solution { 35 | public boolean canFormArray(int[] arr, int[][] pieces) { 36 | Map _map = new HashMap<>(); 37 | for(int[] p: pieces) 38 | _map.put(p[0], p); 39 | 40 | int idx = 0; 41 | while(idx < arr.length){ 42 | if(_map.containsKey(arr[idx])){ 43 | int[] piece = _map.get(arr[idx]); 44 | for(int p: piece){ 45 | if(p != arr[idx]) return false; 46 | else idx++; 47 | } 48 | } else 49 | return false; 50 | } 51 | return true; 52 | } 53 | } 54 | 55 | 56 | 57 | 58 | Python3: 59 | -------- 60 | class Solution: 61 | def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: 62 | _map = {} 63 | for p in pieces: 64 | _map[p[0]] = p 65 | 66 | idx = 0 67 | while idx < len(arr): 68 | if arr[idx] in _map: 69 | piece = _map[arr[idx]] 70 | for p in piece: 71 | if p != arr[idx]: return False 72 | else: idx += 1 73 | else: 74 | return False 75 | return True 76 | 77 | 78 | -------------------------------------------------------------------------------- /949_Largest_Time_for_Given_Digits: -------------------------------------------------------------------------------- 1 | Leetcode 949: Largest Time for Given Digits 2 | Detailed video explanation: https://youtu.be/sn6r0ZV_2y4 3 | ============================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | string largestTimeFromDigits(vector& A) { 11 | string result; 12 | for(int i = 0; i < 4; ++i){ 13 | for(int j = 0; j < 4; ++j){ 14 | for(int k = 0; k < 4; ++k){ 15 | if(i == j || j == k || k == i) continue; 16 | string hh = to_string(A[i]) + to_string(A[j]); 17 | string mm = to_string(A[k]) + to_string(A[6-i-j-k]); 18 | string _time = hh + ":" + mm; 19 | if(hh < "24" && mm < "60" && _time > result) result = _time; 20 | } 21 | } 22 | } 23 | return result; 24 | } 25 | }; 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public String largestTimeFromDigits(int[] A) { 33 | String result = ""; 34 | for(int i = 0; i < 4; ++i){ 35 | for(int j = 0; j < 4; ++j){ 36 | for(int k = 0; k < 4; ++k){ 37 | if(i == j || j == k || k == i) continue; 38 | String hh = A[i] + "" + A[j]; 39 | String mm = A[k] + "" + A[6-i-j-k]; 40 | String _time = hh + ":" + mm; 41 | if(hh.compareTo("24") < 0 && mm.compareTo("60") < 0 && _time.compareTo(result) > 0) result = _time; 42 | } 43 | } 44 | } 45 | return result; 46 | } 47 | } 48 | 49 | 50 | 51 | Python3: 52 | ------- 53 | class Solution: 54 | def largestTimeFromDigits(self, A: List[int]) -> str: 55 | result = "" 56 | for i in range(4): 57 | for j in range(4): 58 | for k in range(4): 59 | if i == j or j == k or k == i: continue 60 | hh = str(A[i]) + str(A[j]) 61 | mm = str(A[k]) + str(A[6-i-j-k]) 62 | _time = hh + ":" + mm 63 | if hh < "24" and mm < "60" and _time > result: result = _time 64 | return result 65 | 66 | 67 | -------------------------------------------------------------------------------- /128_Longest_Consecutive_Sequence: -------------------------------------------------------------------------------- 1 | Leetcode 128 : Longest Consecutive Sequence 2 | Detailed video explanation : https://youtu.be/goJGPugNLcs 3 | ======================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int longestConsecutive(vector& nums) { 11 | unordered_set nums_set(nums.begin(), nums.end()); 12 | int res = 0; 13 | for(int n : nums){ 14 | if(nums_set.find(n) != nums_set.end()){ 15 | nums_set.erase(n); 16 | int prev = n-1; 17 | int next = n+1; 18 | while(nums_set.find(prev) != nums_set.end()) nums_set.erase(prev--); 19 | while(nums_set.find(next) != nums_set.end()) nums_set.erase(next++); 20 | res = max(res, next-prev-1); 21 | } 22 | } 23 | return res; 24 | } 25 | }; 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public int longestConsecutive(int[] nums) { 33 | Set nums_set = new HashSet(); 34 | for(int n : nums) nums_set.add(n); 35 | int res = 0; 36 | for(int n : nums){ 37 | if(nums_set.contains(n) ){ 38 | nums_set.remove(n); 39 | int prev = n-1; 40 | int next = n+1; 41 | while(nums_set.contains(prev)) nums_set.remove(prev--); 42 | while(nums_set.contains(next)) nums_set.remove(next++); 43 | res = Math.max(res, next-prev-1); 44 | } 45 | } 46 | return res; 47 | } 48 | } 49 | 50 | 51 | 52 | Python3: 53 | ------- 54 | class Solution: 55 | def longestConsecutive(self, nums: List[int]) -> int: 56 | nums_set = set(nums) 57 | res = 0 58 | for n in nums: 59 | if n in nums_set: 60 | nums_set.remove(n) 61 | prev, next = n-1, n+1 62 | while prev in nums_set: 63 | nums_set.remove(prev) 64 | prev -= 1 65 | while next in nums_set: 66 | nums_set.remove(next) 67 | next += 1 68 | res = max(res, next-prev-1) 69 | return res 70 | 71 | -------------------------------------------------------------------------------- /216_Combination_Sum_III: -------------------------------------------------------------------------------- 1 | Leetcode 216: Combination Sum III 2 | Detailed video explanation: https://youtu.be/rP_K3WJnRR4 3 | ================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | vector> result; 10 | void try_combination(vector& combination, int k, int n, int start){ 11 | if(k == combination.size()){ 12 | if(n == 0) result.push_back(combination); 13 | return; 14 | } 15 | for(int i = start; i <= 9; ++i){ 16 | combination.push_back(i); 17 | try_combination(combination, k, n-i, i+1); 18 | combination.pop_back(); 19 | } 20 | } 21 | public: 22 | vector> combinationSum3(int k, int n) { 23 | vector combination; 24 | try_combination(combination, k, n, 1); 25 | return result; 26 | } 27 | }; 28 | 29 | 30 | 31 | Java: 32 | ----- 33 | class Solution { 34 | List> result = new ArrayList(); 35 | void try_combination(List combination, int k, int n, int start){ 36 | if(k == combination.size()){ 37 | if(n == 0) result.add(new ArrayList(combination)); 38 | return; 39 | } 40 | for(int i = start; i <= 9; ++i){ 41 | combination.add(i); 42 | try_combination(combination, k, n-i, i+1); 43 | combination.remove(combination.size() - 1); 44 | } 45 | } 46 | public List> combinationSum3(int k, int n) { 47 | List combination = new ArrayList(); 48 | try_combination(combination, k, n, 1); 49 | return result; 50 | } 51 | } 52 | 53 | 54 | 55 | Python3: 56 | ------- 57 | class Solution: 58 | def combinationSum3(self, k: int, n: int) -> List[List[int]]: 59 | result = [] 60 | def try_combination(combination, n, start): 61 | if k == len(combination): 62 | if n == 0: result.append(combination.copy()) 63 | return 64 | for i in range(start, 10): 65 | combination.append(i) 66 | try_combination(combination, n-i, i+1) 67 | combination.pop() 68 | try_combination([], n, 1) 69 | return result 70 | 71 | 72 | -------------------------------------------------------------------------------- /102_Binary_Tree_Level_Order_Traversal: -------------------------------------------------------------------------------- 1 | Leetcode 102 : Binary Tree Level Order Traversal 2 | Detailed video explanation : https://youtu.be/jKFic8BnVA4 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | vector> levelOrder(TreeNode* root) { 22 | if(!root) return {}; 23 | vector> result; 24 | queue Q; 25 | Q.push(root); 26 | while(!Q.empty()){ 27 | int count = Q.size(); 28 | vector level_nodes; 29 | for(int i = 0; i < count; ++i){ 30 | TreeNode *node = Q.front(); 31 | Q.pop(); 32 | if(node->left) Q.push(node->left); 33 | if(node->right) Q.push(node->right); 34 | level_nodes.push_back(node->val); 35 | } 36 | result.push_back(level_nodes); 37 | } 38 | return result; 39 | } 40 | }; 41 | 42 | 43 | 44 | 45 | Python3: 46 | -------- 47 | # Definition for a binary tree node. 48 | # class TreeNode: 49 | # def __init__(self, val=0, left=None, right=None): 50 | # self.val = val 51 | # self.left = left 52 | # self.right = right 53 | class Solution: 54 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 55 | if root == None: return [] 56 | result, Q = [], [] 57 | Q.append(root) 58 | while Q: 59 | count = len(Q) 60 | level_nodes = [] 61 | for i in range(count): 62 | node = Q[0] 63 | Q.pop(0) 64 | if node.left != None: Q.append(node.left) 65 | if node.right != None: Q.append(node.right) 66 | level_nodes.append(node.val) 67 | 68 | result.append(level_nodes) 69 | 70 | return result 71 | 72 | -------------------------------------------------------------------------------- /208_Implement_Trie_(Prefix_Tree): -------------------------------------------------------------------------------- 1 | Leetcode 208 : Implement Trie (Prefix Tree) 2 | 3 | ===================================================== 4 | 5 | C++: 6 | ---- 7 | 8 | // Hashmap based 9 | class Trie { 10 | unordered_map children; 11 | bool isEndOfWord; 12 | public: 13 | Trie():isEndOfWord(false) {} 14 | 15 | void insert(string word) { 16 | Trie* curr = this; 17 | for(char c: word){ 18 | if(!curr->children.count(c)) 19 | curr->children[c] = new Trie(); 20 | curr = curr->children[c]; 21 | } 22 | curr->isEndOfWord = true; 23 | } 24 | 25 | bool search(string word) { 26 | Trie* curr = this; 27 | for(char c: word){ 28 | if(!curr->children.count(c)) 29 | return false; 30 | curr = curr->children[c]; 31 | } 32 | return curr->isEndOfWord; 33 | } 34 | 35 | bool startsWith(string prefix) { 36 | Trie* curr = this; 37 | for(char c: prefix){ 38 | if(!curr->children.count(c)) 39 | return false; 40 | curr = curr->children[c]; 41 | } 42 | return true; 43 | } 44 | }; 45 | 46 | /* Vector based 47 | class Trie { 48 | vector children; 49 | bool isEndOfWord; 50 | public: 51 | Trie():isEndOfWord(false), children(26, nullptr) {} 52 | 53 | void insert(string word) { 54 | Trie* curr = this; 55 | for(char c: word){ 56 | if(!curr->children[c-'a']) 57 | curr->children[c-'a'] = new Trie(); 58 | curr = curr->children[c-'a']; 59 | } 60 | curr->isEndOfWord = true; 61 | } 62 | 63 | bool search(string word) { 64 | Trie* curr = this; 65 | for(char c: word){ 66 | if(!curr->children[c-'a']) 67 | return false; 68 | curr = curr->children[c-'a']; 69 | } 70 | return curr->isEndOfWord; 71 | } 72 | 73 | bool startsWith(string prefix) { 74 | Trie* curr = this; 75 | for(char c: prefix){ 76 | if(!curr->children[c-'a']) 77 | return false; 78 | curr = curr->children[c-'a']; 79 | } 80 | return true; 81 | } 82 | }; 83 | */ 84 | -------------------------------------------------------------------------------- /835_Image_Overlap: -------------------------------------------------------------------------------- 1 | Leetcode 835: Image Overlap 2 | Detailed video Explanation: https://youtu.be/zfjBapE3Y6E 3 | ============================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | int shift_count(vector>& A, vector>& B){ 10 | int n = A.size(), count = 0; 11 | for(int x = 0; x < n; ++x){ 12 | for(int y = 0; y < n; ++y){ 13 | int temp = 0; 14 | for(int i = y; i < n; ++i){ 15 | for(int j = x; j < n; ++j) 16 | if(A[i][j] == 1 && B[i-y][j-x] == 1) temp++; 17 | } 18 | count = max(count, temp); 19 | } 20 | } 21 | return count; 22 | } 23 | public: 24 | int largestOverlap(vector>& A, vector>& B) { 25 | return max(shift_count(A, B), shift_count(B, A)); 26 | } 27 | }; 28 | 29 | 30 | 31 | Java: 32 | ----- 33 | class Solution { 34 | private int shift_count(int[][] A, int[][] B){ 35 | int n = A.length, count = 0; 36 | for(int x = 0; x < n; ++x){ 37 | for(int y = 0; y < n; ++y){ 38 | int temp = 0; 39 | for(int i = y; i < n; ++i){ 40 | for(int j = x; j < n; ++j) 41 | if(A[i][j] == 1 && B[i-y][j-x] == 1) temp++; 42 | } 43 | count = Math.max(count, temp); 44 | } 45 | } 46 | return count; 47 | } 48 | public int largestOverlap(int[][] A, int[][] B) { 49 | return Math.max(shift_count(A, B), shift_count(B, A)); 50 | } 51 | } 52 | 53 | 54 | 55 | Python3: 56 | ------- 57 | class Solution: 58 | def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int: 59 | def shift_count(AA, BB): 60 | n, count = len(AA), 0 61 | for x in range(n): 62 | for y in range(n): 63 | temp = 0 64 | for i in range(y, n): 65 | for j in range(x, n): 66 | if AA[i][j] == 1 and BB[i-y][j-x] == 1: temp += 1 67 | count = max(count, temp) 68 | return count 69 | 70 | return max(shift_count(A, B), shift_count(B, A)) 71 | 72 | 73 | -------------------------------------------------------------------------------- /107_BinaryTree_Level_Order_traversal_ii: -------------------------------------------------------------------------------- 1 | Letcode 107: Binary Tree Level Order traversal II 2 | Detailed video explanation can be found here: https://youtu.be/FSWqYp3k1O4 3 | 4 | C++ 5 | --- 6 | vector> levelOrderBottom(TreeNode* root) { 7 | vector> result; 8 | if(!root) return result; 9 | queue Q; 10 | Q.push(root); 11 | while(!Q.empty()){ 12 | int n = Q.size(); 13 | vector nodes(n); 14 | for(int i = 0; i < n; ++i){ 15 | TreeNode* node = Q.front(); 16 | nodes[i] = node->val; 17 | Q.pop(); 18 | if(node->left) Q.push(node->left); 19 | if(node->right) Q.push(node->right); 20 | } 21 | result.push_back(nodes); 22 | } 23 | reverse(result.begin(), result.end()); 24 | return result; 25 | } 26 | 27 | 28 | Java: 29 | ---- 30 | public List> levelOrderBottom(TreeNode root) { 31 | ArrayList> result = new ArrayList>(); 32 | if(root == null) return result; 33 | Queue Q = new LinkedList<>(); 34 | Q.add(root); 35 | while(!Q.isEmpty()){ 36 | int n = Q.size(); 37 | List nodes = new ArrayList(); 38 | for(int i = 0; i < n; ++i){ 39 | TreeNode node = Q.poll(); 40 | nodes.add(node.val); 41 | if(node.left != null) Q.add(node.left); 42 | if(node.right != null) Q.add(node.right); 43 | } 44 | result.add(0, nodes); 45 | } 46 | return result; 47 | } 48 | 49 | 50 | Python3: 51 | -------- 52 | def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: 53 | result = [] 54 | if root == None: return result 55 | Q = [] 56 | Q.append(root) 57 | while len(Q) > 0: 58 | n = len(Q) 59 | nodes = [] 60 | for i in range(n): 61 | node = Q.pop(0) 62 | nodes.append(node.val) 63 | if node.left != None: Q.append(node.left) 64 | if node.right != None: Q.append(node.right) 65 | result.insert(0, nodes) 66 | 67 | return result 68 | -------------------------------------------------------------------------------- /967_Numbers_With_Same_Consecutive_Differences: -------------------------------------------------------------------------------- 1 | Leetcode 967: Numbers With Same Consecutive Differences 2 | Detailed video explanation: https://youtu.be/TAfXh2l9FyA 3 | ======================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | void dfs(int num, int N, int K, vector& result){ 10 | if(N == 0){ 11 | result.push_back(num); 12 | return; 13 | } 14 | int last_digit = num%10; 15 | if(last_digit >= K) dfs(num*10 + last_digit - K, N-1, K, result); 16 | if(K > 0 && last_digit + K < 10) dfs(num*10 + last_digit + K, N-1, K, result); 17 | } 18 | public: 19 | vector numsSameConsecDiff(int N, int K) { 20 | vector result; 21 | if(N == 1) result.push_back(0); 22 | for(int d = 1; d < 10; ++d) 23 | dfs(d, N-1, K, result); 24 | 25 | return result; 26 | } 27 | }; 28 | 29 | 30 | Java: 31 | ----- 32 | class Solution { 33 | private void dfs(int num, int N, int K, List result){ 34 | if(N == 0){ 35 | result.add(num); 36 | return; 37 | } 38 | int last_digit = num%10; 39 | if(last_digit >= K) dfs(num*10 + last_digit - K, N-1, K, result); 40 | if(K > 0 && last_digit + K < 10) dfs(num*10 + last_digit + K, N-1, K, result); 41 | } 42 | 43 | public int[] numsSameConsecDiff(int N, int K) { 44 | List result = new ArrayList(); 45 | if(N == 1) result.add(0); 46 | for(int d = 1; d < 10; ++d) 47 | dfs(d, N-1, K, result); 48 | 49 | return result.stream().mapToInt(i->i).toArray(); 50 | } 51 | } 52 | 53 | 54 | Python3: 55 | ------- 56 | class Solution: 57 | def numsSameConsecDiff(self, N: int, K: int) -> List[int]: 58 | result = [] 59 | if N == 1: result.append(0) 60 | 61 | def dfs( num, N): 62 | if N == 0: 63 | result.append(num) 64 | return 65 | last_digit = num%10 66 | if last_digit >= K: dfs(num*10 + last_digit - K, N-1) 67 | if K > 0 and last_digit + K < 10: dfs(num*10 + last_digit + K, N-1) 68 | 69 | for d in range(1, 10): 70 | dfs(d, N-1) 71 | 72 | return result 73 | 74 | 75 | -------------------------------------------------------------------------------- /100_Same_Tree: -------------------------------------------------------------------------------- 1 | Leetcode 100: Same Tree 2 | Detailed video explanation of Recursive and Iterative Approach: https://youtu.be/5qj18l76xy4 3 | 4 | C++: 5 | ==== 6 | Recursive: 7 | ---------- 8 | bool isSameTree(TreeNode* p, TreeNode* q) { 9 | if(!p && !q) return true; 10 | if(!p || !q) return false; 11 | if(p->val != q->val) return false; 12 | 13 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 14 | } 15 | 16 | Iterative: 17 | ---------- 18 | class Solution { 19 | bool areEqual(TreeNode* p, TreeNode* q){ 20 | if(!p && !q) return true; 21 | if(!p || !q) return false; 22 | if(p->val != q->val) return false; 23 | return true; 24 | } 25 | public: 26 | bool isSameTree(TreeNode* p, TreeNode* q) { 27 | if(!areEqual(p, q)) return false; 28 | queue Q1, Q2; 29 | Q1.push(p); 30 | Q2.push(q); 31 | while(!Q1.empty()){ 32 | TreeNode* n1 = Q1.front(); 33 | Q1.pop(); 34 | TreeNode* n2 = Q2.front(); 35 | Q2.pop(); 36 | 37 | if(!areEqual(n1, n2)) return false; 38 | if(n1){ 39 | if(!areEqual(n1->left, n2->left)) return false; 40 | if(n1->left){ 41 | Q1.push(n1->left); 42 | Q2.push(n2->left); 43 | } 44 | if(!areEqual(n1->right, n2->right)) return false; 45 | if(n1->right){ 46 | Q1.push(n1->right); 47 | Q2.push(n2->right); 48 | } 49 | } 50 | } 51 | return true; 52 | } 53 | 54 | 55 | Java: 56 | ===== 57 | public boolean isSameTree(TreeNode p, TreeNode q) { 58 | if(p == null && q == null) return true; 59 | if(p == null || q == null) return false; 60 | if(p.val != q.val) return false; 61 | 62 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 63 | } 64 | 65 | 66 | Python3: 67 | ======== 68 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 69 | if p == None and q == None: return True 70 | if p == None or q == None: return False 71 | if p.val != q.val: return False 72 | 73 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 74 | 75 | 76 | -------------------------------------------------------------------------------- /969_Pancake_Sorting: -------------------------------------------------------------------------------- 1 | Leetcode 969: Pancake Sorting 2 | Detailed video explanation: https://youtu.be/AFtXLUn_TZg 3 | ============================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | void flip(vector& A, int idx){ 9 | for(int i = 0; i <= idx/2; ++i){ 10 | int tmp = A[i]; 11 | A[i] = A[idx-i]; 12 | A[idx-i] = tmp; 13 | } 14 | } 15 | public: 16 | vector pancakeSort(vector& A) { 17 | vector result; 18 | for(int i = A.size()-1; i > 0; --i){ 19 | for(int j = 1; j <= i; ++j){ 20 | if(A[j] == i+1){ 21 | flip(A, j); 22 | result.push_back(j+1); 23 | break; 24 | } 25 | } 26 | flip(A, i); 27 | result.push_back(i+1); 28 | } 29 | return result; 30 | } 31 | }; 32 | 33 | 34 | 35 | Java: 36 | ---- 37 | class Solution { 38 | private void flip(int[]A, int idx){ 39 | for(int i = 0; i <= idx/2; ++i){ 40 | int tmp = A[i]; 41 | A[i] = A[idx-i]; 42 | A[idx-i] = tmp; 43 | } 44 | } 45 | public List pancakeSort(int[] A) { 46 | List result = new ArrayList(); 47 | for(int i = A.length-1; i > 0; --i){ 48 | for(int j = 1; j <= i; ++j){ 49 | if(A[j] == i+1){ 50 | flip(A, j); 51 | result.add(j+1); 52 | break; 53 | } 54 | } 55 | flip(A, i); 56 | result.add(i+1); 57 | } 58 | return result; 59 | } 60 | } 61 | 62 | 63 | 64 | Python3: 65 | ------- 66 | class Solution: 67 | def pancakeSort(self, A: List[int]) -> List[int]: 68 | result = [] 69 | def flip(idx): 70 | for i in range(0, idx//2+1): 71 | tmp = A[i] 72 | A[i] = A[idx-i] 73 | A[idx-i] = tmp 74 | for i in range(len(A)-1, 0, -1): 75 | for j in range(1, i+1): 76 | if A[j] == i+1: 77 | flip(j) 78 | result.append(j+1) 79 | break 80 | flip(i) 81 | result.append(i+1) 82 | return result 83 | 84 | 85 | -------------------------------------------------------------------------------- /81_Search_in_Rotated_Sorted_Array_II: -------------------------------------------------------------------------------- 1 | Leetcode 81: Search in Rotated Sorted Array II 2 | Detailed video explanation: https://youtu.be/WkihvY2rJjc 3 | ==================================================== 4 | 5 | C++: 6 | ---- 7 | class Solution { 8 | public: 9 | bool search(vector& nums, int target) { 10 | int l=0, r = nums.size()-1; 11 | while(l <= r){ 12 | int mid = l + (r-l)/2; 13 | if(nums[mid] == target) return true; 14 | if( (nums[l] == nums[mid]) && (nums[r] == nums[mid])) {l++; r--;} 15 | else if(nums[l] <= nums[mid]){ 16 | if((nums[l] <= target) && (nums[mid] > target)) r = mid-1; 17 | else l = mid + 1; 18 | } else { 19 | if((nums[mid] < target) && (nums[r] >= target)) l = mid + 1; 20 | else r = mid-1; 21 | } 22 | } 23 | return false; 24 | } 25 | }; 26 | 27 | 28 | 29 | Java: 30 | ----- 31 | class Solution { 32 | public boolean search(int[] nums, int target) { 33 | int l=0, r = nums.length-1; 34 | while(l <= r){ 35 | int mid = l + (r-l)/2; 36 | if(nums[mid] == target) return true; 37 | if( (nums[l] == nums[mid]) && (nums[r] == nums[mid])) {l++; r--;} 38 | else if(nums[l] <= nums[mid]){ 39 | if((nums[l] <= target) && (nums[mid] > target)) r = mid-1; 40 | else l = mid + 1; 41 | } else { 42 | if((nums[mid] < target) && (nums[r] >= target)) l = mid + 1; 43 | else r = mid-1; 44 | } 45 | } 46 | return false; 47 | } 48 | } 49 | 50 | 51 | 52 | Python3: 53 | -------- 54 | class Solution: 55 | def search(self, nums: List[int], target: int) -> bool: 56 | l, r = 0, len(nums)-1 57 | while l <= r: 58 | mid = l + (r-l)//2 59 | if nums[mid] == target: return True 60 | if (nums[l] == nums[mid]) and (nums[r] == nums[mid]): l, r = l+1, r-1 61 | elif nums[l] <= nums[mid]: 62 | if (nums[l] <= target) and (nums[mid] > target): r = mid-1 63 | else: l = mid + 1 64 | else: 65 | if (nums[mid] < target) and (nums[r] >= target): l = mid + 1 66 | else: r = mid-1 67 | return False 68 | 69 | -------------------------------------------------------------------------------- /25_Reverse_Nodes_in_k-Group: -------------------------------------------------------------------------------- 1 | Leetcode 25: Reverse Nodes in k-Group 2 | Detailed video explanation: https://youtu.be/BfQeP6XEXEc 3 | ======================================================== 4 | 5 | C++: 6 | --- 7 | class Solution { 8 | public: 9 | ListNode* reverseKGroup(ListNode* head, int k) { 10 | if(!head || !head->next || k == 1) return head; 11 | int n = 0; // count 12 | ListNode *curr = head; 13 | while(curr){ 14 | n++; 15 | curr = curr->next; 16 | } 17 | 18 | ListNode *prev = nullptr, *next, *newHead; 19 | ListNode *t1 = nullptr, *t2 = head; 20 | curr = head; 21 | 22 | while(n >= k){ 23 | for(int i = 0; i < k; i++){ 24 | next = curr->next; 25 | curr->next = prev; 26 | prev = curr; 27 | curr = next; 28 | } 29 | if(!newHead) newHead = prev; 30 | if(t1) t1->next = prev; 31 | t2->next = curr; // n is not multiple of k 32 | t1 = t2; 33 | t2 = curr; 34 | prev = nullptr; 35 | n -= k; 36 | } 37 | return newHead; 38 | } 39 | }; 40 | 41 | Python3: 42 | ------- 43 | # Definition for singly-linked list. 44 | # class ListNode: 45 | # def __init__(self, val=0, next=None): 46 | # self.val = val 47 | # self.next = next 48 | class Solution: 49 | def reverseKGroup(self, head: ListNode, k: int) -> ListNode: 50 | if (head == None) or (head.next == None) or (k == 1): return head 51 | n = 0 # count 52 | curr = head 53 | while curr != None: 54 | n, curr = n+1, curr.next 55 | 56 | prev, next, newHead = None, None, None 57 | t1, t2 = None, head 58 | curr = head 59 | 60 | while n >= k: 61 | for i in range(k): 62 | next = curr.next 63 | curr.next = prev 64 | prev = curr 65 | curr = next 66 | 67 | if newHead == None: newHead = prev 68 | if t1 != None: t1.next = prev 69 | t2.next = curr # n is not multiple of k 70 | t1 = t2 71 | t2 = curr 72 | prev = None 73 | n -= k 74 | 75 | return newHead 76 | 77 | -------------------------------------------------------------------------------- /174_DungeonGame: -------------------------------------------------------------------------------- 1 | // C++: 2 | // ----- 3 | int calculateMinimumHP(vector>& dungeon) { 4 | int r = dungeon.size(); 5 | int c = dungeon[0].size(); 6 | vector> sol(r, vector(c)); 7 | 8 | sol[r-1][c-1] = dungeon[r-1][c-1] > 0 ? 1 : 1-dungeon[r-1][c-1]; 9 | 10 | for(int i = r-2; i >= 0; --i) 11 | sol[i][c-1] = max(sol[i+1][c-1] - dungeon[i][c-1], 1); 12 | for(int j = c-2; j >= 0; --j) 13 | sol[r-1][j] = max(sol[r-1][j+1] - dungeon[r-1][j], 1); 14 | 15 | for(int i = r-2; i >= 0; --i){ 16 | for(int j = c-2; j >= 0; --j){ 17 | sol[i][j] = max(min(sol[i+1][j], sol[i][j+1])-dungeon[i][j], 1); 18 | } 19 | } 20 | return sol[0][0]; 21 | } 22 | 23 | // Java: 24 | // ----- 25 | public int calculateMinimumHP(int[][] dungeon) { 26 | int r = dungeon.length; 27 | int c = dungeon[0].length; 28 | int[][] sol = new int[r][c]; 29 | 30 | sol[r-1][c-1] = dungeon[r-1][c-1] > 0 ? 1 : 1-dungeon[r-1][c-1]; 31 | 32 | for(int i = r-2; i >= 0; --i) 33 | sol[i][c-1] = Math.max(sol[i+1][c-1] - dungeon[i][c-1], 1); 34 | for(int j = c-2; j >= 0; --j) 35 | sol[r-1][j] = Math.max(sol[r-1][j+1] - dungeon[r-1][j], 1); 36 | 37 | for(int i = r-2; i >= 0; --i){ 38 | for(int j = c-2; j >= 0; --j){ 39 | sol[i][j] = Math.max(Math.min(sol[i+1][j], sol[i][j+1])-dungeon[i][j], 1); 40 | } 41 | } 42 | return sol[0][0]; 43 | } 44 | 45 | # Python3: 46 | # -------- 47 | def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: 48 | r = len(dungeon) 49 | c = len(dungeon[0]) 50 | sol = [[0]*c for i in range(r)] 51 | 52 | sol[r-1][c-1] = 1 if dungeon[r-1][c-1] > 0 else 1-dungeon[r-1][c-1] 53 | 54 | for i in range(r-2, -1, -1): 55 | sol[i][c-1] = max(sol[i+1][c-1] - dungeon[i][c-1], 1) 56 | for j in range(c-2, -1, -1): 57 | sol[r-1][j] = max(sol[r-1][j+1] - dungeon[r-1][j], 1) 58 | 59 | for i in range(r-2, -1, -1): 60 | for j in range(c-2, -1, -1): 61 | sol[i][j] = max(min(sol[i+1][j], sol[i][j+1])-dungeon[i][j], 1) 62 | 63 | return sol[0][0] 64 | -------------------------------------------------------------------------------- /57_Insert_Interval: -------------------------------------------------------------------------------- 1 | Leetcode 57: Insert Interval 2 | Detailed video Explanation: https://youtu.be/FuLfL_WhUHI 3 | ============================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | vector> insert(vector>& intervals, vector& newInterval) { 11 | vector> result; 12 | int i = 0, n = intervals.size(); 13 | while(i < n && intervals[i][1] < newInterval[0]) result.push_back(intervals[i++]); 14 | 15 | vector mI = newInterval; 16 | while(i < n && intervals[i][0] <= newInterval[1]){ 17 | mI[0] = min(mI[0], intervals[i][0]); 18 | mI[1] = max(mI[1], intervals[i++][1]); 19 | } 20 | result.push_back(mI); 21 | 22 | while(i < n) result.push_back(intervals[i++]); 23 | 24 | return result; 25 | } 26 | }; 27 | 28 | 29 | 30 | Java: 31 | ----- 32 | class Solution { 33 | public int[][] insert(int[][] intervals, int[] newInterval) { 34 | List result = new ArrayList(); 35 | int i = 0, n = intervals.length; 36 | while(i < n && intervals[i][1] < newInterval[0]) result.add(intervals[i++]); 37 | 38 | int[] mI = newInterval; 39 | while(i < n && intervals[i][0] <= newInterval[1]){ 40 | mI[0] = Math.min(mI[0], intervals[i][0]); 41 | mI[1] = Math.max(mI[1], intervals[i++][1]); 42 | } 43 | result.add(mI); 44 | 45 | while(i < n) result.add(intervals[i++]); 46 | 47 | return result.toArray(new int[result.size()][2]); 48 | } 49 | } 50 | 51 | 52 | 53 | Python3: 54 | -------- 55 | class Solution: 56 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 57 | result = [] 58 | i, n = 0, len(intervals) 59 | while i < n and intervals[i][1] < newInterval[0]: 60 | result.append(intervals[i]) 61 | i += 1 62 | 63 | mI = newInterval; 64 | while i < n and intervals[i][0] <= newInterval[1]: 65 | mI[0] = min(mI[0], intervals[i][0]) 66 | mI[1] = max(mI[1], intervals[i][1]) 67 | i += 1 68 | 69 | result.append(mI) 70 | 71 | while i < n: 72 | result.append(intervals[i]) 73 | i += 1 74 | 75 | return result 76 | -------------------------------------------------------------------------------- /1379_Find_a_Corresponding_Node_of_a_Binary_Tree_in_a_Clone_of_That_Tree: -------------------------------------------------------------------------------- 1 | Leetcode 1379 : Find a Corresponding Node of a Binary Tree in a Clone of That Tree 2 | Detailed video Explanation: https://youtu.be/_9Vo3S-PbIU 3 | =================================================================================== 4 | 5 | 6 | 7 | C++: 8 | ---- 9 | /** 10 | * Definition for a binary tree node. 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | 19 | class Solution { 20 | public: 21 | TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) { 22 | if(original){ 23 | if(original == target) return cloned; 24 | TreeNode *t = getTargetCopy(original->left, cloned->left, target); 25 | if(t) return t; 26 | return getTargetCopy(original->right, cloned->right, target); 27 | } 28 | return nullptr; 29 | } 30 | }; 31 | 32 | 33 | 34 | Java: 35 | ----- 36 | /** 37 | * Definition for a binary tree node. 38 | * public class TreeNode { 39 | * int val; 40 | * TreeNode left; 41 | * TreeNode right; 42 | * TreeNode(int x) { val = x; } 43 | * } 44 | */ 45 | 46 | class Solution { 47 | public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) { 48 | if(original != null){ 49 | if(original == target) return cloned; 50 | TreeNode t = getTargetCopy(original.left, cloned.left, target); 51 | if(t != null) return t; 52 | return getTargetCopy(original.right, cloned.right, target); 53 | } 54 | return null; 55 | } 56 | } 57 | 58 | 59 | 60 | Python3: 61 | ------- 62 | # Definition for a binary tree node. 63 | # class TreeNode: 64 | # def __init__(self, x): 65 | # self.val = x 66 | # self.left = None 67 | # self.right = None 68 | 69 | class Solution: 70 | def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: 71 | if original != None: 72 | if original == target: return cloned 73 | t = self.getTargetCopy(original.left, cloned.left, target) 74 | if t != None: return t 75 | return self.getTargetCopy(original.right, cloned.right, target) 76 | 77 | return None 78 | 79 | 80 | -------------------------------------------------------------------------------- /332_Reconstruct_Itinerary: -------------------------------------------------------------------------------- 1 | LeetCode 332: Reconstruct Itinerary 2 | Detailed Explanation can be found here: https://youtu.be/j31ZOupyrAs 3 | 4 | C++ 5 | 6 | class Solution { 7 | void dfs(unordered_map>& adj, vector& result, string s){ 8 | while(adj[s].size()){ 9 | string v = *(adj[s].begin()); 10 | adj[s].erase(adj[s].begin()); 11 | dfs(adj, result, v); 12 | } 13 | result.push_back(s); 14 | } 15 | public: 16 | vector findItinerary(vector>& tickets) { 17 | unordered_map> adj; 18 | for(vector& t: tickets) 19 | adj[t[0]].insert(t[1]); 20 | 21 | vector result; 22 | dfs(adj, result, "JFK"); 23 | reverse(result.begin(), result.end()); 24 | return result; 25 | } 26 | }; 27 | 28 | 29 | Java 30 | 31 | class Solution { 32 | private void dfs(Map> adj, LinkedList result, String s){ 33 | PriorityQueue pq = adj.get(s); 34 | while(pq != null && !pq.isEmpty()){ 35 | String v = pq.poll(); 36 | dfs(adj, result, v); 37 | } 38 | result.addFirst(s); 39 | } 40 | public List findItinerary(List> tickets) { 41 | Map> adj = new HashMap(); 42 | for(List t: tickets){ 43 | adj.putIfAbsent(t.get(0), new PriorityQueue<>()); 44 | adj.get(t.get(0)).add(t.get(1)); 45 | } 46 | 47 | LinkedList result = new LinkedList(); 48 | dfs(adj, result, "JFK"); 49 | return result; 50 | } 51 | } 52 | 53 | Python3 54 | class Solution: 55 | def findItinerary(self, tickets: List[List[str]]) -> List[str]: 56 | self.adj = {} 57 | tickets.sort(key=lambda x: x[1]) 58 | 59 | for u, v in tickets: 60 | if u in self.adj: 61 | self.adj[u].append(v) 62 | else: 63 | self.adj[u] = [v] 64 | 65 | self.result = [] 66 | self.dfs("JFK") 67 | 68 | return self.result[::-1] 69 | 70 | def dfs(self, s): 71 | while s in self.adj and len(self.adj[s]) > 0: 72 | v = self.adj[s][0] 73 | (self.adj[s]).pop(0) 74 | self.dfs(v) 75 | 76 | self.result.append(s) 77 | -------------------------------------------------------------------------------- /814_Binary_tree_Pruning: -------------------------------------------------------------------------------- 1 | Leetcode 814 : Binary Tree Pruning 2 | Detailed video explanation : https://youtu.be/EW_eWjP2pAM 3 | ========================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode* pruneTree(TreeNode* root) { 22 | if(!root) return nullptr; 23 | root->left = pruneTree(root->left); 24 | root->right = pruneTree(root->right); 25 | if(root->left || root->right) 26 | return root; 27 | if(root->val == 0) return nullptr; 28 | return root; 29 | } 30 | }; 31 | 32 | 33 | 34 | Java: 35 | ----- 36 | /** 37 | * Definition for a binary tree node. 38 | * public class TreeNode { 39 | * int val; 40 | * TreeNode left; 41 | * TreeNode right; 42 | * TreeNode() {} 43 | * TreeNode(int val) { this.val = val; } 44 | * TreeNode(int val, TreeNode left, TreeNode right) { 45 | * this.val = val; 46 | * this.left = left; 47 | * this.right = right; 48 | * } 49 | * } 50 | */ 51 | class Solution { 52 | public TreeNode pruneTree(TreeNode root) { 53 | if(root == null) return null; 54 | root.left = pruneTree(root.left); 55 | root.right = pruneTree(root.right); 56 | if(root.left != null || root.right != null) 57 | return root; 58 | if(root.val == 0) return null; 59 | return root; 60 | } 61 | } 62 | 63 | 64 | 65 | Python3: 66 | -------- 67 | # Definition for a binary tree node. 68 | # class TreeNode: 69 | # def __init__(self, val=0, left=None, right=None): 70 | # self.val = val 71 | # self.left = left 72 | # self.right = right 73 | class Solution: 74 | def pruneTree(self, root: TreeNode) -> TreeNode: 75 | if root == None: return None 76 | root.left = self.pruneTree(root.left) 77 | root.right = self.pruneTree(root.right) 78 | if root.left != None or root.right != None: 79 | return root 80 | if root.val == 0: return None 81 | return root 82 | 83 | -------------------------------------------------------------------------------- /359_Logger_rate_Limiter: -------------------------------------------------------------------------------- 1 | Leetcode 359 : Logger Rate Limiter 2 | Detailed video Explanation: https://youtu.be/GXmMeKGSfP4 3 | ===================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Logger { 9 | unordered_map map0_10, map10_20; 10 | int t; 11 | public: 12 | /** Initialize your data structure here. */ 13 | Logger():t(0) { 14 | 15 | } 16 | 17 | /** Returns true if the message should be printed in the given timestamp, otherwise returns false. 18 | If this method returns false, the message will not be printed. 19 | The timestamp is in seconds granularity. */ 20 | bool shouldPrintMessage(int timestamp, string message) { 21 | if(timestamp >= t + 10){ 22 | map10_20 = map0_10; 23 | map0_10.clear(); 24 | t = timestamp; 25 | } 26 | if(map0_10.find(message) != map0_10.end()) return false; 27 | int ts = map10_20[message]; 28 | if(ts && timestamp < ts + 10) return false; 29 | map0_10[message] = timestamp; 30 | return true; 31 | } 32 | }; 33 | 34 | /** 35 | * Your Logger object will be instantiated and called as such: 36 | * Logger* obj = new Logger(); 37 | * bool param_1 = obj->shouldPrintMessage(timestamp,message); 38 | */ 39 | 40 | 41 | Python3: 42 | ------- 43 | class Logger: 44 | 45 | def __init__(self): 46 | """ 47 | Initialize your data structure here. 48 | """ 49 | self.map0_10, self.map10_20 = {}, {} 50 | self.t = 0 51 | 52 | 53 | def shouldPrintMessage(self, timestamp: int, message: str) -> bool: 54 | """ 55 | Returns true if the message should be printed in the given timestamp, otherwise returns false. 56 | If this method returns false, the message will not be printed. 57 | The timestamp is in seconds granularity. 58 | """ 59 | if timestamp >= self.t + 10: 60 | self.map10_20 = self.map0_10 61 | self.map0_10 = {} 62 | self.t = timestamp 63 | 64 | if message in self.map0_10: return False 65 | if message in self.map10_20 and timestamp < self.map10_20[message] + 10: return False 66 | self.map0_10[message] = timestamp 67 | return True 68 | 69 | 70 | 71 | # Your Logger object will be instantiated and called as such: 72 | # obj = Logger() 73 | # param_1 = obj.shouldPrintMessage(timestamp,message) 74 | 75 | 76 | -------------------------------------------------------------------------------- /563_Binary_Tree_Tilt: -------------------------------------------------------------------------------- 1 | Leetcode 563: Binary Tree Tilt 2 | Detailed video explanation: https://youtu.be/h-Wo5TIzfjI 3 | ======================================= 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | int findSum(TreeNode* root, int& tilt){ 21 | if(!root) return 0; 22 | int l = findSum(root->left, tilt); 23 | int r = findSum(root->right, tilt); 24 | tilt += abs(l-r); 25 | return l + r + root->val; 26 | } 27 | public: 28 | int findTilt(TreeNode* root) { 29 | int tilt = 0; 30 | findSum(root, tilt); 31 | return tilt; 32 | } 33 | }; 34 | 35 | 36 | 37 | Java: 38 | ----- 39 | /** 40 | * Definition for a binary tree node. 41 | * public class TreeNode { 42 | * int val; 43 | * TreeNode left; 44 | * TreeNode right; 45 | * TreeNode() {} 46 | * TreeNode(int val) { this.val = val; } 47 | * TreeNode(int val, TreeNode left, TreeNode right) { 48 | * this.val = val; 49 | * this.left = left; 50 | * this.right = right; 51 | * } 52 | * } 53 | */ 54 | class Solution { 55 | private int tilt = 0; 56 | private int findSum(TreeNode root){ 57 | if(root == null) return 0; 58 | int l = findSum(root.left); 59 | int r = findSum(root.right); 60 | tilt += Math.abs(l-r); 61 | return l + r + root.val; 62 | } 63 | public int findTilt(TreeNode root) { 64 | findSum(root); 65 | return tilt; 66 | } 67 | } 68 | 69 | 70 | 71 | 72 | Python3: 73 | -------- 74 | # Definition for a binary tree node. 75 | # class TreeNode: 76 | # def __init__(self, val=0, left=None, right=None): 77 | # self.val = val 78 | # self.left = left 79 | # self.right = right 80 | class Solution: 81 | def findTilt(self, root: TreeNode) -> int: 82 | self.tilt = 0 83 | def findSum(root): 84 | if root == None: return 0 85 | l = findSum(root.left) 86 | r = findSum(root.right) 87 | self.tilt += abs(l-r) 88 | return l + r + root.val 89 | findSum(root) 90 | return self.tilt 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /82_Remove_Duplicates_from_Sorted_List_II: -------------------------------------------------------------------------------- 1 | Leetcode 82: Remove Duplicates from Sorted List II 2 | Detailed video Explanation: https://youtu.be/iv2RAR61-wM 3 | ====================================================== 4 | 5 | 6 | 7 | C++: 8 | ---- 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode() : val(0), next(nullptr) {} 15 | * ListNode(int x) : val(x), next(nullptr) {} 16 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | ListNode* deleteDuplicates(ListNode* head) { 22 | if(!head || !head->next) return head; 23 | ListNode *next = head->next; 24 | 25 | if(next->val == head->val){ 26 | while(next && next->val == head->val) next = next->next; 27 | return deleteDuplicates(next); 28 | } else { 29 | head->next = deleteDuplicates(next); 30 | return head; 31 | } 32 | } 33 | }; 34 | 35 | 36 | 37 | Java: 38 | ----- 39 | /** 40 | * Definition for singly-linked list. 41 | * public class ListNode { 42 | * int val; 43 | * ListNode next; 44 | * ListNode() {} 45 | * ListNode(int val) { this.val = val; } 46 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 47 | * } 48 | */ 49 | class Solution { 50 | public ListNode deleteDuplicates(ListNode head) { 51 | if(head == null || head.next == null) return head; 52 | ListNode next = head.next; 53 | 54 | if(next.val == head.val){ 55 | while(next != null && next.val == head.val) next = next.next; 56 | return deleteDuplicates(next); 57 | } else { 58 | head.next = deleteDuplicates(next); 59 | return head; 60 | } 61 | } 62 | } 63 | 64 | 65 | 66 | 67 | Python3: 68 | -------- 69 | # Definition for singly-linked list. 70 | # class ListNode: 71 | # def __init__(self, val=0, next=None): 72 | # self.val = val 73 | # self.next = next 74 | class Solution: 75 | def deleteDuplicates(self, head: ListNode) -> ListNode: 76 | if head == None or head.next == None: return head 77 | next = head.next 78 | 79 | if next.val == head.val: 80 | while next != None and next.val == head.val: next = next.next 81 | return self.deleteDuplicates(next) 82 | else: 83 | head.next = self.deleteDuplicates(next) 84 | return head 85 | 86 | 87 | -------------------------------------------------------------------------------- /123_Best_Time_to_Buy_and_Sell_Stock_III: -------------------------------------------------------------------------------- 1 | Leetcode 123: Best Time to Buy and Sell Stock III 2 | Detailed video Explanation: https://youtu.be/0FKn0FSIQYE 3 | ================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int n = prices.size(); 12 | if(n < 2) return 0; 13 | 14 | int p1 = prices[0], p2 = prices[n-1]; 15 | vector profit1(n, 0); 16 | vector profit2(n, 0); 17 | 18 | for(int i = 1; i < n; ++i){ 19 | profit1[i] = max(profit1[i-1], prices[i] - p1); 20 | p1 = min(p1, prices[i]); 21 | 22 | int j = n-1-i; 23 | profit2[j] = max(profit2[j+1], p2 - prices[j]); 24 | p2 = max(p2, prices[j]); 25 | } 26 | 27 | int profit = 0; 28 | for(int i = 0; i < n; ++i) 29 | profit = max(profit, profit1[i] + profit2[i]); 30 | return profit; 31 | } 32 | }; 33 | 34 | 35 | Java: 36 | ---- 37 | class Solution { 38 | public int maxProfit(int[] prices) { 39 | int n = prices.length; 40 | if(n < 2) return 0; 41 | 42 | int p1 = prices[0], p2 = prices[n-1]; 43 | int[] profit1 = new int[n]; 44 | int[] profit2 = new int[n]; 45 | 46 | for(int i = 1; i < n; ++i){ 47 | profit1[i] = Math.max(profit1[i-1], prices[i] - p1); 48 | p1 = Math.min(p1, prices[i]); 49 | 50 | int j = n-1-i; 51 | profit2[j] = Math.max(profit2[j+1], p2 - prices[j]); 52 | p2 = Math.max(p2, prices[j]); 53 | } 54 | 55 | int profit = 0; 56 | for(int i = 0; i < n; ++i) 57 | profit = Math.max(profit, profit1[i] + profit2[i]); 58 | return profit; 59 | } 60 | } 61 | 62 | 63 | Python3: 64 | ------- 65 | class Solution: 66 | def maxProfit(self, prices: List[int]) -> int: 67 | n = len(prices) 68 | if n < 2: return 0 69 | 70 | p1, p2 = prices[0], prices[n-1] 71 | profit1, profit2 = [0]*n, [0]*n 72 | 73 | for i in range(1, n): 74 | profit1[i] = max(profit1[i-1], prices[i] - p1) 75 | p1 = min(p1, prices[i]) 76 | 77 | j = n-1-i 78 | profit2[j] = max(profit2[j+1], p2 - prices[j]) 79 | p2 = max(p2, prices[j]) 80 | 81 | profit = 0; 82 | for i in range(n): 83 | profit = max(profit, profit1[i] + profit2[i]) 84 | return profit 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /1022_Sum_of_Root_To_Leaf_Binary_Numbers: -------------------------------------------------------------------------------- 1 | Leetcode 1022: Sum of Root To Leaf Binary Numbers 2 | Detailed video explanation: https://youtu.be/Wj4mLZ7XW0A 3 | ================================================== 4 | 5 | 6 | C++: 7 | ---- 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | int sumRootToLeaf(TreeNode* root, int sum) { 21 | if(!root) return 0; 22 | sum = (sum << 1) + root->val; 23 | if(!root->left && !root->right) return sum; 24 | return sumRootToLeaf(root->left, sum) + sumRootToLeaf(root->right, sum); 25 | } 26 | public: 27 | int sumRootToLeaf(TreeNode* root) { 28 | return sumRootToLeaf(root, 0); 29 | } 30 | }; 31 | 32 | 33 | 34 | 35 | Java: 36 | ----- 37 | /** 38 | * Definition for a binary tree node. 39 | * public class TreeNode { 40 | * int val; 41 | * TreeNode left; 42 | * TreeNode right; 43 | * TreeNode() {} 44 | * TreeNode(int val) { this.val = val; } 45 | * TreeNode(int val, TreeNode left, TreeNode right) { 46 | * this.val = val; 47 | * this.left = left; 48 | * this.right = right; 49 | * } 50 | * } 51 | */ 52 | class Solution { 53 | private int sumRootToLeaf(TreeNode root, int sum) { 54 | if(root == null) return 0; 55 | sum = (sum << 1) + root.val; 56 | if(root.left == null && root.right == null) return sum; 57 | return sumRootToLeaf(root.left, sum) + sumRootToLeaf(root.right, sum); 58 | } 59 | public int sumRootToLeaf(TreeNode root) { 60 | return sumRootToLeaf(root, 0); 61 | } 62 | } 63 | 64 | 65 | 66 | 67 | Python3: 68 | ------- 69 | # Definition for a binary tree node. 70 | # class TreeNode: 71 | # def __init__(self, val=0, left=None, right=None): 72 | # self.val = val 73 | # self.left = left 74 | # self.right = right 75 | class Solution: 76 | def sumRootToLeaf(self, root: TreeNode) -> int: 77 | def sumRootToLeaf(root, sum): 78 | if root == None: return 0 79 | sum = (sum << 1) + root.val 80 | if root.left == None and root.right == None: return sum 81 | return sumRootToLeaf(root.left, sum) + sumRootToLeaf(root.right, sum) 82 | 83 | return sumRootToLeaf(root, 0) 84 | 85 | 86 | -------------------------------------------------------------------------------- /290_Word_Pattern: -------------------------------------------------------------------------------- 1 | Leetcode 290: Word Pattern 2 | Detailed video explanation: https://youtu.be/cwBUZKqH6sw 3 | ========================================== 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | bool wordPattern(string pattern, string str) { 11 | unordered_map char_map; 12 | unordered_map word_map; 13 | 14 | stringstream s(str); 15 | string word; 16 | int n = pattern.size(), i = 0; 17 | 18 | while(s >> word){ 19 | if(i == n) return false; 20 | char c = pattern[i]; 21 | if(char_map.count(c) != word_map.count(word)) return false; 22 | if(char_map.count(c)){ 23 | if( (word_map[word] != c) || (char_map[c] != word)) return false; 24 | } else { 25 | char_map.insert({c, word}); 26 | word_map.insert({word, c}); 27 | } 28 | i++; 29 | } 30 | return i == n; 31 | } 32 | }; 33 | 34 | 35 | 36 | Java: 37 | ----- 38 | class Solution { 39 | public boolean wordPattern(String pattern, String str) { 40 | Map char_map = new HashMap(); 41 | Map word_map = new HashMap(); 42 | 43 | int n = pattern.length(), i = 0; 44 | String[] words = str.split(" "); 45 | if(n != words.length) return false; 46 | 47 | while(i < n){ 48 | char c = pattern.charAt(i); 49 | String word = words[i]; 50 | if(char_map.containsKey(c) != word_map.containsKey(word)) return false; 51 | if(char_map.containsKey(c)){ 52 | if( (word_map.get(word) != c) || !(char_map.get(c).equals(word)) ) return false; 53 | } else { 54 | char_map.put(c, word); 55 | word_map.put(word, c); 56 | } 57 | i++; 58 | } 59 | return i == n; 60 | } 61 | } 62 | 63 | 64 | 65 | Python3: 66 | -------- 67 | class Solution: 68 | def wordPattern(self, pattern: str, str: str) -> bool: 69 | char_map, word_map = {}, {} 70 | n, i = len(pattern), 0 71 | words = str.split(" ") 72 | if n != len(words): return False 73 | 74 | while i < n: 75 | c, word = pattern[i], words[i] 76 | if (c in char_map) != (word in word_map): return False 77 | if c in char_map: 78 | if (word_map[word] != c) or (char_map[c] != word): return False 79 | else: 80 | char_map[c] = word 81 | word_map[word] = c 82 | i += 1 83 | return i == n 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /84_Largest_Rectangle_in_Histogram: -------------------------------------------------------------------------------- 1 | Leetcode 84: Largest Rectangle in Histogram 2 | Detailed video explanation: https://youtu.be/2JPo2JnaJeo 3 | ================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | public: 10 | int largestRectangleArea(vector& heights) { 11 | int n = heights.size(); 12 | vector sL(n, 0); 13 | vector sR(n, 0); 14 | sL[0] = -1, sR[n-1] = n; 15 | for(int i = 1; i < n; ++i){ 16 | int idx = i-1; 17 | while(idx >= 0 && heights[idx] >= heights[i]) 18 | idx = sL[idx]; 19 | sL[i] = idx; 20 | } 21 | for(int i = n-2; i >= 0; --i){ 22 | int idx = i+1; 23 | while(idx < n && heights[idx] >= heights[i]) 24 | idx = sR[idx]; 25 | sR[i] = idx; 26 | } 27 | int result = 0; 28 | for(int i = 0; i < n; ++i) 29 | result = max(result, heights[i]*(sR[i] - sL[i] - 1)); 30 | return result; 31 | } 32 | }; 33 | 34 | 35 | 36 | 37 | Java: 38 | ----- 39 | class Solution { 40 | public int largestRectangleArea(int[] heights) { 41 | int n = heights.length; 42 | int[] sL = new int[n]; 43 | int[] sR = new int[n]; 44 | sL[0] = -1; sR[n-1] = n; 45 | for(int i = 1; i < n; ++i){ 46 | int idx = i-1; 47 | while(idx >= 0 && heights[idx] >= heights[i]) 48 | idx = sL[idx]; 49 | sL[i] = idx; 50 | } 51 | for(int i = n-2; i >= 0; --i){ 52 | int idx = i+1; 53 | while(idx < n && heights[idx] >= heights[i]) 54 | idx = sR[idx]; 55 | sR[i] = idx; 56 | } 57 | int result = 0; 58 | for(int i = 0; i < n; ++i) 59 | result = Math.max(result, heights[i]*(sR[i] - sL[i] - 1)); 60 | return result; 61 | } 62 | } 63 | 64 | 65 | 66 | 67 | Python3: 68 | -------- 69 | class Solution: 70 | def largestRectangleArea(self, heights: List[int]) -> int: 71 | n = len(heights) 72 | sL, sR = [0]*n, [0]*n 73 | sL[0], sR[n-1] = -1, n 74 | for i in range(1, n): 75 | idx = i-1; 76 | while idx >= 0 and heights[idx] >= heights[i]: 77 | idx = sL[idx] 78 | sL[i] = idx 79 | for i in range(n-2, -1, -1): 80 | idx = i+1; 81 | while idx < n and heights[idx] >= heights[i]: 82 | idx = sR[idx] 83 | sR[i] = idx 84 | 85 | result = 0 86 | for i in range(0, n): 87 | result = max(result, heights[i]*(sR[i] - sL[i] - 1)) 88 | return result 89 | -------------------------------------------------------------------------------- /497_Random_Point_in_Non-overlapping_Rectangles: -------------------------------------------------------------------------------- 1 | Leetcode 497: Random Point in Non-overlapping Rectangles 2 | Detailed video explanation: https://youtu.be/8kwPXbTMSnk 3 | ========================================================= 4 | 5 | 6 | C++: 7 | ---- 8 | class Solution { 9 | int num_pts; 10 | vector rect_cum_count; 11 | vector> rects; 12 | public: 13 | Solution(vector>& rects) { 14 | num_pts = 0; 15 | this->rects = rects; 16 | for(vector& rect: rects){ 17 | num_pts += (rect[2] - rect[0] + 1)*(rect[3] - rect[1] + 1); 18 | rect_cum_count.push_back(num_pts); 19 | } 20 | } 21 | 22 | vector pick() { 23 | int pt_idx = rand() % num_pts; 24 | int l = 0, r = rects.size()-1; 25 | while(l < r){ 26 | int mid = l + (r-l)/2; 27 | if(rect_cum_count[mid] <= pt_idx) l = mid+1; 28 | else r = mid; 29 | } 30 | // l = rectangle index 31 | vector& rect = rects[l]; 32 | int x_pts = rect[2] - rect[0] + 1; 33 | int y_pts = rect[3] - rect[1] + 1; 34 | int pts_in_rect = x_pts*y_pts; 35 | int pt_start = rect_cum_count[l] - pts_in_rect; 36 | int offset = pt_idx - pt_start; 37 | return {rect[0] + offset%x_pts, rect[1] + offset/x_pts}; 38 | } 39 | }; 40 | 41 | /** 42 | * Your Solution object will be instantiated and called as such: 43 | * Solution* obj = new Solution(rects); 44 | * vector param_1 = obj->pick(); 45 | */ 46 | 47 | 48 | Python3: 49 | ------- 50 | class Solution: 51 | 52 | def __init__(self, rects: List[List[int]]): 53 | self.num_pts = 0 54 | self.rects = rects 55 | self.rect_cum_count = [] 56 | for rect in rects: 57 | self.num_pts += (rect[2] - rect[0] + 1)*(rect[3] - rect[1] + 1) 58 | self.rect_cum_count.append(self.num_pts) 59 | 60 | def pick(self) -> List[int]: 61 | pt_idx = random.randint(0, self.num_pts-1) 62 | l, r = 0, len(self.rects)-1 63 | while l < r: 64 | mid = l + (r-l)//2 65 | if self.rect_cum_count[mid] <= pt_idx: l = mid+1 66 | else: r = mid 67 | # l = rectangle index 68 | rect = self.rects[l] 69 | x_pts = rect[2] - rect[0] + 1 70 | y_pts = rect[3] - rect[1] + 1 71 | pts_in_rect = x_pts*y_pts 72 | pt_start = self.rect_cum_count[l] - pts_in_rect 73 | offset = pt_idx - pt_start; 74 | return [rect[0] + offset%x_pts, rect[1] + offset//x_pts] 75 | 76 | 77 | # Your Solution object will be instantiated and called as such: 78 | # obj = Solution(rects) 79 | # param_1 = obj.pick() 80 | 81 | 82 | --------------------------------------------------------------------------------