├── .github ├── ISSUE_TEMPLATE │ └── submit-a-leetcode-problem.md └── workflows │ └── leetcodeChecker.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── LeetCode ├── 0001_Two_Sum.py ├── 0002_Add_Two_Numbers.py ├── 0003_Longest_Substring_Without_Repeating_Characters.py ├── 0004_Median_of_Two_Sorted_Array.py ├── 0005_Longest_Palindromic_Substring.py ├── 0006_ZigZag_Conversion.py ├── 0007_Reverse_Integer.py ├── 0008_String_to_Integer.py ├── 0009_Palindrom_Number.py ├── 0010_Regular_Expression_Matching.py ├── 0011 - Container With Most Water.py ├── 0012_Integer_to_Roman.py ├── 0013_Roman to Integer.py ├── 0014_Longest_common_Prefix.py ├── 0015_3Sum.py ├── 0016_3sum_closest.py ├── 0017_Letter_Combinations_of_a_Phone_Number.py ├── 0018_4sum.py ├── 0019_Remove_nth_node_from_end_of_list.py ├── 0020_Valid_Parentheses.py ├── 0021_Merge_Two_Sorted_Lists.py ├── 0022_GenerateParenthesis.py ├── 0023_Merge_k_Sorted_Lists.py ├── 0024_ Swap_Nodes_in_Pairs.py ├── 0025_Reverse_Node_in_K_Groups.py ├── 0026_remove_duplicates_from_sorted_array.py ├── 0027_Remove_Element.py ├── 0028_strStr.py ├── 0029_DivideTwoIntegers.py ├── 0030_Substring_with_Concatenation_of_All_Words.py ├── 0031_Next_Permutation.py ├── 0032_Longest_Valid_Parentheses.py ├── 0033_Search_Rotated_Sort_Array.py ├── 0034_find_first_and_last_position_of_element_in_sorted_array.py ├── 0035_Search_Insert_Position.py ├── 0036_Valid_Sudoku.py ├── 0037_Sudoku_Solver.py ├── 0038 _Count_and_Say.py ├── 0039_Combination_Sum.py ├── 0040_Combination_Sum_2.py ├── 0041_find_missing_positive.py ├── 0042_Trapping_Rain_Water.py ├── 0043_Multiply Strings.py ├── 0044_Wildcard_Matching.py ├── 0045_Jump_Game_II.py ├── 0047_Permutations II.py ├── 0048_Rotate_Image.py ├── 0049_Group_Anagrams.py ├── 0050_Powxn.py ├── 0051_N-Queen_1.py ├── 0052_N_Queens_2.py ├── 0053_Maximum_Subarray.py ├── 0054_Spiral_Matrix.py ├── 0055_jump_game.py ├── 0056_Merge_Intervals.py ├── 0057_Insert_Interval.py ├── 0058_Length_of_Last_Word.py ├── 0059_Spiral_Matrix_II.py ├── 0060 - Permutation_Sequence.py ├── 0061_Rotate_List.py ├── 0062_Unique_Paths.py ├── 0063_UniquePathsII.py ├── 0064_Minimum_Path_Sum.py ├── 0065_Valid_Number.py ├── 0066_Plus_One.py ├── 0067_Add_Binary.py ├── 0069 _ Sqrt(x).py ├── 0070_Climbing_Stairs.py ├── 0071_Simplify_Path.py ├── 0072_Edit_Distance.py ├── 0073_Set Matrix Zeroes.py ├── 0075_Sort_Colors.py ├── 0076_Minimum_Window_Substring.py ├── 0077_Combinations.py ├── 0078_Subsets.py ├── 0079_Word_Search.py ├── 0080_Remove_Duplicates_from_Sorted_Array_II.py ├── 0081_Search_in_Rotated_Sorted_Array II.py ├── 0082_Remove_Duplicates_from_Sorted_List_II.py ├── 0083_Remove_Dupticates_from_Sorted_List.py ├── 0084_Largest_Rectangle_in_Histogram.py ├── 0086_Partition_List.py ├── 0087_Scramble_String.py ├── 0088_Merge_Sorted_Array.py ├── 0089_Gray_code.py ├── 0090_Subsets_II.py ├── 0091_Decode_Ways.py ├── 0093_Restore_IP_address.py ├── 0094_Binary_Tree_Inorder_Traversal.py ├── 0098_Validate_Binary_Search_Tree.py ├── 0100_Same_Tree.py ├── 0101_Symmetric_Tree.py ├── 0102_Binary_Tree_Level_Order_Traversal.py ├── 0103_Binary_Tree_Zigzag_Level_Order_Traversal.py ├── 0104_Maximum_Depth_of_Binary_Tree.py ├── 0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py ├── 0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py ├── 0107_Binary_Tree_Level_Order_Traversal_II.py ├── 0110_balanced_binary_tree.py ├── 0111_Minimum_Depth_of_Binary_Tree.py ├── 0112_Path_Sum.py ├── 0118_pascal_triangle.py ├── 0119_Pascal_Triangle2.py ├── 0120_minimum_path_triangle.py ├── 0121_Best_Time_to_Buy_and_Sell_Stock.py ├── 0123_Best_Time_To_Buy_And_Sell_Stock_III.py ├── 0125_Valid_Palindrome.py ├── 0126_Word_Ladder_II.py ├── 0134_Gas_Station.py ├── 0136_Single_Number.py ├── 0137_Single_Number_II.py ├── 0138_Copy_List_with_Random_Pointer.py ├── 0139_Word_Break.py ├── 0141_Linked_List_Cycle.py ├── 0144_Binary_Tree_Preorder_Traversal.py ├── 0145_binary_tree_postorder_traversal.py ├── 0146_LRU_Cache.py ├── 0151_Reverse_Words_in_a_String.py ├── 0155_Min_stack.py ├── 0165_Compare_Version_Numbers.py ├── 0167_Two_Sum_II.py ├── 0169_Majority_Element.py ├── 0174_Dungeon_Game.py ├── 0189_Rotate_Array.py ├── 0190_Reverse_bits.py ├── 0191_Number_of_1_bits.py ├── 0198_House_Robber.py ├── 0200_Number_of_Islands.py ├── 0202_Happy_Number.py ├── 0203_Remove_Linked_List_Elements.py ├── 0206_Reverse_Linked_List.py ├── 0208_Implement_Trie.py.py ├── 0212_Word_search_II.py ├── 0213_House_robber2.py ├── 0215_Kth_Largest_Element_In_An_Array.py ├── 0216_Combination_Sum_III.py ├── 0217_Contains_Duplicate.py ├── 0219_ContainsDuplicateII.py ├── 0220_Contains_Duplicate_III.py ├── 0222_Count_Complete_Tree_Nodes.py ├── 0231_Power_Of_Two.py ├── 0233_Number_of_Digit_One.py ├── 0234_Palindrome_Linked_List_.py ├── 0237_Delete_Node_in_a_Linked_List.py ├── 0242_Valid_anagrams.py ├── 0257_Binary_Tree_Paths.py ├── 0258_Add_Digits.py ├── 0260_Single_Number_III.py ├── 0268_Missing_Number.py ├── 0273_Integer_to_English_Words.py ├── 0274_H_Index.py ├── 0278_First_Bad_Version.py ├── 0279-PerfectSquares.py ├── 0283_Move_Zeroes.py ├── 0289_Game_of_Life.py ├── 0292_Nim_Game.py ├── 0299_Bulls_and_Cows.py ├── 0319_BulbSwitcher.py ├── 0326_Power_Of_Three.py ├── 0337_House_Robber_III.py ├── 0338_Counting_Bits.py ├── 0342_Power_Of_Four.py ├── 0343_Integer_Break.py ├── 0347_Top_K_Frequent_Elements.py ├── 0367_ValidPerfectSquare.py ├── 0368_Largest_Divisible_Subset.py ├── 0371_sum_of_two_integers.py ├── 0374_Guess_Number_Higher_or_Lower ├── 0383_RansomNote.py ├── 0389_FindTheDifference.py ├── 0401_Binary_Watch_.py ├── 0412_Fizz Buzz.py ├── 0414_Third_Maximum_Number.py ├── 0437_Path_Sum_III.py ├── 0443_String_Compression.py ├── 0448-Find-All-Numbers-Disappeared-in-an-Array.py ├── 0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py ├── 0456_Find_132_Pattern.py ├── 0459_Repeated_Substring_Pattern.py ├── 0483_Smallest_Good_Base.py ├── 0500_Keyboard_Row.py ├── 0521_Longest_Uncommon_Subsequence_I.py ├── 0532_K_diff_Pairs_in_an_Array.py ├── 0537_Complex_Number_Multiplication.py ├── 0551_ Student_Attendance_Record_I.py ├── 0561_Array_Partition_I.py ├── 0567_Permutations_in_String.py ├── 0589_Nary_Tree_Preorder_Traversal.py ├── 0599_Minimum_Index_Sum_of_Two_Lists.py ├── 0617_Merge_Two_Binary_Trees.py ├── 0647_Palindromic_Substrings.py ├── 0654_Maximum_Binary_Tree.py ├── 0686_Repeated_String_Match.py ├── 0701_Insert_into_a_Binary_Search_Tree.py ├── 0728_Self_Dividing_Numbers.py ├── 0741_CherryPickup.py ├── 0746_Min_Cost_Climbing_Stairs.py ├── 0763_Partition_Labels.py ├── 0771_Jewels_and_Stones.py ├── 0777_Swap_Adjacent_in_LR String.py ├── 0829_Consecutive_Numbers_Sum.py ├── 0832_Flipping_an_Image.py ├── 0859_Buddy_String.py ├── 0867_Transpose_Matrix.py ├── 0888_Fair_Candy_Swap.py ├── 0891_Sum_of_Subsequence_Widths.py ├── 0929_Unique_Email_Addresses.py ├── 0933_Number_of_Recent_Calls.py ├── 0938_Range_Sum_of_BST.py ├── 0942_DI_String_Match.py ├── 0949_Largest_Time_for_Given_Digits.py ├── 0973_ K_Closest_Points_to_Origin.py ├── 0980_Unique_Paths_III.py ├── 0995_Minimum_Number_of_K_Consecutive_Bit_Flips.py ├── 0997_Find_The_Town_Judge.py ├── 1002_Find_Common_Character.py ├── 1009_Complement_of_base_10_integer.py ├── 1018_Binary_Tree_Prefix_Divisible_By_5.py ├── 1023_Camelcase_Matching.py ├── 1046_Last Stone Weight.py ├── 1053_Previous_Permutation_With_One_Swap.py ├── 1103_Distributing_Candies_to_people.py ├── 1108_Defanging_an_IP_Address.py ├── 1137_N_th_Tribonacci_Number.py ├── 1160_FindWordsThatCanBeFormedByCharacters.py ├── 1189_Maximum_Number_of_Balloons.py ├── 1219_path_with_maximum_gold.py ├── 1221_Split_ a_String_in_Balanced_Strings.py ├── 1227_Airplane_Seat_Assignment_Probability.py ├── 1249_Minimum_Remove_to_Make_Valid_Parentheses.py ├── 1250_Check_If_It_Is_a_Good_Array.py ├── 1252_Cells_with_Odd_Values_in_a_Matrix.py ├── 1276_Number_of_Burgers_with_No_Waste_of_Ingredients.py ├── 1281_Subtract_the_Product_and_Sum_of_Digits_of_an_Integer.py ├── 1282_Group_People_Given_the_Group_Size_They_Belong_To.py ├── 1288_Remove_Covered_Intervals.py ├── 1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py ├── 1340_Jump_Game_V.py ├── 1346_Check_if_N_and_its_Double_Exist.py ├── 1351_Count_Negative_Numbers_in_Sorted_Matrix.py ├── 1363_Largest_Multiple_of_Three.py ├── 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py ├── 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py ├── 1380_Lucky_Numbers_in_a_Matrix.py ├── 1402_Reducing_Dishes.py ├── 1431_Kids_With_the_Greatest_Number_of_Candies.py ├── 1436_Destination_City.py ├── 1441_build_an_array_with_stack_operations.py ├── 1446_consecutive_characters.py ├── 1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py ├── 1464_Maximum_Product_Of_Two_Elements_In_An_Array.py ├── 1470_Shuffle_The_Array.py ├── 1499_Max_Value_of_Equation.py ├── 1512_Number_of_Good_Pairs.py ├── 1518_Water_Bottles.py ├── 1544_Make_string_great.py ├── 1550_Three_Consecutive_Odds.py ├── 1556_Thousand_Separator.py ├── 1559_Detect_Cycles_In_2D_Grid.py ├── 1561_Maximum_Number_of_Coins_You_Can_Get.py ├── 1582_SpecialPositionsInABinaryMatrix.py ├── 1588_SumOfAllOddLengthSubarrays.py ├── 1589-maximum-sum-obtained-of-any-permutation.py ├── 1592_Rearrange_Spaces_Between_Words.py ├── 1598_Crawler_Log_Folder.py ├── 1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py ├── 1603_Design_Parking_System.py ├── 1604_Alert_Using_Same_Key_Card_Three_or_More_Times_in_a_One_Hour_Period.py ├── 1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py ├── 1606_Find_Servers_That_Handled_Most_Number_of_Requests.py ├── 1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py └── 1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── leetcodeChecker.py └── requirements.txt /.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Submit a LeetCode Problem 3 | about: Use this Template to submit a new LeetCode Problem 4 | title: 00## - LeetCode Problem Title 5 | labels: 'hacktoberfest' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Description of the Problem 11 | You may copy that from LeetCode 12 | 13 | ## Code 14 | ``` 15 | Code 16 | ``` 17 | 18 | ## Link To The LeetCode Problem 19 | [LeetCode](https://leetcode.com/) 20 | -------------------------------------------------------------------------------- /.github/workflows/leetcodeChecker.yml: -------------------------------------------------------------------------------- 1 | name: py 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: checkout 12 | uses: actions/checkout@v2 13 | - name: setup python 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: 3.8 17 | - name: Install dependencies 18 | run: | 19 | python -m pip install --upgrade pip 20 | pip install -r requirements.txt 21 | - name: run python 22 | run: | 23 | python leetcodeChecker.py 24 | env: 25 | GITHUB_ACCESS_TOKEN: ${{ github.TOKEN }} 26 | REPO_NAME: ${{ github.repository }} 27 | PR_NUMBER: ${{ github.event.pull_request.number }} 28 | LEETCODE_CSRF_TOKEN: ${{ secrets.LEETCODE_CSRF_TOKEN }} 29 | LEETCODE_SESSION_TOKEN: ${{ secrets.LEETCODE_SESSION }} 30 | 31 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | ## Folders and Files 4 | Please make sure your file is in the `LeetCode`-Folder and Named like this: 5 | `0001_TwoSum.py` -> 4-digit Number of the LeetCode Issue, Underscore, LeetCodeName 6 | 7 | ### Opening Issues 8 | When you open an issue, please make sure the Problem is not already implemented (Look at Code/Leetcode for the Problemnumber). 9 | Opened Issues by existing Problem will be closed & PR made to this Issue marked as **spam** 10 | The Contributer who opened an issue will be assigned prefered to the issue. If there is no PR within about 7 Days the issue will be assigned to another Contributer. 11 | 12 | ### Pull Requests 13 | Only Pull Requests **joined with an Issue** and matching the **naming-conventions** (See Folders and Files) will be merged! 14 | If there is no Issue joined in the PR your PR will be labeld as **spam** and closed. 15 | If your code don't passes the Check on LeetCode.com your PR will be labled as **"invalid"** and the Issue stays open for the next PR! 16 | If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! 17 | 18 | ## Which PR's will be accepted? 19 | * Ones you are assigned to 20 | * Your PR has to link the Issue 21 | * Your Solution must be correct - you can check ist on LeetCode (submit) if it works on different test-cases 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Viktoria Jechsmayr 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeetCode/0001_Two_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, nums, target): 3 | if len(nums) <= 1: 4 | return False 5 | buff_dict = {} 6 | for i in range(len(nums)): 7 | if nums[i] in buff_dict: 8 | return [buff_dict[nums[i]], i] 9 | else: 10 | buff_dict[target - nums[i]] = i -------------------------------------------------------------------------------- /LeetCode/0002_Add_Two_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addTwoNumbers(self, l1, l2 ,c = 0): 3 | val = l1.val + l2.val + c 4 | c = val // 10 5 | ret = ListNode(val % 10 ) 6 | 7 | if (l1.next != None or l2.next != None or c != 0): 8 | if l1.next == None: 9 | l1.next = ListNode(0) 10 | if l2.next == None: 11 | l2.next = ListNode(0) 12 | ret.next = self.addTwoNumbers(l1.next,l2.next,c) 13 | return ret -------------------------------------------------------------------------------- /LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | map_chars = {} 4 | longest = 0 5 | j = 0 6 | 7 | for i in range(0, len(s)): 8 | if s[i] in map_chars.keys(): 9 | j = max(j, map_chars[s[i]] + 1) 10 | 11 | longest = max(longest, i - j + 1) 12 | map_chars[s[i]] = i 13 | 14 | return longest -------------------------------------------------------------------------------- /LeetCode/0004_Median_of_Two_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: float 7 | """ 8 | i1 = 0 9 | i2 = 0 10 | num1 = 0 11 | num2 = 0 12 | len1 = len(nums1) 13 | len2 = len(nums2) 14 | len4 = len1 + len2 15 | len3 = int(len4 / 2) + 1 16 | for x in range(len3): 17 | if len1 > i1 and len2 > i2: 18 | if nums1[i1] <= nums2[i2]: 19 | num1 = num2 20 | num2 = nums1[i1] 21 | i1 = i1 + 1 22 | else: 23 | num1 = num2 24 | num2 = nums2[i2] 25 | i2 = i2 + 1 26 | elif len1 > i1: 27 | num1 = num2 28 | num2 = nums1[i1] 29 | i1 = i1 + 1 30 | else: 31 | num1 = num2 32 | num2 = nums2[i2] 33 | i2 = i2 + 1 34 | 35 | if len4 % 2 == 0: 36 | return (num1 + num2)/2 37 | else: 38 | return float(num2) -------------------------------------------------------------------------------- /LeetCode/0005_Longest_Palindromic_Substring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem:- 3 | 4 | Given a string s, find the longest palindromic substring in s. 5 | You may assume that the maximum length of s is 1000. 6 | 7 | Example 1: 8 | Input: "babad" 9 | Output: "bab" 10 | Note: "aba" is also a valid answer. 11 | 12 | ''' 13 | 14 | class Solution: 15 | def longestPalindrome(self, s: str) -> str: 16 | res = "" 17 | resLen = 0 18 | 19 | for i in range(len(s)): 20 | # odd length 21 | l, r = i, i 22 | while l >= 0 and r < len(s) and s[l] == s[r]: 23 | if (r - l + 1) > resLen: 24 | res = s[l:r + 1] 25 | resLen = r - l + 1 26 | l -= 1 27 | r += 1 28 | 29 | # even length 30 | l, r = i, i + 1 31 | while l >= 0 and r < len(s) and s[l] == s[r]: 32 | if (r - l + 1) > resLen: 33 | res = s[l:r + 1] 34 | resLen = r - l + 1 35 | l -= 1 36 | r += 1 37 | 38 | return res -------------------------------------------------------------------------------- /LeetCode/0006_ZigZag_Conversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param {string} s 3 | # @param {integer} numRows 4 | # @return {string} 5 | def convert(self, s, numRows): 6 | 7 | if numRows == 1: 8 | return s 9 | 10 | rows = ["" for i in range(numRows)] 11 | 12 | direction = -1 13 | row = 0 14 | for i in range(len(s)): 15 | 16 | rows[row]+=s[i] 17 | if (row == 0 or row==numRows-1): 18 | direction *= -1 19 | row+=direction 20 | 21 | return "".join(rows) 22 | -------------------------------------------------------------------------------- /LeetCode/0007_Reverse_Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | if x >= 2**31-1 or x <= -2**31: return 0 4 | else: 5 | strg = str(x) 6 | if x >= 0 : 7 | revst = strg[::-1] 8 | else: 9 | temp = strg[1:] 10 | temp2 = temp[::-1] 11 | revst = "-" + temp2 12 | if int(revst) >= 2**31-1 or int(revst) <= -2**31: return 0 13 | else: return int(revst) -------------------------------------------------------------------------------- /LeetCode/0008_String_to_Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myAtoi(self, s: str) -> int: 3 | INT_MAX = (1 << 31) - 1 4 | INT_MIN = -(1 << 31) 5 | 6 | ret = 0 7 | s = s.strip() 8 | 9 | if s == "": 10 | return ret 11 | 12 | negate = -1 if s[0] == '-' else 1 13 | 14 | if s[0] in ('+', '-'): 15 | s = s[1::] 16 | 17 | for c in s: 18 | if not '0' <= c <= '9': 19 | break 20 | 21 | ret = ret * 10 + ord(c) - ord('0') 22 | 23 | ret *= negate 24 | ret = min(max(ret, INT_MIN), INT_MAX) 25 | 26 | return ret -------------------------------------------------------------------------------- /LeetCode/0009_Palindrom_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | if x > 0 and x < 10: 4 | return True 5 | 6 | copyNumber = x 7 | newNumber = 0 8 | while copyNumber > 0: 9 | newNumber = int(newNumber * 10 + (copyNumber % 10)) 10 | copyNumber = int(copyNumber / 10) 11 | 12 | return newNumber == x -------------------------------------------------------------------------------- /LeetCode/0010_Regular_Expression_Matching.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s: str, p: str) -> bool: 3 | string, pattern = [], [] 4 | string[:0], pattern[:0] = s, p 5 | string.insert(0, 0) 6 | pattern.insert(0, 0) 7 | s, p = len(string), len(pattern) 8 | dp = [[False for _ in range(p)] for __ in range(s)] 9 | dp[0][0] = True 10 | for i in range(p): 11 | if pattern[i] is '*' and dp[0][i-2]: dp[0][i] = True 12 | for i in range(1, s): 13 | for j in range(1, p): 14 | if pattern[j] is string[i] or pattern[j] is '.': 15 | dp[i][j] = dp[i-1][j-1] 16 | elif pattern[j] is '*' and (pattern[j-1] is string[i] or pattern[j-1] is '.'): 17 | dp[i][j] = dp[i][j-2] or dp[i-1][j] 18 | elif pattern[j] is '*' and not (pattern[j-1] is string[i] or pattern[j-1] is '.'): 19 | dp[i][j] = dp[i][j-2] 20 | return dp[s-1][p-1] 21 | -------------------------------------------------------------------------------- /LeetCode/0011 - Container With Most Water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | i=0 4 | j=len(height)-1 5 | a=0 6 | b=0 7 | while ia: 15 | a=b 16 | return a -------------------------------------------------------------------------------- /LeetCode/0012_Integer_to_Roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | values = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] 3 | romanNumerals = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] 4 | 5 | def intToRoman(self, num: int, ptr: int = len(values) - 1) -> str: 6 | if num == 0: 7 | return "" 8 | 9 | while True: 10 | if num >= self.values[ptr]: 11 | return self.romanNumerals[ptr] + self.intToRoman(num - self.values[ptr], ptr) 12 | else: 13 | ptr -= 1 14 | -------------------------------------------------------------------------------- /LeetCode/0013_Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | 4 | symbolValDict = { 5 | 'I':1, 6 | 'V':5, 7 | 'X':10, 8 | 'L':50, 9 | 'C':100, 10 | 'D':500, 11 | 'M':1000 12 | } 13 | 14 | 15 | i = 0 16 | finalDigit = 0 17 | while(i= nextDigit: 22 | finalDigit += firstDigit 23 | i+=1 24 | else: 25 | finalDigit += nextDigit - firstDigit 26 | i+=2 27 | else: 28 | finalDigit += firstDigit 29 | i+=1 30 | 31 | 32 | return finalDigit -------------------------------------------------------------------------------- /LeetCode/0014_Longest_common_Prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs): 3 | """ 4 | :type strs: List[str] 5 | :rtype: str 6 | """ 7 | if len(strs) == 0: 8 | return '' 9 | res = '' 10 | strs = sorted(strs) 11 | for i in strs[0]: 12 | if strs[-1].startswith(res+i): 13 | res += i 14 | else: 15 | break 16 | return res -------------------------------------------------------------------------------- /LeetCode/0015_3Sum.py: -------------------------------------------------------------------------------- 1 | def threeSum(self, nums): 2 | nums.sort() 3 | result = [] 4 | for left in range(len(nums) - 2): # renamed this to left because this will always be the leftmost pointer in the triplet 5 | if left > 0 and nums[left] == nums[left - 1]: # this step makes sure that we do not have any duplicates in our result output 6 | continue 7 | mid = left + 1 # renamed this to mid because this is the pointer that is between the left and right pointers 8 | right = len(nums) - 1 9 | while mid < right: 10 | curr_sum = nums[left] + nums[mid] + nums[right] 11 | if curr_sum < 0: 12 | mid += 1 13 | elif curr_sum > 0: 14 | right -= 1 15 | else: 16 | result.append([nums[left], nums[mid], nums[right]]) 17 | while mid < right and nums[mid] == nums[mid + 1]: # Another conditional for not calculating duplicates 18 | mid += 1 19 | while mid < right and nums[right] == nums[right - 1]: # Avoiding duplicates check 20 | right -= 1 21 | mid += 1 22 | right -= 1 23 | return result -------------------------------------------------------------------------------- /LeetCode/0016_3sum_closest.py: -------------------------------------------------------------------------------- 1 | # Import necessary dependencies 2 | import sys 3 | 4 | class Solution: 5 | def threeSumClosest(self, nums, target): 6 | # Sort the array 7 | nums.sort() 8 | # Initialize closest sum 9 | closest_sum = sys.maxsize 10 | 11 | # Starting from the first element,fix the smallest number 12 | # Implement the two pointers method in the remaining array 13 | for num in range(len(nums) - 2): 14 | # Initialize the two pointers 15 | # One pointing to the last element 16 | # the other pointing to element next to the fixed element. 17 | ptr_first, ptr_last = num + 1, len(nums) - 1 18 | 19 | # While the pointers don't cross each other 20 | while ptr_first < ptr_last: 21 | # Calculate the sum 22 | sum_temp = nums[num] + nums[ptr_first] + nums[ptr_last] 23 | 24 | # Compare against the variable closest_sum 25 | # If it is closer than the current closest_sum 26 | # Update closest sum. Also check : 27 | # If sum is greater than target, decrement ptr_last to decrease sum 28 | # Else, increment ptr_first to increase sum 29 | if abs(target - sum_temp) < abs(target - closest_sum): 30 | closest_sum = sum_temp 31 | if sum_temp > target: 32 | ptr_last = ptr_last - 1 33 | else: 34 | ptr_first = ptr_first + 1 35 | return closest_sum 36 | -------------------------------------------------------------------------------- /LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from typing import List 3 | 4 | class Solution: 5 | def letterCombinations(self, digits: str) -> List[str]: 6 | keyboard = { 7 | '2': "abc", 8 | '3': "def", 9 | '4': "ghi", 10 | '5': "jkl", 11 | '6': "mno", 12 | '7': "pqrs", 13 | '8': "tuv", 14 | '9': "wxyz", 15 | } 16 | 17 | pressed = [keyboard[c] for c in digits] 18 | 19 | return [''.join(p) for p in itertools.product(*pressed) if p != ()] -------------------------------------------------------------------------------- /LeetCode/0018_4sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fourSum(self, nums, target): 3 | def kSum(nums, target, k): 4 | res = [] 5 | if len(nums) == 0 or nums[0] * k > target or target > nums[-1] * k: 6 | return res 7 | if k == 2: 8 | return twoSum(nums, target) 9 | for i in range(len(nums)): 10 | if i == 0 or nums[i - 1] != nums[i]: 11 | for _, set in enumerate(kSum(nums[i + 1:], target - nums[i], k - 1)): 12 | res.append([nums[i]] + set) 13 | return res 14 | 15 | def twoSum(nums, target): 16 | res = [] 17 | lo, hi = 0, len(nums) - 1 18 | while (lo < hi): 19 | sum = nums[lo] + nums[hi] 20 | if sum < target or (lo > 0 and nums[lo] == nums[lo - 1]): 21 | lo += 1 22 | elif sum > target or (hi < len(nums) - 1 and nums[hi] == nums[hi + 1]): 23 | hi -= 1 24 | else: 25 | res.append([nums[lo], nums[hi]]) 26 | lo += 1 27 | hi -= 1 28 | return res 29 | 30 | nums.sort() 31 | return kSum(nums, target, 4) -------------------------------------------------------------------------------- /LeetCode/0019_Remove_nth_node_from_end_of_list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 9 | 10 | # use dummy head will make the removal of head node easier 11 | dummy_head = ListNode(-1) 12 | dummy_head.next = head 13 | 14 | # cur keeps iteration till the end 15 | # prev_of_removal traverses to the previous node of the one of being removed 16 | cur, prev_of_removal = dummy_head, dummy_head 17 | 18 | 19 | while cur.next != None: 20 | 21 | # n-step delay for prev_of_removal 22 | if n <= 0: 23 | prev_of_removal = prev_of_removal.next 24 | 25 | cur = cur.next 26 | 27 | n -=1 28 | 29 | 30 | # Remove the N-th node from end of list 31 | n_th_node = prev_of_removal.next 32 | prev_of_removal.next = n_th_node.next 33 | 34 | del n_th_node 35 | 36 | return dummy_head.next 37 | -------------------------------------------------------------------------------- /LeetCode/0020_Valid_Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | stack = [] 4 | openbrackets = ('(', '[', '{') 5 | matches = ('()', '[]', '{}') 6 | 7 | for c in s: 8 | if c in openbrackets: 9 | stack.append(c) 10 | else: 11 | if len(stack) < 1 or stack[-1] + c not in matches: 12 | return False 13 | 14 | stack.pop() 15 | 16 | return len(stack) == 0 -------------------------------------------------------------------------------- /LeetCode/0021_Merge_Two_Sorted_Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 9 | current_point = front = ListNode() 10 | 11 | while True: 12 | if l1 == None and l2 == None: 13 | break 14 | elif l1 == None: 15 | current_point.next = ListNode(l2.val) 16 | l2 = l2.next 17 | elif l2 == None: 18 | current_point.next = ListNode(l1.val) 19 | l1 = l1.next 20 | elif l1.val <= l2.val: 21 | current_point.next = ListNode(l1.val) 22 | l1 = l1.next 23 | else: 24 | current_point.next = ListNode(l2.val) 25 | l2 = l2.next 26 | 27 | current_point = current_point.next 28 | 29 | return front.next 30 | -------------------------------------------------------------------------------- /LeetCode/0022_GenerateParenthesis.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n: int) -> List[str]: 3 | def isValid(s: str) -> bool: 4 | stk = [] 5 | for b in s: 6 | if b == '(': 7 | stk.append(b) 8 | else: 9 | if stk and stk[-1] == '(': 10 | stk.pop() 11 | else: 12 | return False 13 | return stk == [] 14 | 15 | ans = [] 16 | for mask in range(1<<(2*n)): 17 | s = "" 18 | for bit in range(2*n): 19 | if mask & (1< ListNode: 3 | output = {} 4 | for node in lists: 5 | cur = node 6 | while cur: 7 | if cur.val not in output: 8 | output[cur.val] = [cur, cur] 9 | else: 10 | output[cur.val][1].next = cur 11 | output[cur.val][1] = cur 12 | cur = cur.next 13 | sorted_keys = sorted(list(output.keys())) 14 | 15 | for k in range(len(sorted_keys) - 1): 16 | output[sorted_keys[k]][1].next = output[sorted_keys[k + 1]][0] 17 | if sorted_keys: 18 | return output[sorted_keys[0]][0] 19 | else: 20 | return None 21 | -------------------------------------------------------------------------------- /LeetCode/0024_ Swap_Nodes_in_Pairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem:- 3 | 4 | Given a linked list, swap every two adjacent nodes and return its head. 5 | You may not modify the values in the list's nodes, only nodes itself may be changed. 6 | 7 | Example: 8 | - Given 1->2->3->4, you should return the list as 2->1->4->3. 9 | 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | # class ListNode: 14 | # def __init__(self, val=0, next=None): 15 | # self.val = val 16 | # self.next = next 17 | class Solution: 18 | def swapPairs(self, head: ListNode) -> ListNode: 19 | pre, pre.next = self, head 20 | while pre.next and pre.next.next: 21 | a = pre.next 22 | b = a.next 23 | pre.next, b.next, a.next = b, a, b.next 24 | pre = a 25 | return self.next 26 | 27 | 28 | -------------------------------------------------------------------------------- /LeetCode/0025_Reverse_Node_in_K_Groups.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Oct 2 00:13:21 2020 5 | 6 | @author: anjalisingh 7 | 8 | Leet Code Accepted Code 9 | """ 10 | 11 | class Node: 12 | def __init__(self, val=None): 13 | self.val = val; 14 | self.next = None 15 | 16 | class Solution: 17 | def __init__(self): 18 | self.head = None 19 | 20 | # def InsertAtBeg(self, d): 21 | # nn = Node(d) 22 | # nn.next = self.head 23 | # self.head = nn 24 | 25 | 26 | 27 | # def Print(self): 28 | # printVal = self.head 29 | # while printVal is not None: 30 | # print(printVal.val) 31 | # printVal = printVal.next 32 | 33 | def reverseKGroup(self, head, k): 34 | cnt = 0 35 | c =0 36 | curr = head 37 | next = None 38 | prev = None 39 | temp = curr 40 | while temp is not None and c int: 3 | # Here we are using each element of list as keys, same can be achieved via set but that won't be ordered 4 | nums[:] = list(dict.fromkeys(nums)) 5 | return len(nums) 6 | 7 | -------------------------------------------------------------------------------- /LeetCode/0027_Remove_Element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums: List[int], val: int) -> int: 3 | """ 4 | :type nums: list 5 | :type val: int 6 | :rtype: int (size of num) 7 | """ 8 | while val in nums: 9 | nums.remove(val) 10 | return len(nums) 11 | 12 | -------------------------------------------------------------------------------- /LeetCode/0028_strStr.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def strStr(self, haystack, needle): 3 | 4 | i = 0 5 | j = 0 6 | m = len(needle) 7 | n = len(haystack) 8 | if m ==0: 9 | return 0 10 | while i=m: 11 | if haystack[i] == needle[j]: 12 | temp = i 13 | while j= divisor: 14 | left -= div 15 | ans += Q 16 | Q+=Q 17 | div += div 18 | if left < div: 19 | Q = 1 20 | div = divisor 21 | 22 | if not negative: 23 | return min(ans,2147483647) 24 | else: 25 | return max(-ans,-2147483648) -------------------------------------------------------------------------------- /LeetCode/0030_Substring_with_Concatenation_of_All_Words.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def findSubstring(self,s, words): 4 | self.Incr = len(words[0]) 5 | self.LenWords = len(words) 6 | self.Index = 0 7 | self.m = self.Incr * self.LenWords 8 | self.Max = len(s) - self.m 9 | self.output = [] 10 | while self.Index <= self.Max : 11 | WordsCopy = words.copy() 12 | upperBound = self.Index 13 | lowerBound = upperBound + self.m 14 | for i in range(upperBound,lowerBound,self.Incr): 15 | tempStr = s[i: i + self.Incr] 16 | if tempStr in WordsCopy : 17 | WordsCopy.remove(tempStr) 18 | else: 19 | break 20 | if WordsCopy == [] : 21 | self.output.append(self.Index) 22 | self.Index += 1 23 | return self.output 24 | 25 | 26 | -------------------------------------------------------------------------------- /LeetCode/0031_Next_Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextPermutation(self, nums: List[int]) -> None: 3 | i = j = len(nums)-1 4 | while i > 0 and nums[i-1] >= nums[i]: 5 | i -= 1 6 | if i == 0: # nums are in descending order 7 | nums.reverse() 8 | return 9 | k = i - 1 # find the last "ascending" position 10 | while nums[j] <= nums[k]: 11 | j -= 1 12 | nums[k], nums[j] = nums[j], nums[k] 13 | l, r = k+1, len(nums)-1 # reverse the second part 14 | while l < r: 15 | nums[l], nums[r] = nums[r], nums[l] 16 | l +=1 ; r -= 1 -------------------------------------------------------------------------------- /LeetCode/0032_Longest_Valid_Parentheses.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict 2 | 3 | class Solution: 4 | def _score(self, position: List[int], state: Dict[int,bool]) -> List[int]: 5 | score = 0 6 | scores = list() 7 | for pos in position: 8 | matched = state.get(pos) 9 | if not matched: 10 | scores.append(score) 11 | score = 0 12 | 13 | else: 14 | score = score + 2 15 | 16 | scores.append(score) 17 | 18 | return scores 19 | 20 | def longestValidParentheses(self, s: str) -> int: 21 | scores = [0] 22 | state = dict() 23 | position = list() 24 | opened = list() 25 | closed = list() 26 | for p, paren in enumerate(s): 27 | if paren == "(": 28 | opened.append(p) 29 | position.append(p) 30 | state[p] = False 31 | 32 | elif paren == ")" and len(opened) > 0: 33 | op = opened.pop() 34 | state[op] = True 35 | 36 | else: 37 | scores.extend(self._score(position, state)) 38 | state = dict() 39 | position = list() 40 | opened = list() 41 | closed = list() 42 | 43 | scores.extend(self._score(position, state)) 44 | return max(scores) 45 | -------------------------------------------------------------------------------- /LeetCode/0033_Search_Rotated_Sort_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | left, right = 0, len(nums) - 1 4 | while left <= right: 5 | mid = (left + right) // 2 6 | if nums[mid] == target: 7 | return mid 8 | 9 | if nums[mid] >= nums[left]: 10 | if nums[left] <= target < nums[mid]: 11 | right = mid - 1 12 | else: 13 | left = mid + 1 14 | else: 15 | if nums[mid] < target <= nums[right]: 16 | left = mid + 1 17 | else: 18 | right = mid - 1 19 | return -1 20 | -------------------------------------------------------------------------------- /LeetCode/0034_find_first_and_last_position_of_element_in_sorted_array.py: -------------------------------------------------------------------------------- 1 | 2 | # Approach: Binary Search 3 | # Time Complexity: O(n) linear 4 | # Space Complexity: O(1) constant 5 | 6 | class Solution(object): 7 | 8 | def searchRange(self, nums, target): 9 | l = self.search(nums, target, True) 10 | if l == -1: 11 | return [-1,-1] 12 | 13 | r = self.search(nums, target, False) 14 | return [l, r] 15 | 16 | def search(self, nums, target, isStart): 17 | left = 0 18 | right = len(nums) - 1 19 | while left <= right: 20 | mid = left + int((right - left) / 2) 21 | if nums[mid] == target: 22 | if isStart: 23 | if mid == 0: 24 | return 0 25 | else: 26 | if nums[mid - 1] != target: 27 | return mid 28 | else: 29 | right = mid - 1 30 | else: 31 | if mid == len(nums) - 1: 32 | return mid 33 | else: 34 | if nums[mid + 1] != target: 35 | return mid 36 | else: 37 | left = mid + 1 38 | elif nums[mid] > target: 39 | right = mid - 1 40 | else: 41 | left = mid + 1 42 | return -1 43 | -------------------------------------------------------------------------------- /LeetCode/0035_Search_Insert_Position.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | if target in nums: 4 | return nums.index(target) 5 | else: 6 | nums.append(target) 7 | nums.sort() 8 | return nums.index(target) -------------------------------------------------------------------------------- /LeetCode/0036_Valid_Sudoku.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board: List[List[str]]) -> bool: 3 | return self.isValidRow(board) and self.isValidCol(board) and self.isValidSquare(board) 4 | 5 | def isValidRow(self, board): 6 | for row in board: 7 | if not self.isValidUnit(row): 8 | return False 9 | return True 10 | 11 | def isValidCol(self, board): 12 | for col in zip(*board): 13 | if not self.isValidUnit(col): 14 | return False 15 | return True 16 | 17 | def isValidSquare(self, board): 18 | for i in (0, 3, 6): 19 | for j in (0, 3, 6): 20 | square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)] 21 | if not self.isValidUnit(square): 22 | return False 23 | return True 24 | 25 | def isValidUnit(self, unit): 26 | array = [c for c in unit if c != '.'] 27 | return len(set(array)) == len(array) -------------------------------------------------------------------------------- /LeetCode/0037_Sudoku_Solver.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | 4 | class Solution: 5 | def solveSudoku(self, board: List[List[str]]) -> None: 6 | rows = defaultdict(set) 7 | cols = defaultdict(set) 8 | subgrids = defaultdict(set) 9 | empty_cells = deque() 10 | for i in range(9): 11 | for j in range(9): 12 | if board[i][j] != '.': 13 | rows[i].add(board[i][j]) 14 | cols[j].add(board[i][j]) 15 | subgrids[(i//3, j//3)].add(board[i][j]) 16 | else: 17 | empty_cells.append((i, j)) 18 | 19 | def dfs(): 20 | if not empty_cells: 21 | return True 22 | 23 | row, col = empty_cells[0] 24 | subgrid = (row//3, col//3) 25 | for digit in {"1", '2', '3', '4', '5', '6', '7', '8', '9'}: 26 | if digit not in rows[row] and digit not in cols[col] and digit not in subgrids[subgrid]: 27 | board[row][col] = digit 28 | rows[row].add(digit) 29 | cols[col].add(digit) 30 | subgrids[subgrid].add(digit) 31 | empty_cells.popleft() 32 | if dfs(): 33 | return True 34 | 35 | board[row][col] = '.' 36 | rows[row].remove(digit) 37 | cols[col].remove(digit) 38 | subgrids[subgrid].remove(digit) 39 | empty_cells.appendleft((row, col)) 40 | return False 41 | dfs() 42 | return board 43 | -------------------------------------------------------------------------------- /LeetCode/0038 _Count_and_Say.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n: int) -> str: 3 | s = '1' 4 | for _ in range(n - 1): 5 | s = ''.join(str(len(group)) + digit 6 | for group, digit in re.findall(r'((.)\2*)', s)) 7 | return s -------------------------------------------------------------------------------- /LeetCode/0039_Combination_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates, target): 3 | candidates.sort() 4 | res = [] 5 | self.dfs(candidates, target, 0, [], res) 6 | return res 7 | 8 | def dfs(self, nums, target, index, path, res): 9 | if target < 0: 10 | return 11 | if target == 0: 12 | res.append(path) 13 | return 14 | for i in range(index, len(nums)): 15 | self.dfs(nums, target-nums[i], i, path + [nums[i]], res) -------------------------------------------------------------------------------- /LeetCode/0040_Combination_Sum_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem :- 3 | 4 | Given a collection of candidate numbers (candidates) and a target number (target), 5 | find all unique combinations in candidates where the candidate numbers sums to target. 6 | 7 | - Each number in candidates may only be used once in the combination. 8 | 9 | Example:- 10 | 11 | Input: candidates = [10,1,2,7,6,1,5], target = 8, 12 | A solution set is: 13 | [ 14 | [1, 7], 15 | [1, 2, 5], 16 | [2, 6], 17 | [1, 1, 6] 18 | ] 19 | 20 | ''' 21 | class Solution: 22 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 23 | candidates.sort() 24 | table = [None] + [set() for i in range(target)] 25 | for i in candidates: 26 | if i > target: 27 | break 28 | for j in range(target - i, 0, -1): 29 | table[i + j] |= {elt + (i,) for elt in table[j]} 30 | table[i].add((i,)) 31 | return map(list, table[target]) 32 | 33 | 34 | -------------------------------------------------------------------------------- /LeetCode/0041_find_missing_positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | hasOne = False; 4 | for i in range(len(nums)): 5 | if(nums[i]==1): 6 | hasOne = True 7 | if(nums[i]<0): 8 | nums[i] = 0 9 | 10 | if not hasOne: 11 | return 1 12 | 13 | for i in range(len(nums)): 14 | if(abs(nums[i])>0 and abs(nums[i])<=len(nums)): 15 | if(nums[abs(nums[i])-1]==0): 16 | nums[abs(nums[i])-1]=-1 17 | elif(nums[abs(nums[i])-1]>0): 18 | nums[abs(nums[i])-1]*=-1 19 | 20 | for i in range(len(nums)): 21 | if nums[i]>=0: 22 | return i+1 23 | 24 | return len(nums)+1 25 | -------------------------------------------------------------------------------- /LeetCode/0042_Trapping_Rain_Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | n = len(height) 4 | if n>0: 5 | left = [0]*n 6 | right = [0]*n 7 | result = 0 8 | 9 | # Fill left array 10 | left[0] = height[0] 11 | for i in range( 1, n): 12 | left[i] = max(left[i-1], height[i]) 13 | 14 | # Fill right array 15 | right[n-1] = height[n-1] 16 | for i in range(n-2, -1, -1): 17 | right[i] = max(right[i + 1], height[i]); 18 | 19 | for i in range(0, n): 20 | result += min(left[i], right[i]) - height[i] 21 | 22 | return result 23 | else: 24 | return 0 -------------------------------------------------------------------------------- /LeetCode/0043_Multiply Strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, num1, num2): 3 | a,b=eval(num1),eval(num2) 4 | c=a*b 5 | c=str(c) 6 | return c 7 | 8 | -------------------------------------------------------------------------------- /LeetCode/0044_Wildcard_Matching.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s: str, p: str) -> bool: 3 | #this is a dynamic programming solution fot this 4 | matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)] 5 | matrix[0][0] = True 6 | 7 | for i in range(1,len(matrix[0])): 8 | if p[i-1] == '*': 9 | matrix[0][i] = matrix[0][i-1] 10 | 11 | for i in range(1, len(matrix)): 12 | for j in range(1, len(matrix[0])): 13 | if s[i - 1] == p[j - 1] or p[j - 1] == '?': 14 | matrix[i][j] = matrix[i-1][j-1] 15 | elif p[j-1] == '*': 16 | matrix[i][j] = matrix[i][j-1] or matrix[i-1][j] 17 | else: 18 | matrix[i][j] = False 19 | return matrix[len(s)][len(p)] 20 | -------------------------------------------------------------------------------- /LeetCode/0045_Jump_Game_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums): 3 | if len(nums) == 1: 4 | return 0 5 | # number of jumps currently 6 | jump = 0 7 | # max index by current number of jumps 8 | cur = 0 9 | # max index by current + 1 number of jumps 10 | next = 0 11 | for i in range(len(nums)): 12 | if i > cur: 13 | jump += 1 14 | if cur == next: 15 | return -1 16 | cur = next 17 | next = max(next, nums[i] + i) 18 | return jump 19 | -------------------------------------------------------------------------------- /LeetCode/0047_Permutations II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 3 | results = [] 4 | def Combination(permutation, counter): 5 | if len(permutation) == len(nums): 6 | results.append(list(permutation)) 7 | return 8 | 9 | for num in counter: 10 | if counter[num] > 0: 11 | permutation.append(num) 12 | counter[num] -= 1 13 | Combination(permutation, counter) 14 | permutation.pop() 15 | counter[num] += 1 16 | 17 | Combination([], Counter(nums)) 18 | 19 | return results -------------------------------------------------------------------------------- /LeetCode/0048_Rotate_Image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | for i in range(len(matrix)): 4 | for j in range(i,len(matrix)): 5 | if i != j: 6 | matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j] 7 | for each in matrix: 8 | each.reverse() 9 | return matrix -------------------------------------------------------------------------------- /LeetCode/0049_Group_Anagrams.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Solution(object): 5 | def groupAnagrams(self, strs): 6 | 7 | stringsDict = defaultdict(list) 8 | for str in strs: 9 | stringsDict["".join(sorted(str))].append(str) 10 | ans = [] 11 | for group in stringsDict.values(): 12 | ans.append(group) 13 | 14 | return ans 15 | -------------------------------------------------------------------------------- /LeetCode/0050_Powxn.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self,x: float, n: int) -> float: 3 | if n == -1: 4 | return 1/x 5 | elif n == 1: 6 | return x 7 | elif n == 0: 8 | return 1 9 | if n%2 == 0: 10 | return self.myPow(x*x,n//2) 11 | else: 12 | return self.myPow(x*x,n//2) * x 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/0051_N-Queen_1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Oct 7 20:51:57 2020 4 | 5 | @author: anjalisingh 6 | """ 7 | 8 | class Solution(object): 9 | def solveNQueens(self, n): 10 | # i is column index 11 | # left: left diagonal: \ level-i 12 | # right: right diagonal: / level+i 13 | self.col = [0]*n # not occupied column 14 | self.left = [0]*(2*n-1) # number of left diagonal 15 | self.right = [0]*(2*n-1) 16 | board = [['.' for x in range(n)] for y in range(n)] 17 | self.resultBoard = [] 18 | self.backTrack(n, 0, board) 19 | return self.resultBoard 20 | 21 | def backTrack(self, n, level, board): 22 | if level == n: # finish 23 | res = [] 24 | for i in range(n): 25 | res.append(''.join(board[i])) 26 | self.resultBoard.append(res) 27 | return 28 | for i in range(n): # iterate every column 29 | # if col, left, right are all not accupied, put a queue here 30 | if not self.col[i] and not self.left[level-i] and not self.right[level+i]: 31 | board[level][i] = 'Q' 32 | self.col[i] = 1 33 | self.left[level-i] = 1 34 | self.right[level+i] = 1 # choose 35 | self.backTrack(n, level+1, board) # explore 36 | board[level][i] = '.' # un choose 37 | self.col[i] = 0 38 | self.left[level-i] = 0 39 | self.right[level+i] = 0 40 | 41 | # Queen = Solution() 42 | # print(Queen.solveNQueens(4)) 43 | -------------------------------------------------------------------------------- /LeetCode/0052_N_Queens_2.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # @return an integer 3 | def totalNQueens(self, n): 4 | return self.totalNQueensRecu([], 0, n) 5 | 6 | def totalNQueensRecu(self, solution, row, n): 7 | if row == n: 8 | return 1 9 | result = 0 10 | for i in xrange(n): 11 | if i not in solution and reduce(lambda acc, j: abs(row - j) != abs(i - solution[j]) and acc, xrange(len(solution)), True): 12 | result += self.totalNQueensRecu(solution + [i], row + 1, n) 13 | return result -------------------------------------------------------------------------------- /LeetCode/0053_Maximum_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | dp = [0]*len(nums) 4 | dp[0] = nums[0] 5 | max_num = nums[0] 6 | for i in range(1, len(nums)): 7 | dp[i] = max(dp[i-1]+nums[i], nums[i]) 8 | if dp[i]>max_num: max_num = dp[i] 9 | return max_num 10 | -------------------------------------------------------------------------------- /LeetCode/0054_Spiral_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix): 3 | if len(matrix)>0: 4 | k, l = 0, 0 5 | m = len(matrix) 6 | n = len(matrix[0]) 7 | 8 | l1 = [] 9 | while (k < m and l < n): 10 | 11 | for i in range(l, n): 12 | l1.append(matrix[k][i]) 13 | 14 | k += 1 15 | 16 | for i in range(k, m): 17 | l1.append(matrix[i][n - 1]) 18 | n -= 1 19 | 20 | if (k < m): 21 | 22 | for i in range(n - 1, (l - 1), -1): 23 | l1.append(matrix[m - 1][i]) 24 | 25 | m -= 1 26 | 27 | if (l < n): 28 | for i in range(m - 1, k - 1, -1): 29 | l1.append(matrix[i][l]) 30 | 31 | l += 1 32 | return l1 33 | 34 | 35 | -------------------------------------------------------------------------------- /LeetCode/0055_jump_game.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def canJump(self, nums: List[int]) -> bool: 6 | jump_length_left = 0 7 | for num in nums: 8 | if jump_length_left == -1: 9 | return False 10 | jump_length_left = max(jump_length_left - 1, num - 1) 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /LeetCode/0056_Merge_Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | 4 | intervals.sort(key=lambda x: x[0]) 5 | 6 | merged = [] 7 | for interval in intervals: 8 | # if the list of merged intervals is empty or if the current 9 | # interval does not overlap with the previous, simply append it. 10 | if not merged or merged[-1][1] < interval[0]: 11 | merged.append(interval) 12 | else: 13 | # otherwise, there is overlap, so we merge the current and previous 14 | # intervals. 15 | merged[-1][1] = max(merged[-1][1], interval[1]) 16 | 17 | return merged 18 | -------------------------------------------------------------------------------- /LeetCode/0057_Insert_Interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 3 | result = [] 4 | 5 | for interval in intervals: 6 | # the new interval is after the range of other interval, so we can leave the current interval baecause the new one does not overlap with it 7 | if interval[1] < newInterval[0]: 8 | result.append(interval) 9 | # the new interval's range is before the other, so we can add the new interval and update it to the current one 10 | elif interval[0] > newInterval[1]: 11 | result.append(newInterval) 12 | newInterval = interval 13 | # the new interval is in the range of the other interval, we have an overlap, so we must choose the min for start and max for end of interval 14 | elif interval[1] >= newInterval[0] or interval[0] <= newInterval[1]: 15 | newInterval[0] = min(interval[0], newInterval[0]) 16 | newInterval[1] = max(newInterval[1], interval[1]) 17 | 18 | 19 | result.append(newInterval); 20 | return result 21 | -------------------------------------------------------------------------------- /LeetCode/0058_Length_of_Last_Word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | try: 4 | return len(s.split()[-1]) 5 | except IndexError: 6 | return 0 7 | -------------------------------------------------------------------------------- /LeetCode/0059_Spiral_Matrix_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n: int) -> List[List[int]]: 3 | res, lo = [[n*n]], n*n 4 | while lo > 1: 5 | lo, hi = lo - len(res), lo 6 | #print('res:', res) 7 | res = [[i for i in range(lo, hi)]] + [list(j) for j in zip(*res[::-1])] 8 | return res 9 | -------------------------------------------------------------------------------- /LeetCode/0060 - Permutation_Sequence.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | class Solution: 3 | data = [] 4 | 5 | def getPermutation(self, n: int, k: int) -> str: 6 | self.data = [] 7 | string = [] 8 | for i in range(1, n+1): 9 | string.append(str(i)) 10 | string = list(permutations(string)) 11 | temp = string[k-1] 12 | string = [] 13 | string.append("".join(temp)) 14 | return string[0] 15 | 16 | 17 | -------------------------------------------------------------------------------- /LeetCode/0061_Rotate_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 9 | 10 | 11 | if head == None or head.next == None: 12 | return head 13 | count = 1 14 | p = head 15 | while p.next: 16 | count+=1 17 | p=p.next 18 | 19 | rot = k%count 20 | temp = head 21 | p.next = head 22 | for i in range(count-rot-1): 23 | temp = temp.next 24 | answer = temp.next 25 | temp.next = None 26 | 27 | return answer 28 | 29 | -------------------------------------------------------------------------------- /LeetCode/0062_Unique_Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | return math.factorial(n+m-2)//(math.factorial(m-1)*math.factorial(n-1)) -------------------------------------------------------------------------------- /LeetCode/0063_UniquePathsII.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: 3 | n, m = len(obstacleGrid), len(obstacleGrid[0]) 4 | 5 | ways = [[0 for j in range(m)] for i in range(n)] 6 | 7 | for i in range(n): 8 | if obstacleGrid[i][0] == 1: 9 | break 10 | ways[i][0] = 1 11 | 12 | for j in range(m): 13 | if obstacleGrid[0][j] == 1: 14 | break 15 | ways[0][j] = 1 16 | 17 | for i in range(1, n): 18 | for j in range(1, m): 19 | if obstacleGrid[i][j] == 0: 20 | ways[i][j] = ways[i - 1][j] + ways[i][j - 1] 21 | 22 | return ways[n - 1][m - 1] 23 | -------------------------------------------------------------------------------- /LeetCode/0064_Minimum_Path_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPathSum(self, grid: List[List[int]]) -> int: 3 | rows=len(grid) 4 | columns=len(grid[0]) 5 | for i in range(1,columns): 6 | grid[0][i]+=grid[0][i-1] 7 | for j in range(1,rows): 8 | grid[j][0]+=grid[j-1][0] 9 | for k in range(1,rows): 10 | for l in range(1,columns): 11 | grid[k][l]+=min(grid[k][l-1],grid[k-1][l]) 12 | return grid[-1][-1] 13 | -------------------------------------------------------------------------------- /LeetCode/0065_Valid_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isNumber(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | try: 8 | float(s) 9 | return True 10 | except ValueError: 11 | return False -------------------------------------------------------------------------------- /LeetCode/0066_Plus_One.py: -------------------------------------------------------------------------------- 1 | # Problem name : Plus One 2 | # Problem link : https://leetcode.com/problems/plus-one/ 3 | # Contributor : Shreeraksha R Aithal 4 | 5 | class Solution: 6 | def plusOne(self, digits: List[int]) -> List[int]: 7 | n = len(digits) 8 | i = -1 9 | carry = 1 10 | while i>=-n: 11 | digits[i] = digits[i] + carry 12 | carry = digits[i]//10 13 | digits[i] = digits[i]%10 14 | i = i-1 15 | 16 | if carry > 0: 17 | digits = [carry] + digits 18 | 19 | return digits -------------------------------------------------------------------------------- /LeetCode/0067_Add_Binary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | sum = int(a,2) + int(b,2) 4 | return bin(sum)[2:] -------------------------------------------------------------------------------- /LeetCode/0069 _ Sqrt(x).py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mySqrt(self, x): 3 | if x<2: 4 | return x 5 | low = 0 6 | high = x 7 | result=0 8 | while(low<=high): 9 | mid = (low+high)//2 10 | if(mid*mid==x): 11 | return mid 12 | elif(mid*mid int: 19 | return self.fib(n + 1) 20 | 21 | fibStore = {} 22 | def fib(self, n: int) -> int: 23 | if n in self.fibStore: 24 | return self.fibStore[n] 25 | 26 | if n <= 2: 27 | return 1 28 | 29 | value = self.fib(n - 1) + self.fib(n - 2) 30 | self.fibStore[n] = value 31 | return value 32 | 33 | 34 | print(Solution().climbStairs(30)) 35 | -------------------------------------------------------------------------------- /LeetCode/0071_Simplify_Path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def simplifyPath(self, path): 3 | tokens = path.split('/') # some of them could be empty == '//' 4 | stack = [] 5 | ans = '/' 6 | for item in tokens: 7 | if item == '': 8 | continue 9 | if item == '.': 10 | pass 11 | elif item == '..': 12 | if len(stack) > 0: 13 | _ = stack.pop() 14 | else: 15 | stack.append(item) 16 | for item in stack: 17 | ans += item 18 | ans += '/' 19 | 20 | return ans if len(ans) == 1 else ans[:-1] 21 | -------------------------------------------------------------------------------- /LeetCode/0072_Edit_Distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @return an integer 3 | def minDistance(self, word1, word2): 4 | m=len(word1) 5 | n=len(word2) 6 | dp=[[0 for i in range(n+1)] for j in range(m+1)] 7 | for i in range(m+1): 8 | dp[i][0]=i 9 | for j in range(n+1): 10 | dp[0][j]=j 11 | for i in range(1,m+1): 12 | for j in range(1,n+1): 13 | if word1[i-1]==word2[j-1]: 14 | dp[i][j]=dp[i-1][j-1] 15 | else: 16 | dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1) 17 | return dp[m][n] 18 | 19 | test=Solution() 20 | input1=str(input(“Enter a string1”)) 21 | input2=str(input(“Enter a string2”)) 22 | print(test.minDistance(input1,input2)) 23 | -------------------------------------------------------------------------------- /LeetCode/0073_Set Matrix Zeroes.py: -------------------------------------------------------------------------------- 1 | # SOLUTIONS 1 2 | 3 | class Solution(object): 4 | def setZeroes(self, matrix): 5 | """ 6 | :type matrix: List[List[int]] 7 | :rtype: void Do not return anything, modify matrix in-place instead. 8 | """ 9 | R = len(matrix) 10 | C = len(matrix[0]) 11 | rows, cols = set(), set() 12 | 13 | # Essentially, we mark the rows and columns that are to be made zero 14 | for i in range(R): 15 | for j in range(C): 16 | if matrix[i][j] == 0: 17 | rows.add(i) 18 | cols.add(j) 19 | 20 | # Iterate over the array once again and using the rows and cols sets, update the elements 21 | for i in range(R): 22 | for j in range(C): 23 | if i in rows or j in cols: 24 | matrix[i][j] = 0 25 | 26 | 27 | #SOLUTIONS 2 28 | 29 | class Solution(object): 30 | def setZeroes(self, matrix): 31 | """ 32 | :type matrix: List[List[int]] 33 | :rtype: void Do not return anything, modify matrix in-place instead. 34 | """ 35 | is_col = False 36 | R = len(matrix) 37 | C = len(matrix[0]) 38 | for i in range(R): 39 | # Since first cell for both first row and first column is the same i.e. matrix[0][0] 40 | # We can use an additional variable for either the first row/column. 41 | # For this solution we are using an additional variable for the first column 42 | # and using matrix[0][0] for the first row. 43 | if matrix[i][0] == 0: 44 | is_col = True 45 | for j in range(1, C): 46 | # If an element is zero, we set the first element of the corresponding row and column to 0 47 | if matrix[i][j] == 0: 48 | matrix[0][j] = 0 49 | matrix[i][0] = 0 50 | 51 | # Iterate over the array once again and using the first row and first column, update the elements. 52 | for i in range(1, R): 53 | for j in range(1, C): 54 | if not matrix[i][0] or not matrix[0][j]: 55 | matrix[i][j] = 0 56 | 57 | # See if the first row needs to be set to zero as well 58 | if matrix[0][0] == 0: 59 | for j in range(C): 60 | matrix[0][j] = 0 61 | 62 | # See if the first column needs to be set to zero as well 63 | if is_col: 64 | for i in range(R): 65 | matrix[i][0] = 0 -------------------------------------------------------------------------------- /LeetCode/0075_Sort_Colors.py: -------------------------------------------------------------------------------- 1 | # Problem name : Sort Colors 2 | # Problem link : https://leetcode.com/problems/sort-colors/ 3 | # Contributor : Shreeraksha R Aithal 4 | 5 | class Solution: 6 | def sortColors(self, nums: List[int]) -> None: 7 | """ 8 | Do not return anything, modify nums in-place instead. 9 | """ 10 | 11 | i = k = 0 12 | n = len(nums) 13 | j = n-1 14 | while k < n and i < j: 15 | if nums[k] == 0: 16 | if k > i: 17 | nums[i], nums[k] = nums[k], nums[i] 18 | i += 1 19 | else: 20 | k += 1 21 | elif nums[k] == 2: 22 | if k < j: 23 | nums[j], nums[k] = nums[k], nums[j] 24 | j -= 1 25 | else: 26 | k += 1 27 | else: 28 | k += 1 29 | 30 | -------------------------------------------------------------------------------- /LeetCode/0076_Minimum_Window_Substring.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Solution: 4 | def minWindow(self, s: str, t: str) -> str: 5 | char_frequency = defaultdict(lambda: 0) 6 | for c in t: 7 | char_frequency[c] += 1 8 | chars_matched = 0 9 | 10 | start = 0 11 | res = "" 12 | 13 | for end in range(len(s)): 14 | right_char = s[end] 15 | if right_char in t: 16 | char_frequency[right_char] -= 1 17 | if char_frequency[right_char] == 0: 18 | chars_matched += 1 19 | 20 | while start <= end and chars_matched == len(char_frequency): 21 | if res == "" or end-start+1 < len(res): 22 | res = s[start:end+1] 23 | 24 | left_char = s[start] 25 | if left_char in t: 26 | if char_frequency[left_char] == 0: 27 | chars_matched -= 1 28 | char_frequency[left_char] += 1 29 | start += 1 30 | 31 | return res 32 | -------------------------------------------------------------------------------- /LeetCode/0077_Combinations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | # Pretty much same as combination sums II, use index at most once per combo 4 | 5 | # create list from 1 to n 6 | # for each i-th element, call helper function from [i+1:] 7 | # from the helper function, if length of arr passed in == k 8 | # append and return 9 | # otherwise, keep going for i+1 in a for loop in the helper 10 | # ^ after done, delete the last index(backtrack process) 11 | 12 | nums = [_ for _ in range(1,n+1)] 13 | result = [] 14 | combo = [] 15 | n = len(nums) 16 | 17 | for i in range(n): 18 | combo.append(nums[i]) 19 | self.backtrack(nums[i+1:],combo, result, k) 20 | combo = [] 21 | 22 | return result 23 | 24 | def backtrack(self, nums: List[int], combo: List[int], result: List[List[int]], k: int) -> None: 25 | 26 | if len(combo) == k: 27 | result.append([_ for _ in combo]) 28 | return 29 | 30 | n = len(nums) 31 | 32 | for i in range(n): 33 | combo.append(nums[i]) 34 | self.backtrack(nums[i+1:],combo,result,k) 35 | # This is the backtrack process 36 | del combo[-1] 37 | 38 | return -------------------------------------------------------------------------------- /LeetCode/0078_Subsets.py: -------------------------------------------------------------------------------- 1 | #using backtracking approach 2 | 3 | class Solution: 4 | def subsets(self, nums: List[int]) -> List[List[int]]: 5 | def backtrack(first = 0, curr = []): 6 | # if the combination is done 7 | if len(curr) == k: 8 | output.append(curr[:]) 9 | for i in range(first, n): 10 | # add nums[i] into the current combination 11 | curr.append(nums[i]) 12 | # use next integers to complete the combination 13 | backtrack(i + 1, curr) 14 | # backtrack 15 | curr.pop() 16 | 17 | output = [] 18 | n = len(nums) 19 | for k in range(n + 1): 20 | backtrack() 21 | return output 22 | -------------------------------------------------------------------------------- /LeetCode/0079_Word_Search.py: -------------------------------------------------------------------------------- 1 | def exist(self, grid: List[List[str]], word: str) -> bool: 2 | 3 | seen = set() 4 | 5 | # Boundary checking 6 | def inBound(row, col, grid): 7 | return 0 <= row < len(grid) and 0 <= col < len(grid[0]) 8 | 9 | def dfs(grid, word, curr_i, row, col): 10 | 11 | if curr_i == len(word): 12 | return True 13 | 14 | if not inBound(row, col,grid) or grid[row][col] != word[curr_i]: 15 | return False 16 | 17 | seen.add((row, col)) 18 | 19 | # Explore possible paths 20 | pos_paths = [(row, col + 1), (row, col - 1), (row + 1, col), (row - 1, col)] 21 | for row_n, col_n in pos_paths: 22 | if (row_n,col_n) not in seen: 23 | if dfs(grid, word, curr_i + 1, row_n, col_n): 24 | return True 25 | 26 | seen.remove((row,col)) 27 | return False 28 | 29 | for row in range(len(grid)): 30 | for col in range(len(grid[0])): 31 | if grid[row][col] == word[0]: 32 | if dfs(grid, word, 0, row, col): 33 | return True 34 | 35 | return False -------------------------------------------------------------------------------- /LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 3 | ''' 4 | 5 | 6 | class Solution: 7 | # we want to leave at most two of each element 8 | def removeDuplicates(self, nums: list) -> int: 9 | length = 0 10 | lastNum = None 11 | lastLastNum = None 12 | 13 | # iterate in reverse order so that when we modify the list 14 | # it doesn't affect the order of the unvisited elements 15 | i = len(nums) - 1 16 | while i >= 0: 17 | el = nums[i] 18 | if el == lastLastNum: 19 | del nums[i] 20 | else: 21 | length += 1 22 | lastLastNum = lastNum 23 | lastNum = el 24 | i -= 1 25 | 26 | return length 27 | 28 | 29 | if __name__ == '__main__': 30 | solution = Solution() 31 | input = [1, 1, 1, 2, 2, 3] 32 | solution.removeDuplicates(input) 33 | print(input) 34 | print(len(input)) 35 | -------------------------------------------------------------------------------- /LeetCode/0081_Search_in_Rotated_Sorted_Array II.py: -------------------------------------------------------------------------------- 1 | def search(self, nums, target): 2 | l, r = 0, len(nums)-1 3 | while l <= r: 4 | mid = l + (r-l)//2 5 | if nums[mid] == target: 6 | return True 7 | while l < mid and nums[l] == nums[mid]: # tricky part 8 | l += 1 9 | # the first half is ordered 10 | if nums[l] <= nums[mid]: 11 | # target is in the first half 12 | if nums[l] <= target < nums[mid]: 13 | r = mid - 1 14 | else: 15 | l = mid + 1 16 | # the second half is ordered 17 | else: 18 | # target is in the second half 19 | if nums[mid] < target <= nums[r]: 20 | l = mid + 1 21 | else: 22 | r = mid - 1 23 | return False -------------------------------------------------------------------------------- /LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | #class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: ListNode) -> ListNode: 8 | if head is None: 9 | return head 10 | 11 | while (head.next is not None) and (head.val == head.next.val): 12 | while (head.next is not None) and (head.val == head.next.val): 13 | head = head.next 14 | head = head.next 15 | if head is None: 16 | return head 17 | 18 | head.next = self.deleteDuplicates(head.next) 19 | return head -------------------------------------------------------------------------------- /LeetCode/0083_Remove_Dupticates_from_Sorted_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: ListNode) -> ListNode: 8 | if head==None: 9 | return head 10 | current= head.next 11 | prev=head 12 | while current!=None: 13 | if current.val==prev.val: 14 | prev.next=current.next 15 | current=current.next 16 | else: 17 | current=current.next 18 | prev=prev.next 19 | return head -------------------------------------------------------------------------------- /LeetCode/0084_Largest_Rectangle_in_Histogram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestRectangleArea(self, heights: List[int]) -> int: 3 | heights.append(0) 4 | lst = [-1] 5 | output = 0 6 | 7 | for i in range(len(heights)): 8 | while (heights[i] < heights[lst[-1]]): 9 | height = heights[lst.pop()] 10 | width = i - lst[-1] - 1 11 | output = max(output, height * width) 12 | lst.append(i) 13 | 14 | heights.pop() 15 | return output 16 | -------------------------------------------------------------------------------- /LeetCode/0086_Partition_List.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def partition(self, head, x): 3 | """ 4 | :type head: ListNode 5 | :type x: int 6 | :rtype: ListNode 7 | """ 8 | 9 | # before and after are the two pointers used to create two list 10 | # before_head and after_head are used to save the heads of the two lists. 11 | # All of these are initialized with the dummy nodes created. 12 | before = before_head = ListNode(0) 13 | after = after_head = ListNode(0) 14 | 15 | while head: 16 | # If the original list node is lesser than the given x, 17 | # assign it to the before list. 18 | if head.val < x: 19 | before.next = head 20 | before = before.next 21 | else: 22 | # If the original list node is greater or equal to the given x, 23 | # assign it to the after list. 24 | after.next = head 25 | after = after.next 26 | 27 | # move ahead in the original list 28 | head = head.next 29 | 30 | # Last node of "after" list would also be ending node of the reformed list 31 | after.next = None 32 | # Once all the nodes are correctly assigned to the two lists, 33 | # combine them to form a single list which would be returned. 34 | before.next = after_head.next 35 | 36 | return before_head.next 37 | -------------------------------------------------------------------------------- /LeetCode/0087_Scramble_String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isScramble(self, s1: str, s2: str) -> bool: 3 | def scramble(s1, s2): 4 | key = (s1, s2) 5 | if key in mem: 6 | return mem[key] 7 | 8 | if sorted(s1) != sorted(s2): 9 | return False 10 | 11 | if s1 == s2: 12 | mem[key] = True 13 | return True 14 | 15 | for i in range(len(s1) - 1, 0, -1): 16 | if (scramble(s1[:i], s2[:i]) and scramble(s1[i:], s2[i:])) or ( 17 | scramble(s1[:i], s2[-i:]) and scramble(s1[i:], s2[:-i]) 18 | ): 19 | return True 20 | mem[key] = False 21 | return False 22 | 23 | mem = {} 24 | return scramble(s1, s2) 25 | -------------------------------------------------------------------------------- /LeetCode/0088_Merge_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 3 | for x in nums2: 4 | for y in range(len(nums1)): 5 | if nums1[y]==0: 6 | nums1[y]+=x 7 | break 8 | nums1.sort() 9 | -------------------------------------------------------------------------------- /LeetCode/0089_Gray_code.py: -------------------------------------------------------------------------------- 1 | def gray(a): 2 | return ((a)^(a>>1)) 3 | 4 | class Solution: 5 | def grayCode(self, n: int) -> List[int]: 6 | ans=[] 7 | for i in range(pow(2,n)): 8 | ans.append(gray(i)) 9 | return ans 10 | 11 | 12 | -------------------------------------------------------------------------------- /LeetCode/0090_Subsets_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 3 | fin=[] 4 | for i in range(2**len(nums)): 5 | lst=[] 6 | for j in range(len(nums)): 7 | if i%2==1: lst.append(nums[j]) 8 | i=i//2 9 | if i==0: break 10 | 11 | fin.append(sorted(lst)) 12 | 13 | lst2=[] 14 | for x in fin: 15 | if not x in lst2: 16 | lst2.append(x) 17 | 18 | return sorted(lst2,key= lambda x: x[0] if x else -1 ) -------------------------------------------------------------------------------- /LeetCode/0091_Decode_Ways.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | def in_range(n): 4 | if n[0] == '0': 5 | return False 6 | to_int = int(n) 7 | if to_int <= 26 and to_int > 0: 8 | return True 9 | return False 10 | 11 | N = len(s) 12 | a, b = 1, 1 13 | if N == 0 or s[0] == '0': 14 | return 0 15 | 16 | for i in range(1, N): 17 | extra = a if in_range(s[i-1:i+1]) else 0 18 | c = extra + (b if in_range(s[i]) else 0) 19 | a, b = b, c 20 | return b 21 | -------------------------------------------------------------------------------- /LeetCode/0093_Restore_IP_address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def restoreIpAddresses(self, s: str) -> list: 4 | 5 | return self.convert(s) 6 | 7 | def convert(self,s): 8 | 9 | sz = len(s) 10 | 11 | # Check for string size 12 | if sz > 12: 13 | return [] 14 | snew = s 15 | l = [] 16 | 17 | # Generating different combinations. 18 | for i in range(1, sz - 2): 19 | for j in range(i + 1, sz - 1): 20 | for k in range(j + 1, sz): 21 | snew = snew[:k] + "." + snew[k:] 22 | snew = snew[:j] + "." + snew[j:] 23 | snew = snew[:i] + "." + snew[i:] 24 | 25 | # Check for the validity of combination 26 | if self.is_valid(snew): 27 | l.append(snew) 28 | 29 | snew = s 30 | 31 | return l 32 | 33 | 34 | 35 | 36 | def is_valid(self,ip): 37 | 38 | # Splitting by "." 39 | ip = ip.split(".") 40 | 41 | # Checking for the corner cases 42 | for i in ip: 43 | if (len(i) > 3 or int(i) < 0 or 44 | int(i) > 255): 45 | return False 46 | if len(i) > 1 and int(i) == 0: 47 | return False 48 | if (len(i) > 1 and int(i) != 0 and 49 | i[0] == '0'): 50 | return False 51 | 52 | return True 53 | -------------------------------------------------------------------------------- /LeetCode/0094_Binary_Tree_Inorder_Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def inorderTraversal(self, root: TreeNode) -> List[int]: 9 | res = [] 10 | myStack = [] 11 | curr = root 12 | while len(myStack) or curr is not None: 13 | while curr is not None: 14 | myStack.append(curr) 15 | curr = curr.left 16 | curr = myStack.pop() 17 | res.append(curr.val) 18 | curr = curr.right 19 | return res 20 | -------------------------------------------------------------------------------- /LeetCode/0098_Validate_Binary_Search_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def isValidBST(self, root: TreeNode, sm=[], gt=[]) -> bool: 10 | if root is None: 11 | return True 12 | 13 | if any([root.val <= x for x in sm]) or any([root.val >= x for x in gt]): 14 | return False 15 | 16 | return (root.left is None or self.isValidBST(root.left, sm, gt + [root.val])) and (root.right is None or self.isValidBST(root.right, sm + [root.val], gt)) 17 | -------------------------------------------------------------------------------- /LeetCode/0100_Same_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def isSameTree(self, p, q): 9 | if(p is None and q is None): 10 | return True 11 | 12 | if(p==None or q==None): 13 | return False 14 | 15 | if(p.val!=q.val): 16 | return False 17 | 18 | else: 19 | return self.isSameTree( p.right, q.right) and self.isSameTree( p.left, q.left) 20 | -------------------------------------------------------------------------------- /LeetCode/0101_Symmetric_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSymmetric(self, root: TreeNode) -> bool: 9 | if root == None: 10 | return True 11 | 12 | return self.isMirror(root.left, root.right) 13 | 14 | 15 | def isMirror(self, a: TreeNode, b: TreeNode) -> bool: 16 | if (a and b) and (a.val == b.val): 17 | return self.isMirror(a.left, b.right) and self.isMirror(a.right, b.left) 18 | 19 | return a == None and b == None 20 | -------------------------------------------------------------------------------- /LeetCode/0102_Binary_Tree_Level_Order_Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Level Order Traversal - BFS 3 | 4 | A Tree Algorithm where the nodes in a tree are visited in a level by level fashion. 5 | i.e Nodes at each level are processed before moving on to the next. 6 | 7 | Steps 8 | 1. For every node, add to a queue. 9 | 2. Process the node and pop from the front of the queue. 10 | 3. Add its left and right child to the queue. 11 | 12 | Time complexity is O(N) since we visit every node at least once. N is the number of nodes in the tree. 13 | Space complexity is O(N) since we make use of a queue data structure having a maximum of size N. 14 | 15 | 16 | Sample Binary Tree: 17 | 18 | 8 19 | / \ 20 | 3 10 21 | / \ \ 22 | 1 6 14 23 | 24 | Level-Order Traversal of this binary tree results in: 25 | output = [[8], [3,10], [1,6,14]] 26 | """ 27 | 28 | # Code implementation 29 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 30 | import collections 31 | output = [] 32 | queue = collections.deque([root]) 33 | 34 | if root == None: 35 | return [] 36 | 37 | while queue: 38 | num_of_nodes = len(queue) 39 | curr_level = [] 40 | 41 | for node in range(num_of_nodes): 42 | curr_node = queue.popleft() 43 | curr_level.append(curr_node.val) 44 | 45 | if curr_node.left: 46 | queue.append(curr_node.left) 47 | 48 | if curr_node.right: 49 | queue.append(curr_node.right) 50 | 51 | output.append(curr_level) 52 | 53 | 54 | 55 | return output 56 | -------------------------------------------------------------------------------- /LeetCode/0103_Binary_Tree_Zigzag_Level_Order_Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: 9 | q = [] 10 | t = [] 11 | 12 | if root: 13 | q.append((0, root)) 14 | 15 | while len(q) > 0: 16 | level, curr = q.pop(0) 17 | 18 | if level >= len(t): 19 | t.append([]) 20 | t[level].append(curr.val) 21 | 22 | if curr.left: 23 | q.append((level + 1, curr.left)) 24 | if curr.right: 25 | q.append((level + 1, curr.right)) 26 | 27 | for i in range(len(t)): 28 | if i % 2 == 1: 29 | t[i] = reversed(t[i]) 30 | return t 31 | 32 | -------------------------------------------------------------------------------- /LeetCode/0104_Maximum_Depth_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxDepth(self, root: TreeNode) -> int: 9 | if root==None: 10 | return 0 11 | else: 12 | return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 13 | -------------------------------------------------------------------------------- /LeetCode/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 9 | if len(preorder) == 0: 10 | return None 11 | 12 | n = preorder.pop(0) 13 | i = inorder.index(n) 14 | 15 | l = self.buildTree(preorder[:i], inorder[:i]) 16 | r = self.buildTree(preorder[i:], inorder[i+1:]) 17 | 18 | return TreeNode(n, l, r) 19 | 20 | -------------------------------------------------------------------------------- /LeetCode/0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: 3 | return self.helperFunc(inorder, postorder, 0, len(inorder)-1, len(postorder)-1) 4 | def helperFunc(self, inorder: List[int], postorder: List[int], left: int, right: int, postIndex: int) -> TreeNode: 5 | # checks if there is node required else puts null in the binary tree 6 | if postIndex == -1: 7 | return 8 | # creating the root of the subtree from the value present at current postIndex 9 | root = TreeNode(postorder[postIndex]) 10 | # we find the root's value in order to divide them into left and right subtree 11 | x = 0 12 | for i in range(len(inorder)): 13 | if root.val == inorder[i]: 14 | x = i 15 | # finding corresponding values that are roots for left and right subtrees or assign -1 16 | right_post = -1 if abs(right - x) == 0 else postIndex - 1 17 | left_post = -1 if abs(left - x) == 0 else postIndex -1 - abs(right - x) 18 | # calling recursively helperFunc for left and right subtrees 19 | root.left = self.helperFunc(inorder, postorder, left, x-1, left_post) 20 | root.right = self.helperFunc(inorder, postorder, x+1, right, right_post) 21 | return root 22 | -------------------------------------------------------------------------------- /LeetCode/0107_Binary_Tree_Level_Order_Traversal_II.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: 9 | q = [] 10 | t = [] 11 | 12 | if root: 13 | q.append((0, root)) 14 | 15 | while len(q) > 0: 16 | level, curr = q.pop(0) 17 | 18 | if level >= len(t): 19 | t.append([]) 20 | t[level].append(curr.val) 21 | 22 | if curr.left: 23 | q.append((level + 1, curr.left)) 24 | if curr.right: 25 | q.append((level + 1, curr.right)) 26 | 27 | return reversed(t) 28 | -------------------------------------------------------------------------------- /LeetCode/0110_balanced_binary_tree.py: -------------------------------------------------------------------------------- 1 | #class TreeNode(object): 2 | # def __init__(self, x): 3 | # self.val = x 4 | # self.left = None 5 | # self.right = None 6 | 7 | 8 | class Solution(object): 9 | # @param root, a tree node 10 | # @return a boolean 11 | def isBalanced(self, root): 12 | def getHeight(root): 13 | if root is None: 14 | return 0 15 | left_height, right_height = \ 16 | getHeight(root.left), getHeight(root.right) 17 | if left_height < 0 or right_height < 0 or \ 18 | abs(left_height - right_height) > 1: 19 | return -1 20 | return max(left_height, right_height) + 1 21 | return (getHeight(root) >= 0) -------------------------------------------------------------------------------- /LeetCode/0111_Minimum_Depth_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def minDepth(self, root: TreeNode) -> int: 10 | if not root: 11 | return 0 12 | if not root.left or not root.right: 13 | return max(self.minDepth(root.left), self.minDepth(root.right)) + 1 14 | else: 15 | return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 16 | -------------------------------------------------------------------------------- /LeetCode/0112_Path_Sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def hasPathSum(self, root: TreeNode, sum: int) -> bool: 10 | if not root: 11 | return False 12 | if not root.left and not root.right: 13 | return root.val == sum 14 | return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val) -------------------------------------------------------------------------------- /LeetCode/0118_pascal_triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | if numRows==0: 4 | return [] 5 | triangle=[[1]] 6 | for row in range(numRows-1): 7 | triangle.append([1]+[triangle[-1][i]+triangle[-1][i+1] for i in range(row)]+[1]) 8 | return triangle 9 | -------------------------------------------------------------------------------- /LeetCode/0119_Pascal_Triangle2.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getRow(self, rowIndex): 3 | """ 4 | :type rowIndex: int 5 | :rtype: List[int] 6 | """ 7 | 8 | if rowIndex == 0: 9 | return [1] 10 | if rowIndex == 1: 11 | return [1,1] 12 | 13 | init = [1,1] 14 | for i in range(0, rowIndex-1): 15 | new_vec = [] 16 | for v in range(0, len(init)-1): 17 | new_vec.append(init[v] + init[v+1]) 18 | new_vec = [1] + new_vec + [1] 19 | init = new_vec 20 | return init 21 | -------------------------------------------------------------------------------- /LeetCode/0120_minimum_path_triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumTotal(self, triangle: List[List[int]]) -> int: 3 | # using memoization technique 4 | 5 | # creating the list to track the minimum path 6 | mem = [item for item in triangle[-1]] # ---> array's nottom row is updated here 7 | 8 | # trying track backward from bottom-most array 9 | for i in range(len(triangle)-2, -1, -1): # ---> if len(triangle) = 5 -- range from 3, 2, 1 (in reverse order) 10 | for j in range(len(triangle[i])): 11 | mem[j] = triangle[i][j] + min(mem[j], mem[j+1]) # calculate the distance with minimum adjacent value 12 | 13 | #print (mem) 14 | return mem[0] 15 | -------------------------------------------------------------------------------- /LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | if len(prices) == 0: 4 | return 0 5 | profit = 0 6 | mincost = prices[0] 7 | 8 | for i in range(1, len(prices)): 9 | profit = max(profit, prices[i] - mincost) 10 | mincost = min(mincost, prices[i]) 11 | return profit -------------------------------------------------------------------------------- /LeetCode/0123_Best_Time_To_Buy_And_Sell_Stock_III.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Python program to solve issue: 0123- Best Time to Buy adn Sell Stock 4 | 5 | Issue Id: #383 6 | ''' 7 | 8 | 9 | class Solution: 10 | 11 | #Evalutes the all days to buy and sell stock & Generate maximum profit 12 | def maxProfit(self, prices: List[int]) -> int: 13 | 14 | #Checks whether price array is empty or less then 2 elements 15 | if prices==None or len(prices) < 2: 16 | return 0 17 | 18 | maxProfit=0 #Stores maximum profit 19 | 20 | minPrice=prices[0] #the minimum price from the first day to day k-1 21 | 22 | #the maximum profit with at most one transaction from the first day to day k 23 | first=[0 for x in range(0,len(prices))] 24 | 25 | #Evaluates maximum profit from first day to last day 26 | for i in range(1,len(prices)): 27 | maxProfit= max(maxProfit, prices[i]- minPrice) 28 | first[i]= maxProfit 29 | minPrice= min(minPrice, prices[i]) 30 | 31 | maxProfit=0 32 | maxPrice=prices[len(prices)-1] #the maximum price from day k+1 to the last day 33 | 34 | #the maximum profit with at most one transaction from day k to the last day 35 | second=[0 for x in range(len(prices))] 36 | 37 | #Evaluates maximum profit from last day to first day 38 | for j in range(len(prices)-2,-1,-1): 39 | maxProfit = max(maxProfit, (maxPrice - prices[j])) 40 | second[j] = int(maxProfit) 41 | maxPrice = max(maxPrice, prices[j]) 42 | 43 | maxProfit=0 44 | 45 | #Evaluates maximum profit for all days with at most TWO transaction 46 | for k in range(0,len(prices)): 47 | maxProfit= max(maxProfit, first[k]+second[k]) 48 | 49 | return maxProfit -------------------------------------------------------------------------------- /LeetCode/0125_Valid_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | alphnum = "" 4 | #Extract only alphanumeric characters from the given string 5 | for i in s: 6 | #Check whether the character is a lowercase letter or a number 7 | if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"): 8 | alphnum+=i 9 | #Check whether the character is an uppercase letter. 10 | #If yes,convert to lower case 11 | elif ord(i)>=ord('A') and ord(i)<=ord('Z'): 12 | i = chr(32+ord(i)) 13 | alphnum+=i 14 | #Reverse the alphanumeric string and check whether it is a palindrome 15 | rev= alphnum[::-1] 16 | result= rev==alphnum 17 | return result 18 | -------------------------------------------------------------------------------- /LeetCode/0126_Word_Ladder_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: 3 | 4 | from collections import defaultdict 5 | 6 | wordList = set(wordList) 7 | list1 = [] 8 | layer = {} 9 | layer[beginWord] = [[beginWord]] 10 | 11 | while layer: 12 | newlayer = defaultdict(list) 13 | for a in layer: 14 | if a == endWord: 15 | list1.extend(b for b in layer[a]) 16 | else: 17 | for i in range(len(a)): 18 | for j in 'abcdefghijklmnopqrstuvwxyz': 19 | new1 = a[:i]+j+a[i+1:] 20 | if new1 in wordList: 21 | newlayer[new1]+=[k+[new1] for k in layer[a]] 22 | 23 | wordList -= set(newlayer.keys()) 24 | layer = newlayer 25 | 26 | return list1 -------------------------------------------------------------------------------- /LeetCode/0134_Gas_Station.py: -------------------------------------------------------------------------------- 1 | """ 2 | 134. Gas Station Problem 3 | 4 | Problem:- 5 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 6 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). 7 | You begin the journey with an empty tank at one of the gas stations. 8 | Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. 9 | 10 | Input:- gas = [1,2,3,4,5], gas is the array consisting of the gas can get at i th stop 11 | cost= [3,4,5,1,2], cost is the array consisting of the cost to travel from i to i+1 index 12 | 13 | Output:- 3, we have to return the index from where we can start journey and traverse all stops in clockwise manner 14 | 15 | Time complexity :- O(N) where N is the number is the size of array(stops) 16 | Space complexity:- O(1) 17 | 18 | """ 19 | 20 | class Solution: 21 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 22 | # total_fuel variable is maintained to check if path is possible or not if sum(gas) < sum(cost) return -1 23 | n = len(gas) 24 | curr_fuel = 0 25 | total_fuel = 0 26 | start_idx = 0 27 | 28 | for i in range(n): 29 | curr_fuel += gas[i]-cost[i] 30 | total_fuel += gas[i]-cost[i] 31 | # at any index if fuel becomes less than 0 then we have to choose new starting index 32 | if curr_fuel < 0: 33 | # start_idx will be i+1 because at i th index out curr_fuel became < 0 34 | # so we start from any index between start_idx and i there will be no valid start_idx 35 | start_idx = i+1 36 | # reset the curr_fuel to 0 as we have chose new start_idx 37 | curr_fuel = 0 38 | # at last check if start_idx is less than n and total_fuel is not less than 0 return start_idx else -1 39 | return start_idx if start_idx < n and total_fuel>=0 else -1 40 | 41 | 42 | -------------------------------------------------------------------------------- /LeetCode/0136_Single_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums): 3 | singleNumber = nums[0] 4 | for i in range(1, len(nums)): 5 | singleNumber = singleNumber ^ nums[i] 6 | return singleNumber -------------------------------------------------------------------------------- /LeetCode/0137_Single_Number_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | used=[] 4 | for x in nums: 5 | if nums.count(x)==1: 6 | return x 7 | -------------------------------------------------------------------------------- /LeetCode/0138_Copy_List_with_Random_Pointer.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): 5 | self.val = int(x) 6 | self.next = next 7 | self.random = random 8 | """ 9 | 10 | def solve(head): 11 | d = {} 12 | h = head 13 | while(h): 14 | copy = Node(h.val) 15 | d[h] = copy 16 | h = h.next 17 | h = head 18 | while(h): 19 | copy = d[h] 20 | if(h.next): 21 | copy.next = d[h.next] 22 | if(h.random): 23 | copy.random = d[h.random] 24 | h = h.next 25 | if(head): 26 | return d[head] 27 | return None 28 | 29 | class Solution: 30 | def copyRandomList(self, head: 'Node') -> 'Node': 31 | return solve(head) 32 | -------------------------------------------------------------------------------- /LeetCode/0139_Word_Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | dic = {} 4 | for word in wordDict: 5 | if len(word) in dic: 6 | dic[len(word)].append(word) 7 | else: 8 | dic[len(word)] = [word] 9 | dp = [True] + [False] * len(s) 10 | for i in range(len(s)): 11 | for k in dic: 12 | if i - k + 1 >= 0 and dp[i - k + 1] and s[i - k + 1 : i + 1] in dic[k]: 13 | dp[i + 1] = True 14 | return dp[-1] 15 | -------------------------------------------------------------------------------- /LeetCode/0141_Linked_List_Cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | ''' 9 | Solution using Floyd's cycle-finding algorithm (tortoise and hare) 10 | ''' 11 | 12 | def hasCycle(self, head: ListNode) -> bool: 13 | if not head or not head.next: 14 | return False 15 | 16 | fast = slow = head 17 | while fast and fast.next: 18 | slow = slow.next 19 | fast = fast.next.next 20 | 21 | # If there is a cycle, fast will inevitably be on the same node as 22 | # slow. 23 | if fast is slow: 24 | return True 25 | return False 26 | 27 | 28 | class SolutionO1: 29 | ''' 30 | Solution to follow up. Disregards contents of each ListNode. 31 | ''' 32 | 33 | def hasCycle(self, head: ListNode) -> bool: 34 | while head: 35 | if head.val is None: 36 | return True 37 | head.val = None 38 | head = head.next 39 | return False 40 | -------------------------------------------------------------------------------- /LeetCode/0144_Binary_Tree_Preorder_Traversal.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | class Solution: 7 | def preorderTraversal(self, root: TreeNode) -> List[int]: 8 | self.ans=[] 9 | def preorder(root): 10 | if root is None: 11 | return 12 | self.ans.append(root.val) 13 | preorder(root.left) 14 | preorder(root.right) 15 | preorder(root) 16 | return self.ans -------------------------------------------------------------------------------- /LeetCode/0145_binary_tree_postorder_traversal.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def postorderTraversal(self, root): 3 | """ 4 | :type root: TreeNode 5 | :rtype: List[int] 6 | """ 7 | result, stack = [], [(root, False)] 8 | while stack: 9 | root, is_visited = stack.pop() 10 | if root is None: 11 | continue 12 | if is_visited: 13 | result.append(root.val) 14 | else: 15 | stack.append((root, True)) 16 | stack.append((root.right, False)) 17 | stack.append((root.left, False)) 18 | return result -------------------------------------------------------------------------------- /LeetCode/0146_LRU_Cache.py: -------------------------------------------------------------------------------- 1 | class LRUCache: 2 | 3 | def __init__(self, capacity: int): 4 | self.capacity = capacity 5 | self.cache = collections.OrderedDict() 6 | 7 | 8 | def get(self, key: int) -> int: 9 | if key not in self.cache: 10 | return -1 11 | else: 12 | val = self.cache[key] 13 | del self.cache[key] 14 | self.cache[key] = val 15 | return val 16 | 17 | def put(self, key: int, value: int) -> None: 18 | if key in self.cache: 19 | del self.cache[key] 20 | elif len(self.cache) == self.capacity: 21 | self.cache.popitem(last=False) 22 | self.cache[key] = value 23 | 24 | 25 | # Your LRUCache object will be instantiated and called as such: 26 | # obj = LRUCache(capacity) 27 | # param_1 = obj.get(key) 28 | # obj.put(key,value) 29 | -------------------------------------------------------------------------------- /LeetCode/0151_Reverse_Words_in_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s): 3 | list_of_string = s.split(' ') 4 | #appliying filter function to remove extraspaces from list 5 | new_list = list(filter(lambda x : True if (x!="") else False, list_of_string)) 6 | #taking reverse of output list 7 | new_list.reverse() 8 | #joining the elements if list 9 | final_string = " ".join(str(k) for k in new_list) 10 | return final_string 11 | -------------------------------------------------------------------------------- /LeetCode/0155_Min_stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.stack = [] 8 | 9 | 10 | def push(self, x: int) -> None: 11 | self.stack.append(x) 12 | 13 | 14 | def pop(self) -> None: 15 | self.stack.pop() # = self.stack[:-1] #pop() 16 | 17 | 18 | def top(self) -> int: 19 | return self.stack[-1] 20 | 21 | 22 | 23 | def getMin(self) -> int: 24 | return min(self.stack) 25 | 26 | 27 | 28 | # Your MinStack object will be instantiated and called as such: 29 | # obj = MinStack() 30 | # obj.push(x) 31 | # obj.pop() 32 | # param_3 = obj.top() 33 | # param_4 = obj.getMin() 34 | -------------------------------------------------------------------------------- /LeetCode/0165_Compare_Version_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compareVersion(self, version1: str, version2: str) -> int: 3 | v1 = version1.split(".") 4 | v2 = version2.split(".") 5 | while len(v1) < len(v2): 6 | v1.append("0") 7 | while len(v2) < len(v1): 8 | v2.append("0") 9 | for i in range(len(v1)): 10 | a = int(v1[i]) 11 | b = int(v2[i]) 12 | if a != b: 13 | return (a-b)//abs(a-b) 14 | return 0 15 | -------------------------------------------------------------------------------- /LeetCode/0167_Two_Sum_II.py: -------------------------------------------------------------------------------- 1 | # Problem name : Two Sum II - Input array is sorted 2 | # Problem link : https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 3 | # Contributor : Herumb Shandilya 4 | 5 | class Solution: 6 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 7 | for x in numbers: 8 | if x > target: 9 | break 10 | else: 11 | if target - x == x: 12 | return (numbers.index(x)+1,numbers.index(x)+2) 13 | else: 14 | if target - x in numbers: 15 | return(numbers.index(x)+1,numbers.index(target - x)+1) -------------------------------------------------------------------------------- /LeetCode/0169_Majority_Element.py: -------------------------------------------------------------------------------- 1 | # this class will give us a solution 2 | class Solution: 3 | 4 | # the function to find the majority element 5 | def majorityElement(self, arr): 6 | """ 7 | finds the majority element in the arr 8 | :param arr: List[int] a list with elements 9 | :return: int , the majority element 10 | """ 11 | 12 | # a dictionary of numbers we have seen 13 | seen_numbers = {} 14 | 15 | if len(arr) <= 2: 16 | return arr[0] 17 | 18 | # goes through the list of numbers and count the appearance amount 19 | for num in arr: 20 | # adds it to the dictionary 21 | if num not in seen_numbers: 22 | seen_numbers[num] = 1 23 | else: 24 | if (seen_numbers[num] + 1) >= (len(arr) / 2): 25 | return num 26 | else: 27 | # adds one to the counter 28 | seen_numbers[num] += 1 29 | -------------------------------------------------------------------------------- /LeetCode/0174_Dungeon_Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: 3 | R, C = len(dungeon), len(dungeon[0]) 4 | hi = [sum([r for r in row if r<0]+[0]) for row in dungeon] 5 | if not hi:return 1 6 | else: hi = sum(hi) 7 | lo, hi = 1, -hi+1 8 | 9 | def dp(mid): 10 | dp = [[-float('inf')]*(C+1) for _ in range(R+1)] 11 | dp[1][1] = mid + dungeon[0][0] 12 | if dp[1][1]<=0:return False 13 | for i in range(1, R+1): 14 | for j in range(1, C+1): 15 | this_val = max(dp[i][j-1], dp[i-1][j])+dungeon[i-1][j-1] 16 | if this_val > 0:dp[i][j] = this_val 17 | return dp[R][C]>0 18 | 19 | while lo < hi: 20 | mid = (lo+hi)//2 21 | if dp(mid): 22 | hi = mid 23 | else: 24 | lo = mid+1 25 | return lo 26 | -------------------------------------------------------------------------------- /LeetCode/0189_Rotate_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | for i in range(k): 4 | lastValue = nums.pop() 5 | nums.insert(0, lastValue) 6 | return nums -------------------------------------------------------------------------------- /LeetCode/0190_Reverse_bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | 4 | s='{0:032b}'.format(n)[::-1] 5 | return int(s,2) -------------------------------------------------------------------------------- /LeetCode/0191_Number_of_1_bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | 4 | return '{0:b}'.format(n).count('1') -------------------------------------------------------------------------------- /LeetCode/0198_House_Robber.py: -------------------------------------------------------------------------------- 1 | def rob(self, nums: List[int]) -> int: 2 | length = len(nums) 3 | if length == 0: 4 | return 0 5 | dp = [0] * len(nums) 6 | dp[0] = nums[0] 7 | for i in range(1,length): 8 | if i==1: 9 | dp[i] = max(dp[0],nums[i]) 10 | elif i==2: 11 | dp[i] = dp[0]+nums[i] 12 | else: 13 | dp[i] = max(dp[i-2],dp[i-3]) + nums[i] 14 | return max(dp[length-1],dp[length-2]) 15 | 16 | ''' 17 | n = len(nums) 18 | Time complexity = O(n) 19 | Space complexity = O(n) 20 | ''' -------------------------------------------------------------------------------- /LeetCode/0200_Number_of_Islands.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numIslands(self, grid): 3 | """ 4 | :type grid: List[List[str]] 5 | :rtype: int 6 | """ 7 | cnt = 0 8 | 9 | for i in range(len(grid)): 10 | for j in range(len(grid[i])): 11 | if grid[i][j] == "1": 12 | cnt += 1 13 | self.removeIsland(grid, i, j) 14 | return cnt 15 | 16 | # recursive function for replacing adjacent "1"s 17 | def removeIsland(self, grid, i, j): 18 | if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]): 19 | return 20 | if grid[i][j] == "0": 21 | return 22 | grid[i][j] = "0" 23 | self.removeIsland(grid, i+1, j) 24 | self.removeIsland(grid, i-1, j) 25 | self.removeIsland(grid, i, j+1) 26 | self.removeIsland(grid, i, j-1) 27 | -------------------------------------------------------------------------------- /LeetCode/0202_Happy_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isHappy(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | checked = [] 8 | while n != 1 and n not in checked: 9 | checked.append(n) 10 | n = sum([int(i) ** 2 for i in str(n)]) 11 | if n == 1: 12 | return True 13 | return False -------------------------------------------------------------------------------- /LeetCode/0203_Remove_Linked_List_Elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution(object): 8 | def removeElements(self, head, val): 9 | """ 10 | :type head: ListNode 11 | :type val: int 12 | :rtype: ListNode 13 | """ 14 | while head: 15 | if head.val == val: 16 | head = head.next 17 | else: 18 | break 19 | currentNode = head 20 | while currentNode: 21 | while currentNode.next and currentNode.next.val == val: 22 | currentNode.next = currentNode.next.next 23 | 24 | currentNode = currentNode.next 25 | return head 26 | -------------------------------------------------------------------------------- /LeetCode/0206_Reverse_Linked_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def reverseList(self, head, auxNode=None): #recursive mode 8 | if(head==None): 9 | return auxNode 10 | else: 11 | return self.reverseList(head.next, ListNode(head.val, auxNode)) 12 | """ 13 | :type head: ListNode 14 | :rtype: ListNode 15 | """ -------------------------------------------------------------------------------- /LeetCode/0208_Implement_Trie.py.py: -------------------------------------------------------------------------------- 1 | class TrieNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.isEnd = False 5 | self.children = [None for i in range(26)] 6 | class Trie: 7 | def __init__(self): 8 | """ 9 | Initialize your data structure here. 10 | """ 11 | self.root = TrieNode('*') 12 | 13 | 14 | def insert(self, word: str) -> None: 15 | """ 16 | Inserts a word into the trie. 17 | """ 18 | node = self.root 19 | for c in word: 20 | x = ord(c) - ord('a') 21 | if node.children[x] is None: 22 | node.children[x] = TrieNode(c) 23 | node = node.children[x] 24 | node.isEnd = True 25 | 26 | def search(self, word: str) -> bool: 27 | """ 28 | Returns if the word is in the trie. 29 | """ 30 | node = self.root 31 | for c in word: 32 | x = ord(c) - ord('a') 33 | if node.children[x] is not None: 34 | node = node.children[x] 35 | else: 36 | return False 37 | return node.isEnd 38 | 39 | 40 | def startsWith(self, prefix: str) -> bool: 41 | """ 42 | Returns if there is any word in the trie that starts with the given prefix. 43 | """ 44 | node = self.root 45 | for c in prefix: 46 | x = ord(c) - ord('a') 47 | if node.children[x] is not None: 48 | node = node.children[x] 49 | else: 50 | return False 51 | return True 52 | 53 | 54 | # Your Trie object will be instantiated and called as such: 55 | # obj = Trie() 56 | # obj.insert(word) 57 | # param_2 = obj.search(word) 58 | # param_3 = obj.startsWith(prefix) -------------------------------------------------------------------------------- /LeetCode/0212_Word_search_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def neighbours(self, i): 3 | n = [] 4 | if i >= self.cols: 5 | n.append(i-self.cols) 6 | if i + self.cols < self.rows * self.cols: 7 | n.append(i+self.cols) 8 | if i % self.cols > 0: 9 | n.append(i-1) 10 | if i % self.cols < self.cols - 1: 11 | n.append(i+1) 12 | return n 13 | 14 | def search(self, s): 15 | if len(self.words) == 0: 16 | return False 17 | l = 0 18 | r = len(self.words) - 1 19 | while l <= r-1: 20 | c = (l+r)//2 21 | if self.words[c] < s: 22 | l = c+1 23 | else: 24 | r = c 25 | if len(self.words[l]) < len(s): 26 | return False 27 | return self.words[l][:len(s)] == s 28 | 29 | def DFS(self, v, s): 30 | if not self.search(s): 31 | return 32 | if s in self.words and s not in self.found: 33 | self.found.append(s) 34 | ne = self.neighbours(v) 35 | for n in ne: 36 | if self.used[n]: 37 | continue 38 | self.used[n] = True 39 | self.DFS(n, s + self.board[n]) 40 | self.used[n] = False 41 | 42 | 43 | def findWords(self, board, words): 44 | self.found = [] 45 | self.words = sorted(words) 46 | self.rows = len(board) 47 | self.cols = len(board[0]) 48 | self.board = [board[i][j] for i in range(len(board)) for j in range(len(board[0]))] 49 | self.used = [False] * self.cols * self.rows 50 | for i in range(len(self.board)): 51 | self.used[i] = True 52 | self.DFS(i, self.board[i]) 53 | self.used[i] = False 54 | return self.found 55 | 56 | -------------------------------------------------------------------------------- /LeetCode/0215_Kth_Largest_Element_In_An_Array.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | def findKthLargest(self, nums: List[int], k: int) -> int: 4 | heapq.heapify(nums) 5 | res = heapq.nlargest(k,nums) 6 | return res[len(res)-1] -------------------------------------------------------------------------------- /LeetCode/0216_Combination_Sum_III.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def combinationSum3(self, k, n): 3 | ret = [] 4 | self.dfs(list(range(1, 10)), k, n, [], ret) 5 | return ret 6 | 7 | def dfs(self, nums, k, n, path, ret): 8 | if k < 0 or n < 0: 9 | return 10 | if k == 0 and n == 0: 11 | ret.append(path) 12 | for i in range(len(nums)): 13 | self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret) -------------------------------------------------------------------------------- /LeetCode/0217_Contains_Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | Set=set(nums) 4 | if len(Set)==len(nums): 5 | return False 6 | else: 7 | return True 8 | 9 | -------------------------------------------------------------------------------- /LeetCode/0219_ContainsDuplicateII.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | if k < 1: 4 | return False 5 | seen = set() 6 | for i, n in enumerate(nums): 7 | if n in seen: 8 | return True 9 | if i >= k: 10 | seen.remove(nums[i-k]) 11 | seen.add(n) 12 | return False 13 | -------------------------------------------------------------------------------- /LeetCode/0220_Contains_Duplicate_III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: 3 | if t < 0 or not nums or k <= 0: 4 | return False 5 | buckets = {} 6 | width = t + 1 7 | 8 | for n, i in enumerate(nums): 9 | buck = i // width 10 | if buck in buckets: 11 | return True 12 | else: 13 | buckets[buck] = i 14 | if buck - 1 in buckets and i - buckets[buck-1] <= t: 15 | return True 16 | if buck + 1 in buckets and buckets[buck+1] - i <= t: 17 | return True 18 | if n >= k: 19 | del buckets[nums[n-k] // width] 20 | return False -------------------------------------------------------------------------------- /LeetCode/0222_Count_Complete_Tree_Nodes.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def countNodes(self, root: TreeNode) -> int: 9 | 10 | if root == None: return 0 11 | right, left = root, root 12 | h_l , h_r = 0, 0 13 | 14 | while left != None: 15 | h_l +=1 16 | left = left.left 17 | 18 | while right != None: 19 | h_r +=1 20 | right = right.right 21 | 22 | 23 | if (h_l == h_r) : return(1 << h_l) -1 24 | 25 | return 1+ self.countNodes(root.left) + self.countNodes(root.right) 26 | -------------------------------------------------------------------------------- /LeetCode/0231_Power_Of_Two.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, x: int) -> bool: 3 | return (x != 0) and ((x & (x - 1)) == 0); -------------------------------------------------------------------------------- /LeetCode/0233_Number_of_Digit_One.py: -------------------------------------------------------------------------------- 1 | # Denote the number of 1 less than or equal to a given number 2 | # Eg) 3 | # Input: 13 4 | # Output: 6 5 | # Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 6 | 7 | class Solution(object): 8 | def countDigitOne(self, n): 9 | number = 0 10 | i = 1 11 | while(i <= n): 12 | divider = i * 10 13 | number += (int(n / divider) * i + 14 | min(max(n % divider -i + 15 | 1, 0), i)) 16 | i *= 10 17 | 18 | return number -------------------------------------------------------------------------------- /LeetCode/0234_Palindrome_Linked_List_.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | 9 | def reverse(self, head): 10 | p = head.next 11 | while p and p.next: 12 | tmp = p.next 13 | p.next = p.next.next 14 | tmp.next = head.next 15 | head.next = tmp 16 | 17 | def isPalindrome(self, head): 18 | """ 19 | :type head: ListNode 20 | :rtype: bool 21 | """ 22 | 23 | #get middle pointer 24 | p1 = ListNode(0) 25 | p1.next = head 26 | p2 = p1 27 | while p2 and p2.next: 28 | p1 = p1.next 29 | p2 = p2.next.next 30 | 31 | # reverse second half of list 32 | self.reverse(p1) 33 | 34 | # check palindrome 35 | p1 = p1.next 36 | p2 = head 37 | while p1: 38 | if p1.val != p2.val: 39 | return False 40 | p1 = p1.next 41 | p2 = p2.next 42 | return True -------------------------------------------------------------------------------- /LeetCode/0237_Delete_Node_in_a_Linked_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def deleteNode(self, node): 9 | """ 10 | :type node: ListNode 11 | :rtype: void Do not return anything, modify node in-place instead. 12 | """ 13 | node.val = node.next.val 14 | node.next = node.next.next 15 | -------------------------------------------------------------------------------- /LeetCode/0242_Valid_anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | 4 | return (sorted(s) == sorted(t)) -------------------------------------------------------------------------------- /LeetCode/0257_Binary_Tree_Paths.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def __init__(self): 9 | self.listOfPaths = [] #this list will save all paths and return 10 | 11 | def binaryTreePaths(self, root: TreeNode, path="") -> List[str]: 12 | if(root==None): 13 | return [] #nothing to return (it's a empty node) ... 14 | 15 | path += " " + str(root.val)#actual node value becomes a 'element route' 16 | 17 | if(root.left==None and root.right==None): 18 | self.listOfPaths.append(path[1:].replace(" ", "->"))#question output format 19 | 20 | else: 21 | self.binaryTreePaths(root.left, path) #scan by route in left node 22 | self.binaryTreePaths(root.right, path)#scan by route in right node 23 | return self.listOfPaths #return all paths 24 | 25 | -------------------------------------------------------------------------------- /LeetCode/0258_Add_Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | if num < 10: return num 4 | if num % 9 == 0: return 9 5 | return num % 9 6 | -------------------------------------------------------------------------------- /LeetCode/0260_Single_Number_III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, N: List[int]) -> int: 3 | L, d = len(N), set() 4 | for n in N: 5 | if n in d: d.remove(n) 6 | else: d.add(n) 7 | return d -------------------------------------------------------------------------------- /LeetCode/0268_Missing_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def computeXOR(self,n:int) -> int: 3 | if n%4==0: 4 | return n 5 | elif n%4==1: 6 | return 1 7 | elif n%4==2: 8 | return n+1 9 | else: 10 | return 0 11 | def missingNumber(self, nums: List[int]) -> int: 12 | all_xor = self.computeXOR(len(nums)) 13 | current_xor = 0 14 | for i in nums: 15 | current_xor^=i 16 | return(all_xor^current_xor) -------------------------------------------------------------------------------- /LeetCode/0274_H_Index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | citations.sort() 4 | n = len(citations) 5 | if n==0: 6 | return 0 7 | if set(citations) == {0}: 8 | return 0 9 | for i in range(n): 10 | if n-i<=citations[i]: 11 | return n-i -------------------------------------------------------------------------------- /LeetCode/0278_First_Bad_Version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return an integer 4 | # def isBadVersion(version): 5 | 6 | class Solution: 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | l, r, ans = 1, n, -1 13 | while l <= r: 14 | mid = (l + r) // 2 15 | if isBadVersion(mid): 16 | ans = mid 17 | r = mid - 1 18 | else: 19 | l = mid + 1 20 | 21 | return ans 22 | -------------------------------------------------------------------------------- /LeetCode/0279-PerfectSquares.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSquares(self, n): 3 | queue = collections.deque([(0, 0)]) 4 | visited = set() 5 | while queue: 6 | val, dis = queue.popleft() 7 | if val == n: 8 | return dis 9 | for i in range(1, n+1): 10 | j = val + i*i 11 | if j > n: 12 | break 13 | if j not in visited: 14 | visited.add(j) 15 | queue.append((j, dis+1)) -------------------------------------------------------------------------------- /LeetCode/0283_Move_Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | pos = 0 7 | for i in range(len(nums)): 8 | if nums[i]!= 0: 9 | if pos!=i: 10 | nums[pos], nums[i] = nums[i], nums[pos] 11 | pos += 1 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/0289_Game_of_Life.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def gameOfLife(self, board): 3 | self.m = len(board) 4 | self.n = len(board[0]) 5 | self.board = [rows.copy() for rows in board] 6 | for i in range(self.m): 7 | for j in range(self.n): 8 | state = self.board[i][j] 9 | dataDict = self.CheckNeighbors(i,j) 10 | nextGen = self.NextGenState(state,dataDict) 11 | board[i][j] = nextGen 12 | 13 | 14 | def CheckNeighbors(self,row,column): 15 | retDict = {"live":0,"dead":0} 16 | lb = max(column-1,0) 17 | rb = min(column+2,self.n) 18 | tb = max(row -1,0) 19 | bb = min(row+2,self.m) 20 | for rows in range(tb,bb): 21 | for columns in range(lb,rb): 22 | if rows != row or columns != column : 23 | neighbor = self.board[rows][columns] 24 | if neighbor == 1: 25 | retDict["live"] += 1 26 | else: 27 | retDict["dead"] += 1 28 | return retDict 29 | 30 | def NextGenState(self,state,dataDict): 31 | finalState = 0 32 | liveNeighbors = dataDict["live"] 33 | if state == 1: 34 | if liveNeighbors == 2 or liveNeighbors == 3: 35 | finalState = 1 36 | else: 37 | if liveNeighbors == 3: 38 | finalState = 1 39 | return finalState 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /LeetCode/0292_Nim_Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canWinNim(self, n: int) -> bool: 3 | return (n & 0b11) != 0 4 | 5 | 6 | print(Solution().canWinNim(7)) -------------------------------------------------------------------------------- /LeetCode/0299_Bulls_and_Cows.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def getHint(self, secret: str, guess: str) -> str: 4 | n = len(secret) 5 | matched = [] 6 | bulls = cows = 0 7 | for i in range(n): 8 | if secret[i] == guess[i]: 9 | bulls += 1 10 | 11 | a = Counter(secret) 12 | b = Counter(guess) 13 | 14 | for i in set(secret): 15 | cows += min(a[i], b[i]) 16 | 17 | ans = str(bulls) + "A" + str(cows - bulls) + "B" 18 | return ans -------------------------------------------------------------------------------- /LeetCode/0319_BulbSwitcher.py: -------------------------------------------------------------------------------- 1 | # The bulbs that will be turned on in the end will be the ones that are perfect squares. 2 | # So we just have to find the perfect square less than n; Square root of which will be the answer. 3 | # Contributed by: Sahil Bairagi 4 | 5 | class Solution: 6 | def bulbSwitch(self, n: int) -> int: 7 | return int(n**(0.5)) 8 | -------------------------------------------------------------------------------- /LeetCode/0326_Power_Of_Three.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer, write a function to determine if it is a power of three. 3 | 4 | Example 1: 5 | 6 | Input: 27 7 | Output: true 8 | Example 2: 9 | 10 | Input: 0 11 | Output: false 12 | Example 3: 13 | 14 | Input: 9 15 | Output: true 16 | Example 4: 17 | 18 | Input: 45 19 | Output: false 20 | Follow up: 21 | Could you do it without using any loop / recursion? 22 | """ 23 | class Solution(object): 24 | def isPowerOfThree(self, n): 25 | if n<1: 26 | return False 27 | elif n == 1: 28 | return True 29 | elif n == 2: 30 | return False 31 | else: 32 | while n > 2: 33 | a, b = divmod(n, 3) 34 | if b == 0: 35 | n = a 36 | else: 37 | break 38 | if n==1: 39 | return True 40 | else: 41 | return False 42 | 43 | -------------------------------------------------------------------------------- /LeetCode/0338_Counting_Bits.py: -------------------------------------------------------------------------------- 1 | def solve(n): 2 | dp = [0]*(n+1) 3 | offset = 1 4 | for i in range(1,n+1): 5 | if(not i&(i-1)): 6 | offset = i 7 | dp[i] = dp[i-offset] + 1 8 | return dp 9 | 10 | class Solution: 11 | def countBits(self, num: int) -> List[int]: 12 | return solve(num) 13 | -------------------------------------------------------------------------------- /LeetCode/0342_Power_Of_Four.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | #Solution without loops/recursion 4 | def isPowerOfFour(self, num: int) -> bool: 5 | if(num!=0): #number 0 there isn't in the logarithmic function domain! 6 | exponent = math.log(abs(num), 4) #I will discover the number which multiply 4 nth times. The result must be equal to num. Ex: 4^2 = 16 7 | #However, the exponent must to be an integer value for num to be a power of 4. For example, there are no 4's half number power! 8 | return int(math.pow(4, int(exponent)))==num 9 | return False #number zero was the input -------------------------------------------------------------------------------- /LeetCode/0343_Integer_Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def integerBreak(self, n: int) -> int: 3 | if n < 3: 4 | return 1 5 | if n == 3: 6 | return 2 7 | mylist = [1, 2, 3] 8 | for i in range(4, n+1): 9 | temp = [i] 10 | for j in range((i+1)//2): 11 | temp.append(mylist[j]*mylist[-j-1]) 12 | mylist.append(max(temp)) 13 | print(mylist, temp) 14 | return max(mylist) 15 | 16 | solution = Solution() 17 | print(solution.integerBreak(n =4)) -------------------------------------------------------------------------------- /LeetCode/0347_Top_K_Frequent_Elements.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 4 | count = Counter(nums) 5 | unique = list(count.keys()) 6 | 7 | def partition(left, right, pivot_index) -> int: 8 | pivot_frequency = count[unique[pivot_index]] 9 | # 1. move pivot to end 10 | unique[pivot_index], unique[right] = unique[right], unique[pivot_index] 11 | 12 | # 2. move all less frequent elements to the left 13 | store_index = left 14 | for i in range(left, right): 15 | if count[unique[i]] < pivot_frequency: 16 | unique[store_index], unique[i] = unique[i], unique[store_index] 17 | store_index += 1 18 | 19 | # 3. move pivot to its final place 20 | unique[right], unique[store_index] = unique[store_index], unique[right] 21 | 22 | return store_index 23 | 24 | def quickselect(left, right, k_smallest) -> None: 25 | """ 26 | Sort a list within left..right till kth less frequent element 27 | takes its place. 28 | """ 29 | # base case: the list contains only one element 30 | if left == right: 31 | return 32 | 33 | # select a random pivot_index 34 | pivot_index = random.randint(left, right) 35 | 36 | # find the pivot position in a sorted list 37 | pivot_index = partition(left, right, pivot_index) 38 | 39 | # if the pivot is in its final sorted position 40 | if k_smallest == pivot_index: 41 | return 42 | # go left 43 | elif k_smallest < pivot_index: 44 | quickselect(left, pivot_index - 1, k_smallest) 45 | # go right 46 | else: 47 | quickselect(pivot_index + 1, right, k_smallest) 48 | 49 | n = len(unique) 50 | # kth top frequent element is (n - k)th less frequent. 51 | # Do a partial sort: from less frequent to the most frequent, till 52 | # (n - k)th less frequent element takes its place (n - k) in a sorted array. 53 | # All element on the left are less frequent. 54 | # All the elements on the right are more frequent. 55 | quickselect(0, n - 1, n - k) 56 | # Return top k frequent elements 57 | return unique[n - k:] 58 | -------------------------------------------------------------------------------- /LeetCode/0367_ValidPerfectSquare.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPerfectSquare(self, num): 3 | """ 4 | :type num: int 5 | :rtype: bool 6 | """ 7 | 8 | i = 1 9 | sum_odds = 0 10 | while sum_odds < num: 11 | sum_odds += i 12 | if sum_odds == num: 13 | return True 14 | i += 2 15 | return False -------------------------------------------------------------------------------- /LeetCode/0368_Largest_Divisible_Subset.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestDivisibleSubset(self, nums: List[int]) -> List[int]: 3 | if len(nums) < 2: 4 | return nums 5 | #creating a monotonic sequence of list 6 | nums.sort() 7 | #creating a DP list to keep track of how many preceeding elements can divide ith element 8 | dp = [1]*len(nums) 9 | max_ind = 0 10 | #dp pass using the following condition 11 | for i in range(1, len(nums)): 12 | for j in range(i): 13 | if nums[i]%nums[j] == 0: 14 | dp[i] = max(dp[i], dp[j] + 1) 15 | if dp[max_ind] < dp[i]: 16 | max_ind = i 17 | res = [] 18 | res.append(nums[max_ind]) 19 | prev = nums[max_ind] 20 | #reconstructing the sequence by iterating backwards 21 | for i in range(max_ind - 1, -1, -1): 22 | if dp[i] > 0 and dp[max_ind]-1 == dp[i] and prev%nums[i] == 0: 23 | res.append(nums[i]) 24 | prev = nums[i] 25 | max_ind = i 26 | res.reverse() 27 | return res -------------------------------------------------------------------------------- /LeetCode/0371_sum_of_two_integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getSum(self, a: int, b: int) -> int: 3 | # 32 bits integer max and min 4 | MAX = 0x7FFFFFFF 5 | MIN = 0x80000000 6 | 7 | mask = 0xFFFFFFFF 8 | 9 | while b != 0: 10 | carry = a & b 11 | a, b = (a ^ b) & mask, (carry << 1) & mask 12 | 13 | return a if a <= MAX else ~(a ^ mask) -------------------------------------------------------------------------------- /LeetCode/0374_Guess_Number_Higher_or_Lower: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def guessNumber(self, n: int) -> int: 3 | l, r = 0, n 4 | while l <= r: 5 | m = (l + r)//2 6 | if guess(m) == 0: return m 7 | elif guess(m) == -1: 8 | r = m - 1 9 | else: 10 | l = m + 1 11 | return l 12 | -------------------------------------------------------------------------------- /LeetCode/0383_RansomNote.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 3 | return all( 4 | ransomNote.count(letter) <= magazine.count(letter) 5 | for letter in set(ransomNote) 6 | ) 7 | -------------------------------------------------------------------------------- /LeetCode/0389_FindTheDifference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | a = 0 4 | b = 0 5 | if 0 <= len(s) <= 1000: 6 | for chars in s: 7 | if 97 <= ord(chars) <= 122: 8 | a += ord(chars) 9 | for letters in t: 10 | if 97 <= ord(letters) <= 122: 11 | b += ord(letters) 12 | return chr(b - a) 13 | -------------------------------------------------------------------------------- /LeetCode/0401_Binary_Watch_.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def combination(self, n, k, inp, res): 3 | # inp is expected to be a list of size n 4 | #print n,k,inp,res 5 | if k == 0: 6 | res.append([i for i in inp]) 7 | return 8 | if k > n: 9 | return 10 | #for i in range(1,n+1): 11 | inp[n-1] = 1 12 | self.combination(n-1,k-1, inp, res) 13 | inp[n-1] = 0 14 | self.combination(n-1, k, inp, res) 15 | 16 | 17 | def getHours(self, h): 18 | if h == 0: 19 | return ["0"] 20 | if h == 1: 21 | return ["1", "2", "4", "8"] 22 | if h == 2: 23 | return ["3", "5", "6", "9", "10"] 24 | if h == 3: 25 | return ["7", "11"] 26 | 27 | def getMinutes(self, m): 28 | inp = [0,0,0,0,0,0] 29 | res = [] 30 | self.combination(6, m, inp, res) 31 | mins = [1, 2, 4, 8, 16, 32] 32 | minutes = [] 33 | for comb in res: 34 | i = 0 35 | mn = 0 36 | while i < 6: 37 | if comb[i] == 1: 38 | mn += mins[i] 39 | i += 1 40 | if mn > 59: 41 | continue 42 | if mn < 10: 43 | minutes.append("0" + str(mn)) 44 | else: 45 | minutes.append(str(mn)) 46 | return minutes 47 | 48 | def readBinaryWatch(self, num): 49 | """ 50 | :type num: int 51 | :rtype: List[str] 52 | """ 53 | i = 0 54 | res = [] 55 | 56 | while i <= num: 57 | h = i 58 | m = num - i 59 | if h < 4 and m < 6: 60 | lh = self.getHours(h) 61 | #print lh 62 | lm = self.getMinutes(m) 63 | #print lm 64 | for hr in lh: 65 | for mn in lm: 66 | res.append(hr + ":" + mn) 67 | i += 1 68 | 69 | return res 70 | -------------------------------------------------------------------------------- /LeetCode/0412_Fizz Buzz.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fizzBuzz(self, n): 3 | return [str(i) * (i % 3 != 0 and i % 5 != 0) + "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) 4 | for i in range(1, n + 1)] 5 | -------------------------------------------------------------------------------- /LeetCode/0414_Third_Maximum_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def thirdMax(self, nums: List[int]) -> int: 3 | nums_set = sorted(set(nums), reverse=True) 4 | if len(nums_set) >= 3: 5 | return nums_set[2] 6 | else: 7 | return nums_set[0] 8 | -------------------------------------------------------------------------------- /LeetCode/0437_Path_Sum_III.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | count = 0 9 | past_sums = {} 10 | 11 | def pathSum(self, root: TreeNode, sum: int) -> int: 12 | if root is not None: 13 | self.recurse(root, 0, sum) 14 | return self.count 15 | 16 | def recurse(self, node, summed, target): 17 | if node is None: 18 | return False 19 | else: 20 | summed += node.val 21 | if summed == target: 22 | self.count += 1 23 | if summed - target in self.past_sums: 24 | self.count += self.past_sums[summed - target] 25 | if summed in self.past_sums: 26 | self.past_sums[summed] += 1 27 | else: 28 | self.past_sums[summed] = 1 29 | self.recurse(node.left, summed, target) 30 | self.recurse(node.right, summed, target) 31 | self.past_sums[summed] -= 1 32 | -------------------------------------------------------------------------------- /LeetCode/0443_String_Compression.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compress(self, chars: List[str]) -> int: 3 | read = 0 4 | while read < len(chars) - 1: 5 | count = 1 6 | read_next = read + 1 7 | while read < len(chars) - 1 and chars[read_next] == chars[read]: 8 | del chars[read_next] 9 | count += 1 10 | if count > 1: 11 | for char in str(count): 12 | chars.insert(read_next, char) 13 | read_next += 1 14 | read = read_next 15 | return len(chars) 16 | 17 | -------------------------------------------------------------------------------- /LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | List=[] 4 | for i in range(len(nums)): 5 | val= abs(nums[i])-1 6 | if(nums[val]>0): 7 | nums[val]=-nums[val] 8 | for i in range(len(nums)): 9 | if(nums[i]>0): 10 | List.append(i+1) 11 | return List 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinArrowShots(self, points: List[List[int]]) -> int: 3 | if points == []: 4 | return 0 5 | points.sort(key = lambda x: x[0]) 6 | start = points[0][0] 7 | end = points[0][1] 8 | ans = len(points) 9 | for i in range(1, len(points)): 10 | if start <= points[i][0] <= end: 11 | ans -= 1 12 | if points[i][1] < end: 13 | end = points[i][1] 14 | else: 15 | start = points[i][0] 16 | end = points[i][1] 17 | 18 | return ans 19 | -------------------------------------------------------------------------------- /LeetCode/0456_Find_132_Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def find132pattern(self, nums: List[int]): 3 | if not nums or len(nums)< 2: 4 | return False 5 | 6 | m=0 7 | ln=len(nums) 8 | for i in range(len(nums)-1, -1, -1): 9 | n=nums[i] 10 | if i+1nums[i+1]: 11 | break 12 | else: 13 | m+=1 14 | else: 15 | return False 16 | 17 | ln-=m 18 | assert(ln and m) 19 | mi=ln 20 | s3mx=nums[ln-1] 21 | ln-=1 22 | 23 | s2mx=nums[mi] 24 | while mis2mx: 35 | s2mx=mx2 36 | elif n>s3mx: 37 | s2mx=s3mx 38 | s3mx=n 39 | while mimx2 and n bool: 5 | substringLength:int = 0 6 | substrings:List = [] 7 | 8 | while substringLength < len(s)/2: 9 | substringLength += 1 10 | if len(s)%substringLength != 0: 11 | continue 12 | 13 | substrings = textwrap.wrap(s, substringLength) 14 | if substrings[1:] == substrings[:-1] and len(substrings) > 1: 15 | return True 16 | 17 | return False 18 | -------------------------------------------------------------------------------- /LeetCode/0483_Smallest_Good_Base.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution(object): 4 | def smallestGoodBase(self, n): 5 | """ 6 | :type n: str 7 | :rtype: str 8 | """ 9 | n = int(n) 10 | 11 | for length in range(64, 2, -1): 12 | l = 2 13 | r = int(math.sqrt(n) + 1) 14 | 15 | def sum(mid): 16 | res = 0 17 | for i in range(length - 1, -1, -1): 18 | res += mid ** i 19 | if res > n: 20 | return res 21 | return res 22 | 23 | while l < r - 1: 24 | mid = (l + r) // 2 25 | if sum(mid) <= n: 26 | l = mid 27 | else: 28 | r = mid 29 | 30 | if sum(l) == n: 31 | return str(l) 32 | 33 | return str(n - 1) 34 | -------------------------------------------------------------------------------- /LeetCode/0500_Keyboard_Row.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def findWords(self, words: List[str]) -> List[str]: 4 | rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"] 5 | is_in_row = lambda word, row: all(letter in row for letter in set(word.lower())) 6 | return [word for word in words if any(is_in_row(word, row) for row in rows)] 7 | -------------------------------------------------------------------------------- /LeetCode/0521_Longest_Uncommon_Subsequence_I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLUSlength(self, a: str, b: str) -> int: 3 | if a != b: 4 | return max(len(a), len(b)) 5 | else: 6 | return -1 -------------------------------------------------------------------------------- /LeetCode/0532_K_diff_Pairs_in_an_Array.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def findPairs(self, nums: List[int], k: int) -> int: 4 | ans = 0 5 | c = Counter(nums) 6 | if k == 0: 7 | for val in c.values(): 8 | if val > 1: 9 | ans += 1 10 | return ans 11 | for i in c.keys(): 12 | if i + k in c.keys(): 13 | ans += 1 14 | return ans 15 | -------------------------------------------------------------------------------- /LeetCode/0537_Complex_Number_Multiplication.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def complexNumberMultiply(self, a: str, b: str) -> str: 4 | x = a.split('+') 5 | x[1] = x[1][:-1] 6 | 7 | y = b.split("+") 8 | y[1] = y[1][:-1] 9 | 10 | a_real = int(x[0]) 11 | a_img = int(x[1]) 12 | 13 | 14 | b_real = int(y[0]) 15 | b_img = int(y[1]) 16 | return str(a_real * b_real - a_img * b_img) + "+" + str(a_real * b_img + a_img * b_real) + "i"; 17 | 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/0551_ Student_Attendance_Record_I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkRecord(self, s: str) -> bool: 3 | aCount = 0; 4 | lCount = 0; 5 | for ch in s: 6 | if ch == "L": 7 | lCount += 1 8 | else: 9 | lCount = 0 10 | 11 | if ch == "A": 12 | aCount += 1 13 | 14 | if lCount > 2: 15 | return False 16 | if aCount > 1: 17 | return False 18 | 19 | return True 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/0561_Array_Partition_I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayPairSum(self, nums: List[int]) -> int: 3 | return sum(sorted(nums)[::2]) -------------------------------------------------------------------------------- /LeetCode/0567_Permutations_in_String.py: -------------------------------------------------------------------------------- 1 | #Sliding Window Approach 2 | from collections import Counter 3 | class Solution: 4 | def checkInclusion(self, s1, s2): 5 | d1, d2 = Counter(s1), Counter(s2[:len(s1)]) 6 | for start in range(len(s1), len(s2)): 7 | if d1 == d2: return True 8 | d2[s2[start]] += 1 9 | d2[s2[start-len(s1)]] -= 1 10 | if d2[s2[start-len(s1)]] == 0: 11 | del d2[s2[start-len(s1)]] 12 | return d1 == d2 -------------------------------------------------------------------------------- /LeetCode/0589_Nary_Tree_Preorder_Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def preorder(self, root): 3 | """ 4 | :type root: Node 5 | :rtype: List[int] 6 | """ 7 | def traverse(root): 8 | if not root: return 9 | ret.append(root.val) 10 | for child in root.children: 11 | traverse(child) 12 | 13 | ret = [] 14 | traverse(root) 15 | return ret 16 | -------------------------------------------------------------------------------- /LeetCode/0599_Minimum_Index_Sum_of_Two_Lists.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findRestaurant(self, list1, list2): 3 | ind1 = 0 4 | ind2 = 0 5 | ind_sum = sys.maxsize 6 | rest = list() 7 | 8 | for restaurant1 in list1: 9 | for restaurant2 in list2: 10 | if (restaurant1 == restaurant2) and ((ind1 + ind2) < ind_sum): 11 | ind_sum = ind1 + ind2 12 | rest = [] 13 | rest.append(restaurant2) 14 | elif (restaurant1 == restaurant2) and ((ind1 + ind2) == ind_sum): 15 | rest.append(restaurant2) 16 | ind2 = ind2 + 1 17 | ind1 = ind1 + 1 18 | ind2 = 0 19 | 20 | return rest -------------------------------------------------------------------------------- /LeetCode/0617_Merge_Two_Binary_Trees.py: -------------------------------------------------------------------------------- 1 | #Definition for a binary tree node. 2 | #class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | class Solution: 8 | def mergeTrees(self, t1, t2): 9 | """ 10 | :type t1: TreeNode 11 | :type t2: TreeNode 12 | :rtype: TreeNode 13 | """ 14 | if t1 is None: 15 | return t2 16 | if t2 is not None: 17 | t1.val += t2.val 18 | t1.left = self.mergeTrees(t1.left, t2.left) 19 | t1.right = self.mergeTrees(t1.right, t2.right) 20 | return t1 21 | -------------------------------------------------------------------------------- /LeetCode/0647_Palindromic_Substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | N = len(s) 4 | # declaring a DP matrix of size nxn 5 | dp = [[0 for i in range(N)] for j in range(N)] 6 | # looping through substring of every size and checking whether it is a valid substring 7 | for l in range(N): 8 | for i in range(N-l): 9 | if l == 0: 10 | dp[i][i] = 1 11 | continue 12 | if s[i] == s[i+l]: 13 | if l == 1: 14 | dp[i][i+l] = 1 15 | elif dp[i+1][i+l-1] == 1: 16 | dp[i][i+l] = 1 17 | count = 0 18 | for i in range(N): 19 | for j in range(N): 20 | count+=dp[i][j] 21 | return count -------------------------------------------------------------------------------- /LeetCode/0654_Maximum_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: 3 | def helper(nums, root): 4 | if not nums: 5 | return None 6 | if nums: 7 | root = TreeNode(max(nums)) 8 | ind=nums.index(max(nums)) 9 | root.left= helper(nums[:ind],root) 10 | root.right=helper(nums[ind+1:],root) 11 | return root 12 | root=TreeNode(0) 13 | return helper(nums,root) 14 | -------------------------------------------------------------------------------- /LeetCode/0686_Repeated_String_Match.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def repeatedStringMatch(self, a, b): 3 | """ 4 | :type a: str 5 | :type b: str 6 | :rtype: int 7 | """ 8 | # check for invalid inputs 9 | if (len(a) < 1) | (len(b) < 1) | (len(a) > 1e4) | (len(b) > 1e4): 10 | return -1 11 | 12 | # minimum repetitions of a for b to be a substring 13 | minRep = int(len(b)/len(a)) 14 | rep = minRep 15 | 16 | # increment the number of repetitions at most twice (as in the worst case below) 17 | # b b b b b b b b 18 | # a a a-a a a-a a a-a a a 19 | while (rep <= min( minRep + 2, 1e4 )) and not (b in a*(rep)): 20 | rep += 1 21 | 22 | # The cycle exits when b is a substring of a repeated or if all the possible concatenations have been already checked 23 | # In the second case, the output is set to -1 24 | if not (b in a*(rep)): 25 | rep = -1 26 | 27 | return rep -------------------------------------------------------------------------------- /LeetCode/0701_Insert_into_a_Binary_Search_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | def solve(r,k): 9 | x = TreeNode(k) 10 | ans = r 11 | if(not r): 12 | return x 13 | while(r and (r.left or r.right) ): 14 | if(r.val < k): 15 | if(r.right): 16 | r = r.right 17 | else: 18 | r.right = x 19 | return ans 20 | else: 21 | if(r.left): 22 | r = r.left 23 | else: 24 | r.left = x 25 | return ans 26 | if(r.val < k): 27 | r.right = x 28 | else: 29 | r.left = x 30 | return ans 31 | 32 | class Solution: 33 | def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: 34 | return solve(root,val) 35 | -------------------------------------------------------------------------------- /LeetCode/0728_Self_Dividing_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 3 | result = [] 4 | for i in range(left, right+1): 5 | for char in str(i): 6 | if int(char)==0 or i % int(char)!=0: 7 | break 8 | else: 9 | result.append(i) 10 | return result -------------------------------------------------------------------------------- /LeetCode/0741_CherryPickup.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cherryPickup(self, grid: List[List[int]]) -> int: 3 | n = len(grid) 4 | 5 | @lru_cache(None) 6 | def fn(t, i, ii): 7 | """Return maximum cherries collected at kth step when two robots are at ith and iith row""" 8 | j, jj = t - i, t - ii #columns 9 | if not (0 <= i < n and 0 <= j < n) or t < i or grid[ i][ j] == -1: return -inf #robot 1 not at proper location 10 | if not (0 <= ii < n and 0 <= jj < n) or t < ii or grid[ii][jj] == -1: return -inf #robot 2 not at proper location 11 | if t == 0: return grid[0][0] #starting from 0,0 12 | return grid[i][j] + (i != ii)*grid[ii][jj] + max(fn(t-1, x, y) for x in (i-1, i) for y in (ii-1, ii)) 13 | 14 | return max(0, fn(2*n-2, n-1, n-1)) -------------------------------------------------------------------------------- /LeetCode/0746_Min_Cost_Climbing_Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostClimbingStairs(self, cost: List[int]) -> int: 3 | l=len(cost) 4 | 5 | if l<=2: 6 | return 0 7 | a=[0]*l 8 | a[0]=cost[0] 9 | a[1]=cost[1] 10 | for i in range(2,l): 11 | a[i]=min(a[i-1],a[i-2])+cost[i] 12 | return min(a[l-1],a[l-2]) 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/0763_Partition_Labels.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeOverlappingSpans(self, spans): 3 | spans = sorted(spans) 4 | i, j = 0, 1 5 | while j < len(spans): 6 | if spans[i][1] < spans[j][0]: # Non Overlapping 7 | i += 1 8 | spans[i] = spans[j] 9 | else: 10 | spans[i][1] = max(spans[i][1], spans[j][1]) 11 | j += 1 12 | return spans[:i+1] 13 | 14 | def partitionLabels(self, S: str) -> List[int]: 15 | spans = {} 16 | for i in range (len(S)): 17 | if S[i] not in spans: 18 | spans[S[i]] = [i, i] 19 | else: 20 | spans[S[i]][1] = i 21 | 22 | # one span [startIndex, endIndex] for each unique character 23 | # there will be maximum 26 spans 24 | spans = spans.values() 25 | 26 | nonOverlappingSpans = self.mergeOverlappingSpans(spans) 27 | return [span[1]-span[0]+1 for span in nonOverlappingSpans] -------------------------------------------------------------------------------- /LeetCode/0771_Jewels_and_Stones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, J: str, S: str) -> int: 3 | stones = Counter(S) 4 | count = 0 5 | for j in J: 6 | if stones and j in stones: 7 | count += stones[j] 8 | return count 9 | -------------------------------------------------------------------------------- /LeetCode/0777_Swap_Adjacent_in_LR String.py: -------------------------------------------------------------------------------- 1 | # L can move left util L meets R. And R can move right util R meets L !! X is something that does not really need attention 2 | 3 | class Solution: 4 | def canTransform(self, start: str, end: str) -> bool: 5 | 6 | if start.replace('X', '') != end.replace('X', ''): 7 | return False 8 | 9 | m = collections.Counter() 10 | for s, e in zip(start, end): 11 | m[s] += 1 12 | m[e] -= 1 13 | if m['L'] > 0 or m['R'] < 0: 14 | return False 15 | return True -------------------------------------------------------------------------------- /LeetCode/0829_Consecutive_Numbers_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def consecutiveNumbersSum(self, N: int) -> int: 3 | count = 1 4 | L = 1 5 | while( L * (L + 1) < 2 * N): 6 | a = (1.0 * N - (L * (L + 1) ) / 2) / (L + 1) 7 | if (a ==int(a) ): 8 | count += 1 9 | L += 1 10 | return count 11 | -------------------------------------------------------------------------------- /LeetCode/0832_Flipping_an_Image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 3 | for row in A: 4 | for i in range(int((len(row) + 1) / 2)): 5 | """ 6 | In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] 7 | helps us find the i-th value of the row, counting from the right. 8 | """ 9 | row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 10 | return A 11 | -------------------------------------------------------------------------------- /LeetCode/0859_Buddy_String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buddyStrings(self, A: str, B: str) -> bool: 3 | if len(A) != len(B): 4 | return False 5 | char_count = {} 6 | indexes_to_swap = [] 7 | dup = False 8 | for idx, string in enumerate(A): 9 | curr_char_count = char_count.get(string, 0) 10 | curr_char_count += 1 11 | char_count[string] = curr_char_count 12 | if (curr_char_count > 1): 13 | dup = True 14 | if string != B[idx]: 15 | indexes_to_swap.append(idx) 16 | if len(indexes_to_swap) > 2: 17 | return False 18 | 19 | if len(indexes_to_swap) == 1: 20 | return False 21 | 22 | if len(indexes_to_swap) == 2: 23 | return A[indexes_to_swap[0]] == B[indexes_to_swap[1]] and A[indexes_to_swap[1]] == B[indexes_to_swap[0]] 24 | return dup 25 | -------------------------------------------------------------------------------- /LeetCode/0867_Transpose_Matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. 3 | 4 | Sample input: 5 | [[1,2,3], 6 | [4,5,6], 7 | [7,8,9]] 8 | 9 | Sample output: 10 | [[1,4,7], 11 | [2,5,8], 12 | [3,6,9]] 13 | """ 14 | 15 | class Solution: 16 | def transpose(self, A: List[List[int]]) -> List[List[int]]: 17 | transpose=[] 18 | k=0 19 | for p in range(len(A[0])): 20 | temp=[] 21 | for i in A: 22 | while k List[int]: 3 | total_a = sum(A) 4 | total_b = sum(B) 5 | set_b = set(B) 6 | for candy in A: 7 | swap_item = candy + (total_b - total_a) / 2 8 | if swap_item in set_b: 9 | return [candy, candy + (total_b - total_a) / 2] -------------------------------------------------------------------------------- /LeetCode/0891_Sum_of_Subsequence_Widths.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumSubseqWidths(self, A: List[int]) -> int: 3 | ret_int = 0 4 | A_len = len(A) 5 | A.sort(key=lambda x: int(x), reverse=True) 6 | 7 | for x in range(A_len): 8 | ret_int += A[x] * (2**(A_len - x - 1) - 2**(x)) 9 | 10 | return ret_int % (10**9 + 7) 11 | -------------------------------------------------------------------------------- /LeetCode/0929_Unique_Email_Addresses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numUniqueEmails(self, emails: List[str]) -> int: 3 | seen_emails = set() 4 | for item in emails: 5 | name, domain = item.split('@') 6 | special_index = name.find('+') 7 | if special_index != -1: 8 | name = name[: special_index] 9 | seen_emails.add(name.replace('.', '') + '@' + domain) 10 | return len(seen_emails) 11 | -------------------------------------------------------------------------------- /LeetCode/0933_Number_of_Recent_Calls.py: -------------------------------------------------------------------------------- 1 | class RecentCounter: 2 | 3 | def __init__(self): 4 | self.p = [] 5 | 6 | def ping(self, t: int) -> int: 7 | self.p.append(t) 8 | while self.p[0] < t - 3000: 9 | self.p.pop(0) 10 | return len(self.p) -------------------------------------------------------------------------------- /LeetCode/0938_Range_Sum_of_BST.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.ans = 0 4 | 5 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 6 | def dfs(node): 7 | if node: 8 | if L <= node.val <= R: 9 | self.ans += node.val 10 | if L < node.val: 11 | dfs(node.left) 12 | if node.val < R: 13 | dfs(node.right) 14 | dfs(root) 15 | return self.ans 16 | -------------------------------------------------------------------------------- /LeetCode/0942_DI_String_Match.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diStringMatch(self, S: str) -> List[int]: 3 | mx = 0 4 | mn = 0 5 | res = [0] * (len(S) + 1) 6 | for i in range(len(S)): 7 | if S[i] == "I": 8 | res[i + 1] = mx + 1 9 | mx += 1 10 | else: 11 | res[i + 1] = mn - 1 12 | mn -= 1 13 | return [x - mn for x in res] 14 | -------------------------------------------------------------------------------- /LeetCode/0949_Largest_Time_for_Given_Digits.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from typing import List 3 | 4 | class Solution: 5 | def largestTimeFromDigits(self, arr: List[int]) -> str: 6 | """ 7 | :type A: List[int] 8 | :rtype: str 9 | """ 10 | result = "" 11 | for i in range(len(arr)): 12 | arr[i] *= -1 13 | arr.sort() 14 | for h1, h2, m1, m2 in itertools.permutations(arr): 15 | hours = -(10*h1 + h2) 16 | mins = -(10*m1 + m2) 17 | if 0 <= hours < 24 and 0 <= mins < 60: 18 | result = "{:02}:{:02}".format(hours, mins) 19 | break 20 | return result 21 | 22 | 23 | print(Solution().largestTimeFromDigits([2,3,1,1])) -------------------------------------------------------------------------------- /LeetCode/0973_ K_Closest_Points_to_Origin.py: -------------------------------------------------------------------------------- 1 | from heapq import heappop, heappush 2 | from typing import List, Tuple 3 | 4 | 5 | class Solution: 6 | def closest_points(self, points: List[Tuple[float, float]], k: int) -> List[Tuple[float, float]]: 7 | """ 8 | Finds the K points closest to the origin. 9 | 10 | The implementation pushes the points on a Heap with their key being the distance to the origin, then removes K elements from the heap. 11 | I chose to go with a more verbose implementation to show how it can be done, but alternatively one could do: 12 | 13 | >>> from heapq import nsmallest 14 | ... nsmallest(k, points, key=self.distance) 15 | """ 16 | 17 | heap = [] 18 | for point in points: 19 | heappush(heap, (self.distance(point), point)) 20 | 21 | return [heappop(heap)[1] for _ in range(k)] 22 | 23 | def distance(self, point: Tuple[float, float]) -> float: 24 | """ 25 | Pythagorean formula to get the distance to the origin. 26 | """ 27 | 28 | return (point[0] ** 2 + point[1] ** 2) ** 0.5 29 | -------------------------------------------------------------------------------- /LeetCode/0980_Unique_Paths_III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | ans = 0 3 | def findPathNum(self, i, j, grid: List[List[int]], curLen, pLen)->None: 4 | if(grid[i][j]==2): 5 | if(pLen-1==curLen): 6 | self.ans+=1 7 | return 8 | elif (grid[i][j]==-1): 9 | return 10 | curLen+=1 11 | grid[i][j]=-1 12 | if(i-1>=0): 13 | self.findPathNum(i-1, j, grid, curLen, pLen) 14 | if(j-1>=0): 15 | self.findPathNum(i, j-1, grid, curLen, pLen) 16 | if(i+1 int: 24 | pathLen = 0 25 | start = (0, 0) 26 | for i in range(len(grid)): 27 | for j in range(len(grid[0])): 28 | if(grid[i][j]!=-1): 29 | pathLen+=1 30 | if(grid[i][j]==1): 31 | start = (i, j) 32 | self.findPathNum(start[0], start[1], grid, 0, pathLen) 33 | return self.ans 34 | 35 | -------------------------------------------------------------------------------- /LeetCode/0995_Minimum_Number_of_K_Consecutive_Bit_Flips.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minKBitFlips(self, A: List[int], K: int) -> int: 3 | n = len(A) 4 | flips = [0]*(n+1); ans = 0 5 | for i in range(n): 6 | flips[i] += flips[i-1] if i > 0 else 0 7 | 8 | if not A[i] ^ (flips[i]%2): 9 | if i + K - 1 >= n : 10 | print(i, K) 11 | return -1 12 | ans += 1 13 | flips[i] += 1 14 | flips[i+K] -= 1 15 | 16 | return ans 17 | 18 | -------------------------------------------------------------------------------- /LeetCode/0997_Find_The_Town_Judge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 3 | m=len(trust) 4 | if 1==N: 5 | if 0==m: 6 | return 1 7 | tmp={} 8 | dic={} 9 | for i in range(m): 10 | tmp[trust[i][0]]=1 11 | for i in range(m): 12 | if trust[i][1] not in tmp: 13 | if trust[i][1] not in dic: 14 | dic[trust[i][1]]=1 15 | else: 16 | dic[trust[i][1]]+=1 17 | for key in dic: 18 | if N-1==dic[key]: 19 | return key 20 | return -1 21 | 22 | -------------------------------------------------------------------------------- /LeetCode/1002_Find_Common_Character.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from functools import reduce 3 | class Solution: 4 | def commonChars(self, A: List[str]) -> List[str]: 5 | counted_elements = [Counter(s) for s in A] 6 | reduced_list = reduce(lambda x,y :x & y,counted_elements).elements() 7 | return reduced_list -------------------------------------------------------------------------------- /LeetCode/1009_Complement_of_base_10_integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bitwiseComplement(self, N: int) -> int: 3 | binary = bin(N)[2:] 4 | ans = ['0'] * len(binary) 5 | for i in range(len(binary)): 6 | if binary[i] == '0': 7 | ans[i] = '1' 8 | else: 9 | ans[i] = '0' 10 | return int(''.join(ans), 2) 11 | 12 | -------------------------------------------------------------------------------- /LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def prefixesDivBy5(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: List[bool] 6 | """ 7 | prev = 0 8 | for i in range(len(A)): 9 | prev = 2 * prev + A[i] 10 | A[i] = prev % 5 == 0 11 | return A 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/1023_Camelcase_Matching.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | class Solution: 4 | def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: 5 | p = re.findall('[A-Z][^A-Z]*', pattern) 6 | result = [] 7 | 8 | for x in queries: 9 | y = re.findall('[A-Z][^A-Z]*', x) 10 | if len(p) != len(y): 11 | result.append(False) 12 | 13 | else: 14 | q = [] 15 | 16 | for i in range(len(p)): 17 | t = 'false' 18 | pi = p[i] 19 | c = len(pi) 20 | ct = 0 21 | 22 | for j in y[i]: 23 | if j == pi[ct]: 24 | ct += 1 25 | if ct == c: 26 | t = 'true' 27 | break 28 | q.append(t) 29 | 30 | k = True 31 | if "false" in q: 32 | k = False 33 | 34 | result.append(k) 35 | return result 36 | -------------------------------------------------------------------------------- /LeetCode/1046_Last Stone Weight.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | class Solution: 3 | def lastStoneWeight(self, stones: List[int]) -> int: 4 | stones.sort() 5 | 6 | l=len(stones) 7 | while l>1: 8 | 9 | if stones[l-1]==stones[l-2]: 10 | stones.pop() 11 | stones.pop() 12 | l=l-2 13 | else: 14 | x=stones[l-1]-stones[l-2] 15 | 16 | stones.pop() 17 | stones.pop() 18 | bisect.insort(stones,x) 19 | l-=1 20 | try: 21 | return stones[0] 22 | except: 23 | return 0 24 | 25 | 26 | -------------------------------------------------------------------------------- /LeetCode/1053_Previous_Permutation_With_One_Swap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def prevPermOpt1(self, A: List[int]) -> List[int]: 3 | a_length = len(A) 4 | largest_left_index = 0 5 | largest_left = A[0] 6 | for i in range(2, a_length + 1): 7 | i *= -1 8 | if A[i] > A[i + 1]: 9 | largest_left_index = i 10 | largest_left = A[i] 11 | break 12 | 13 | largest_right_index = 0 14 | largest_right = 0 15 | for i in range(a_length + largest_left_index + 1, a_length): 16 | if A[i] > largest_right and A[i] < largest_left: 17 | largest_right_index = i 18 | largest_right = A[i] 19 | 20 | A[largest_left_index], A[largest_right_index] = A[largest_right_index], A[largest_left_index] 21 | return A 22 | -------------------------------------------------------------------------------- /LeetCode/1103_Distributing_Candies_to_people.py: -------------------------------------------------------------------------------- 1 | def distributeCandies(self, candies: int, num_people: int) -> List[int]: 2 | sum1, rounds, temp = sum(range(1, num_people + 1)), 0, candies 3 | # 1. get the number of rounds that will go through the array 4 | while temp > 0: 5 | temp -= sum1 + rounds * num_people ** 2 6 | rounds += 1 7 | rounds -= 1 8 | result = [0] * num_people 9 | # 2. add up the number until right before the final round 10 | if rounds > 0: 11 | for i in range(1, num_people + 1): 12 | result[i - 1] = (2 * i + (rounds - 1) * num_people) * rounds // 2 13 | candies -= result[i - 1] 14 | base_num = num_people * rounds 15 | # 3. add the final round of numbers 16 | for i in range(1, num_people + 1): 17 | if candies <= base_num + i: 18 | result[i - 1] += candies 19 | break 20 | else: 21 | result[i - 1] += base_num + i 22 | candies -= base_num + i 23 | return result -------------------------------------------------------------------------------- /LeetCode/1108_Defanging_an_IP_Address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | return(address.replace('.','[.]')) 4 | -------------------------------------------------------------------------------- /LeetCode/1137_N_th_Tribonacci_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def tribonacci(self, n: int) -> int: 3 | a, b, c = 0, 1, 1 4 | if n == 0: 5 | return 0 6 | elif n == 1 or n == 2: 7 | return 1 8 | else: 9 | for _ in range(n - 2): 10 | temp = a + b + c 11 | a = b 12 | b = c 13 | c = temp 14 | return temp 15 | -------------------------------------------------------------------------------- /LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countCharacters(self, words: List[str], chars: str) -> int: 3 | charBins = {char:chars.count(char) for char in chars} 4 | goodWords = [] 5 | 6 | for word in words: 7 | if (len(word) > len(chars)): 8 | continue 9 | 10 | if not set(word).issubset(chars): 11 | continue 12 | 13 | letterBins = {letter:word.count(letter) for letter in word} 14 | 15 | goodWord = True 16 | for letter in letterBins: 17 | if letterBins[letter] > charBins[letter]: 18 | goodWord = False 19 | 20 | if (goodWord): 21 | goodWords.append(word) 22 | 23 | return sum(len(word) for word in goodWords) 24 | -------------------------------------------------------------------------------- /LeetCode/1189_Maximum_Number_of_Balloons.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxNumberOfBalloons(self, text) -> int: 3 | """ 4 | :type text: str 5 | :rtype: int 6 | """ 7 | a_count = text.count("b") 8 | b_count = text.count("a") 9 | l_count = text.count("l") / 2 10 | o_count = text.count("o") / 2 11 | n_count = text.count("n") 12 | return int(min([a_count,b_count,l_count,o_count,n_count])) -------------------------------------------------------------------------------- /LeetCode/1219_path_with_maximum_gold.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMaximumGold(self, grid): 3 | def bfs(i, j): 4 | stack = [(grid[i][j], i, j, set([(i, j)]))] 5 | while stack: 6 | temp = [] 7 | for cur, i, j, p in stack: 8 | if cur > self.res: 9 | self.res = cur 10 | self.best_res = p 11 | for x, y in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]: 12 | if 0 <= x < m and 0 <= y < n and grid[x][y] and (x, y) not in p: 13 | temp.append((cur + grid[x][y], x, y, p | {(x, y)})) 14 | stack = temp 15 | m, n = len(grid), len(grid[0]) 16 | self.res = 0 17 | self.best_res = set() 18 | for row in range(m): 19 | for col in range(n): 20 | if grid[row][col] and (row, col) not in self.best_res: 21 | bfs(row, col) 22 | return self.res 23 | -------------------------------------------------------------------------------- /LeetCode/1221_Split_ a_String_in_Balanced_Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | r= 0 4 | l = 0 5 | count = 0 6 | for i in range(len(s)): 7 | if s[i] == "R": 8 | r += 1 9 | else: 10 | l += 1 11 | if r == l: 12 | count += 1 13 | return count 14 | -------------------------------------------------------------------------------- /LeetCode/1227_Airplane_Seat_Assignment_Probability.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nthPersonGetsNthSeat(self, n: int) -> float: 3 | if n == 1: 4 | return 1.0 5 | else: 6 | return 0.5 -------------------------------------------------------------------------------- /LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minRemoveToMakeValid(self, s: str) -> str: 3 | 4 | stackparen = [] 5 | stackindex = [] 6 | result = '' 7 | result1 = '' 8 | i = 0 9 | j = 0 10 | 11 | while i <= len(s) - 1: 12 | if s[i] == ')' and len(stackparen) == 0: 13 | i += 1 14 | continue 15 | if s[i] == '(': 16 | stackparen.append(s[i]) 17 | stackindex.append(j) 18 | if s[i] == ')' and len(stackparen) > 0: 19 | stackparen.pop() 20 | stackindex.pop() 21 | result += s[i] 22 | j += 1 23 | i += 1 24 | 25 | for j, i in enumerate(result): 26 | if j not in stackindex: 27 | result1 += result[j] 28 | return result1 29 | -------------------------------------------------------------------------------- /LeetCode/1250_Check_If_It_Is_a_Good_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isGoodArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | def gcd(a, b): 8 | if a == 0: 9 | return b 10 | if a > b: 11 | return gcd(b, a) 12 | return gcd(b % a, a) 13 | 14 | return reduce(gcd, nums) == 1 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/1252_Cells_with_Odd_Values_in_a_Matrix.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | class Solution: 4 | 5 | def get_summation_matrix(self, n: int, m: int, ri: int, ci: int): 6 | mat = np.zeros([n, m], dtype=int) 7 | mat[ri,:] += 1 8 | mat[:,ci] += 1 9 | return mat 10 | 11 | def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: 12 | matrix_inc = sum(self.get_summation_matrix(n, m, ri, ci) for ri, ci in indices) 13 | return np.count_nonzero(matrix_inc % 2 == 1) 14 | -------------------------------------------------------------------------------- /LeetCode/1276_Number_of_Burgers_with_No_Waste_of_Ingredients.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: 3 | t=tomatoSlices 4 | c=cheeseSlices 5 | return [int(t / 2 - c), int(c * 2 - t / 2)] if t % 2 == 0 and c * 2 <= t <= c * 4 else [] 6 | -------------------------------------------------------------------------------- /LeetCode/1281_Subtract_the_Product_and_Sum_of_Digits_of_an_Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subtractProductAndSum(self, n: int) -> int: 3 | a = 1 4 | b = 0; 5 | while(n): 6 | a*=n%10 7 | b+=n%10 8 | n//=10 9 | return a - b 10 | 11 | -------------------------------------------------------------------------------- /LeetCode/1282_Group_People_Given_the_Group_Size_They_Belong_To.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: 3 | maxGroupSize= max(groupSizes) 4 | groups = [[] for i in range(maxGroupSize)] 5 | 6 | for i, p in enumerate(groupSizes): 7 | groups[p-1].append(i) 8 | if len(groups[p-1]) == p: 9 | groups.append(groups[p-1]) 10 | groups[p-1] = [] 11 | 12 | return groups[maxGroupSize:] 13 | -------------------------------------------------------------------------------- /LeetCode/1288_Remove_Covered_Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: 3 | intervals.sort(key=lambda x: (x[0], -x[1])) 4 | inside = 0 5 | right = -1 6 | for i, j in intervals: 7 | if j <= right: 8 | inside += 1 9 | else: 10 | right = j 11 | return len(intervals) - inside 12 | -------------------------------------------------------------------------------- /LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def replaceElements(self, arr): 3 | for i in range(len(arr)): 4 | if i==len(arr)-1: 5 | arr[i] = -1 6 | else: 7 | arr[i] = max(arr[i+1:]) 8 | return arr -------------------------------------------------------------------------------- /LeetCode/1340_Jump_Game_V.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxJumps(self, arr: List[int], d: int) -> int: 3 | dp = [1] * len(arr) 4 | 5 | for i, _ in sorted(enumerate(arr), key=lambda x: x[1]): 6 | max_h = 0 7 | for j in range(i - 1, max(i - d - 1, -1), -1): 8 | max_h = max(max_h, arr[j]) 9 | if max_h < arr[i]: 10 | dp[i] = max(dp[i], dp[j] + 1) 11 | else: 12 | break 13 | 14 | max_h = 0 15 | for j in range(i + 1, min(i + d + 1, len(arr))): 16 | max_h = max(max_h, arr[j]) 17 | if max_h < arr[i]: 18 | dp[i] = max(dp[i], dp[j] + 1) 19 | else: 20 | break 21 | 22 | return max(dp) 23 | -------------------------------------------------------------------------------- /LeetCode/1346_Check_if_N_and_its_Double_Exist.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkIfExist(self, arr: List[int]) -> bool: 3 | 4 | seen = set() 5 | for x in arr: 6 | if x * 2 in seen or (not x % 2 and x // 2 in seen): 7 | return True 8 | seen.add(x) 9 | return False 10 | -------------------------------------------------------------------------------- /LeetCode/1351_Count_Negative_Numbers_in_Sorted_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countNegatives(self, grid: List[List[int]]) -> int: 3 | count = 0 4 | for row in grid: 5 | for index in range(len(row)-1, -1, -1): 6 | if row[index] < 0: 7 | count += 1 8 | else: 9 | break 10 | 11 | return count -------------------------------------------------------------------------------- /LeetCode/1363_Largest_Multiple_of_Three.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestMultipleOfThree(self, digits: List[int]) -> str: 3 | digits.sort(reverse=True) 4 | N = len(digits) 5 | dp = [[float('-inf')] * N for _ in range(3)] 6 | for n in range(N): 7 | for k in [0, 1, 2, 0]: 8 | if n == 0 or (dp[k][n-1] == float('-inf') and dp[(k - digits[n]) % 3][n-1] == float('-inf')): 9 | if digits[n] % 3 == k: 10 | dp[k][n] = digits[n] 11 | else: 12 | if digits[n] % 3 == 0: 13 | dp[k][n] = dp[k][n-1] * 10 + digits[n] 14 | else: 15 | dp[k][n] = max(dp[k][n-1], dp[(k - digits[n]) % 3][n-1] * 10 + digits[n]) 16 | 17 | return str(dp[0][-1]) if dp[0][-1] != float('-inf') else '' 18 | -------------------------------------------------------------------------------- /LeetCode/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: 3 | ans = [] 4 | for i in range(0, len(nums)): 5 | soln = 0 6 | for j in range(0, len(nums)): 7 | if(nums[j] < nums[i] and j != i): 8 | soln += 1 9 | ans. append(soln) 10 | return ans -------------------------------------------------------------------------------- /LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateTheString(self, n: int) -> str: 3 | ans=[] 4 | if n%2==0: 5 | ans=['x' for i in range(n-1)] 6 | ans.append('y') 7 | else: 8 | ans=['x' for i in range(n)] 9 | return ans 10 | -------------------------------------------------------------------------------- /LeetCode/1380_Lucky_Numbers_in_a_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: 3 | min_n = {min(rows) for rows in matrix} 4 | max_n = {max(columns) for columns in zip(*matrix)} 5 | 6 | return list(min_n & max_n) 7 | 8 | -------------------------------------------------------------------------------- /LeetCode/1402_Reducing_Dishes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSatisfaction(self, satisfaction: List[int]) -> int: 3 | 4 | satisfaction.sort(reverse=True) 5 | ans = cur_sum = 0 6 | for ele in satisfaction: 7 | cur_sum += ele 8 | if cur_sum >= 0: 9 | ans += cur_sum 10 | 11 | return ans; -------------------------------------------------------------------------------- /LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: 3 | m=max(candies) 4 | t=m-extraCandies 5 | output=[] 6 | for i in candies: 7 | if i List[str]: 3 | res = [] 4 | j = 0 5 | for i in range(1,n+1): 6 | res.append("Push") 7 | if i == target[j]: 8 | j += 1 9 | else: 10 | res.append("Pop") 11 | if j == len(target): 12 | break 13 | return res -------------------------------------------------------------------------------- /LeetCode/1446_consecutive_characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPower(self, s: str) -> int: 3 | maxlen,currlen=1,1 4 | for i in range(1,len(s)): 5 | if(s[i]==s[i-1]): 6 | currlen=currlen+1 7 | maxlen=max(maxlen,currlen) 8 | else: 9 | currlen=1 10 | return maxlen -------------------------------------------------------------------------------- /LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 5 | return Counter(target) == Counter(arr) -------------------------------------------------------------------------------- /LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | nums.sort() 4 | return (nums[-1]-1) * (nums[-2]-1) -------------------------------------------------------------------------------- /LeetCode/1470_Shuffle_The_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shuffle(self, nums: List[int], n: int) -> List[int]: 3 | shuffled_list = [0]*(2*n) 4 | left_index = 0 5 | right_index = n 6 | for index in range(0, 2*n): 7 | if index%2 == 0: 8 | shuffled_list[index] = nums[left_index] 9 | left_index += 1 10 | else: 11 | shuffled_list[index] = nums[right_index] 12 | right_index += 1 13 | return shuffled_list 14 | -------------------------------------------------------------------------------- /LeetCode/1499_Max_Value_of_Equation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaxValueOfEquation(self, points, k): 3 | """ 4 | :type points: List[List[int]] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | ans = None 9 | 10 | d = deque() 11 | for x, y in points: 12 | while len(d) > 0 and d[0][0] < x - k: 13 | d.popleft() 14 | 15 | if len(d) != 0: 16 | ans = max(ans, x + y + d[0][1] - d[0][0]) 17 | 18 | while (len(d) != 0) and d[-1][1] - d[-1][0] < y - x: 19 | d.pop() 20 | 21 | d.append((x, y)) 22 | 23 | return ans 24 | -------------------------------------------------------------------------------- /LeetCode/1512_Number_of_Good_Pairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIdenticalPairs(self, nums: List[int]) -> int: 3 | ans = 0 4 | for i in range(0, len(nums)): 5 | for j in range(0, len(nums)): 6 | if(nums[i] == nums[j] and i < j): 7 | ans += 1 8 | return ans -------------------------------------------------------------------------------- /LeetCode/1518_Water_Bottles.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numWaterBottles(self, numBottles, numExchange): 3 | """ 4 | :type numBottles: int 5 | :type numExchange: int 6 | :rtype: int 7 | """ 8 | full = numBottles 9 | empty = 0 10 | drank = 0 11 | 12 | while True: 13 | # 1. Drink 14 | empty += full 15 | drank += full 16 | full = 0 17 | 18 | # 2. Exchange 19 | while empty >= numExchange: 20 | empty -= numExchange 21 | full += 1 22 | 23 | if not full: 24 | break 25 | 26 | return drank 27 | -------------------------------------------------------------------------------- /LeetCode/1544_Make_string_great.py: -------------------------------------------------------------------------------- 1 | def finder(s): 2 | a =0 3 | for i in range(len(s) -1): 4 | if abs(ord(s[i]) - ord(s[i+1])) == 32 : 5 | del s[i] 6 | del s[i] 7 | a =1 8 | break 9 | if a == 0 : 10 | return s 11 | else: 12 | return finder(s) 13 | 14 | class Solution: 15 | def makeGood(self, s: str) -> str: 16 | s = list(s) 17 | h = finder(s) 18 | return ("".join(h)) -------------------------------------------------------------------------------- /LeetCode/1550_Three_Consecutive_Odds.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeConsecutiveOdds(self, arr: List[int]) -> bool: 3 | return '111' in "".join([str(i%2) for i in arr]) -------------------------------------------------------------------------------- /LeetCode/1556_Thousand_Separator.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def thousandSeparator(self, n: int) -> str: 3 | num = n 4 | ans = f'{num:,}'.replace(',', '.') 5 | return ans 6 | -------------------------------------------------------------------------------- /LeetCode/1559_Detect_Cycles_In_2D_Grid.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.directionX = [-1,0,1,0] 4 | self.directionY = [0,1,0,-1] 5 | def isValid(self, x, y, N, M): 6 | if x < N and x >= 0 and y < M and y >= 0: 7 | return True 8 | return False 9 | 10 | def isCycle(self, x, y, arr, visited, parentX, parentY): 11 | # Mark the current vertex as visited 12 | visited[x][y] = True 13 | N, M = len(arr), len(arr[0]) 14 | 15 | for k in range(4): 16 | newX = x + self.directionX[k] 17 | newY = y + self.directionY[k] 18 | if self.isValid(newX, newY, N, M) and arr[newX][newY] == arr[x][y] and not (parentX == newX and parentY == newY): 19 | if visited[newX][newY]: 20 | return True 21 | else: 22 | 23 | check = self.isCycle(newX, newY, arr, visited, x,y) 24 | if check: 25 | return True 26 | return False 27 | 28 | def containsCycle(self, grid: List[List[str]]) -> bool: 29 | N, M = len(grid), len(grid[0]) 30 | # Initially all the cells are unvisited 31 | visited = [[False] * M for _ in range(N)] 32 | 33 | # Variable to store the result 34 | cycle = False 35 | 36 | # As there is no fixed position of the cycle 37 | # we have to loop through all the elements 38 | for i in range(N): 39 | if cycle == True: 40 | break 41 | 42 | for j in range(M): 43 | ## Taking (-1, -1) as source node's parent 44 | if visited[i][j] == False: 45 | cycle = self.isCycle(i, j, grid, visited, -1, -1) 46 | 47 | if cycle == True: 48 | break 49 | 50 | return cycle 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /LeetCode/1561_Maximum_Number_of_Coins_You_Can_Get.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxCoins(self, piles: List[int]) -> int: 3 | piles.sort() 4 | piles = piles[::-1] 5 | ans = 0 6 | n = len(piles) // 3 7 | for i in range(1, 2 * n, 2): 8 | ans += piles[i] 9 | return ans 10 | -------------------------------------------------------------------------------- /LeetCode/1582_SpecialPositionsInABinaryMatrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSpecial(self, mat): 3 | """ 4 | :type mat: List[List[int]] 5 | :rtype: int 6 | """ 7 | numSpecial = 0 8 | 9 | for a in range(len(mat)): 10 | for b in range(len(mat[a])): 11 | if mat[a][b] == 1: 12 | valid = True 13 | for c in range(len(mat[a])): 14 | if mat[a][c] != 0 and c != b: 15 | valid = False 16 | if valid: 17 | for d in range(len(mat)): 18 | if mat[d][b] != 0 and d != a: 19 | valid = False 20 | if valid: 21 | numSpecial+=1 22 | return numSpecial -------------------------------------------------------------------------------- /LeetCode/1588_SumOfAllOddLengthSubarrays.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumOddLengthSubarrays(self, arr): 3 | 4 | _sum = 0 5 | length = len(arr) 6 | sub_len = 1 7 | start = 0 8 | 9 | while sub_len <= length: 10 | for start in range(length - sub_len + 1): 11 | for i in range(start, start + sub_len): 12 | _sum = _sum + arr[i] 13 | sub_len = sub_len + 2 14 | 15 | return _sum -------------------------------------------------------------------------------- /LeetCode/1589-maximum-sum-obtained-of-any-permutation.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | 4 | class Solution(object): 5 | def maxSumRangeQuery(self, nums, requests): 6 | """ 7 | :type nums: List[int] 8 | :type requests: List[List[int]] 9 | :rtype: int 10 | """ 11 | def addmod(a, b, mod): # avoid overflow in other languages 12 | a %= mod 13 | b %= mod 14 | if mod-a <= b: 15 | b -= mod 16 | return a+b 17 | 18 | def mulmod(a, b, mod): # avoid overflow in other languages 19 | a %= mod 20 | b %= mod 21 | if a < b: 22 | a, b = b, a 23 | result = 0 24 | while b > 0: 25 | if b%2 == 1: 26 | result = addmod(result, a, mod) 27 | a = addmod(a, a, mod) 28 | b //= 2 29 | return result 30 | 31 | MOD = 10**9+7 32 | 33 | count = [0]*len(nums) 34 | for start, end in requests: 35 | count[start] += 1 36 | if end+1 < len(count): 37 | count[end+1] -= 1 38 | for i in range(1, len(count)): 39 | count[i] += count[i-1] 40 | nums.sort() 41 | count.sort() 42 | result = 0 43 | for i, (num, c) in enumerate(zip(nums, count)): 44 | # result = addmod(result, mulmod(num, c, MOD), MOD) 45 | result = (result+num*c)%MOD 46 | return result 47 | -------------------------------------------------------------------------------- /LeetCode/1592_Rearrange_Spaces_Between_Words.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderSpaces(self, text: str) -> str: 3 | words = text.split() 4 | space_cnt = text.count(' ') 5 | 6 | if len(words) == 1: 7 | return words[0] + ' ' * space_cnt 8 | else: 9 | return (' '* (space_cnt // (len(words)-1))).join(words)+ ' ' * (space_cnt % (len(words)-1)) -------------------------------------------------------------------------------- /LeetCode/1598_Crawler_Log_Folder.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, logs: List[str]) -> int: 3 | cnt = 0 4 | for log in logs: 5 | if log == "../": 6 | if cnt != 0: 7 | cnt -= 1 8 | continue 9 | elif log == "./": 10 | continue 11 | else: 12 | cnt += 1 13 | return cnt if cnt > 0 else 0 14 | -------------------------------------------------------------------------------- /LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minOperationsMaxProfit(self, customers, boardingCost, runningCost) : 3 | """ 4 | :type customers: List[int] 5 | :type boardingCose: int 6 | :type runningCose: int 7 | :rtype: int 8 | """ 9 | wait = 0 10 | pro = 0 11 | high = 0 12 | res = -1 13 | for i in range(len(customers)): 14 | vacc = 4 - wait 15 | if vacc <= 0: 16 | wait += customers[i] - 4 17 | pro += 4 * boardingCost - runningCost 18 | # board all 19 | elif customers[i] <= vacc: # board=customers[i]+wait 20 | pro += boardingCost * (customers[i] + wait) - runningCost 21 | wait = 0 22 | else: 23 | pro += boardingCost * 4 - runningCost 24 | wait += customers[i] - 4 25 | if pro > high: 26 | high = pro 27 | res = i 28 | # determine after all arrives 29 | pro_per = boardingCost * 4 - runningCost 30 | if pro_per > 0: 31 | last = wait % 4 32 | if wait >= 4: 33 | if boardingCost * last - runningCost > 0: 34 | return len(customers) + wait // 4 + 1 35 | else: 36 | return len(customers) + wait // 4 37 | if boardingCost * last - runningCost > 0: 38 | return len(customers) + 1 39 | return res + 1 if res >= 0 else -1 40 | -------------------------------------------------------------------------------- /LeetCode/1603_Design_Parking_System.py: -------------------------------------------------------------------------------- 1 | class ParkingSystem: 2 | 3 | def __init__(self, big: int, medium: int, small: int): 4 | self._limits = [big, medium, small] 5 | 6 | 7 | def addCar(self, carType: int) -> bool: 8 | self._limits[carType - 1] -= 1 9 | if self._limits[carType - 1] < 0: 10 | return False 11 | return True 12 | -------------------------------------------------------------------------------- /LeetCode/1604_Alert_Using_Same_Key_Card_Three_or_More_Times_in_a_One_Hour_Period.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def alertNames(self, keyName, keyTime): 3 | """ 4 | :type keyName: List[str] 5 | :type keyTime: List[str] 6 | :rtype: List[str] 7 | """ 8 | mapp = {} 9 | for i in range(len(keyName)): 10 | name = keyName[i] 11 | if(name not in mapp): 12 | mapp[name] = [keyTime[i]] 13 | else: 14 | mapp[name].append(keyTime[i]) 15 | res = [] 16 | for name, arr in mapp.items(): 17 | arr.sort() 18 | for i in range(len(arr)-2): 19 | time= arr[i] 20 | t2 = arr[i+1] 21 | t3 = arr[i+2] 22 | if(time[0:2]=="23"): 23 | endTime = "24:00" 24 | if(t2<=endTime and t3<=endTime and t2>time and t3>time): 25 | res.append(name) 26 | break 27 | else: 28 | start = int(time[0:2]) 29 | endTime = str(start+1)+time[2:] 30 | if(start<9): 31 | endTime = "0"+endTime 32 | if(t2<=endTime and t3<=endTime): 33 | res.append(name) 34 | break 35 | return sorted(res) 36 | -------------------------------------------------------------------------------- /LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: 3 | m = len(rowSum) 4 | n = len(colSum) 5 | matrix = [[0]*n for i in range(m)] 6 | print(matrix) 7 | for i in range(m): 8 | for j in range(n): 9 | matrix[i][j] = min(rowSum[i],colSum[j]) 10 | rowSum[i] -= matrix[i][j] 11 | colSum[j] -= matrix[i][j] 12 | return matrix 13 | -------------------------------------------------------------------------------- /LeetCode/1606_Find_Servers_That_Handled_Most_Number_of_Requests.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def busiestServers(self, k, arrival, load): 3 | """ 4 | :type k: int 5 | :type arrival: List[int] 6 | :type load: List[int] 7 | :rtype: List[int] 8 | """ 9 | from sortedcontainers import SortedList 10 | avail = SortedList() 11 | for i in range(k): 12 | avail.add(i) 13 | h = [] 14 | count = [0]*k 15 | for i in range(len(arrival)): 16 | s = arrival[i] 17 | e = arrival[i]+load[i] 18 | while h and h[0][0]<=s: 19 | _, j = heappop(h) 20 | avail.add(j) 21 | if len(h)==k: 22 | continue 23 | si = avail.bisect_left(i%k) 24 | if si==len(avail): 25 | ser = avail[0] 26 | else: 27 | ser = avail[si] 28 | avail.remove(ser) 29 | count[ser]+=1 30 | heappush(h, (e, ser)) 31 | maxReq = max(count) 32 | ans = [] 33 | for i in range(len(count)): 34 | if count[i]==maxReq: 35 | ans.append(i) 36 | return ans 37 | -------------------------------------------------------------------------------- /LeetCode/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def specialArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | out = -1 9 | for i in range(len(nums)): 10 | if nums[~i]>=i+1: 11 | if i==len(nums)-1 or nums[~(i+1)] int: 3 | b = list(bin(n)[2:]) 4 | temp = len(b) 5 | for i in range(1, temp): 6 | b[i] = str(int(b[i]) ^ int(b[i-1])) 7 | return int(''.join(b), 2) 8 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **IMPORTANT: Please do not create a Pull Request without an issue.** 2 | 3 | ### All Submissions: 4 | 5 | * [ ] I have read the CONTRIBUTING document. 6 | * [ ] My code is written in **Python3** and is ending with _.py_ 7 | * [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? 8 | * [ ] I have checked that my submission does pass the test on LeetCode.com 9 | * [ ] Does your filename follow the naming Conventions? 10 | * [ ] Have you linked your PR to an Issue? 11 | 12 | **Closing issues** 13 | 14 | Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such). 15 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.24.0 2 | bs4==0.0.1 3 | PyGithub==1.53 4 | python-dotenv==0.14.0 5 | 6 | --------------------------------------------------------------------------------