├── LeetCode ├── README.md ├── 15.py ├── 1757.sql ├── 2235.py ├── 1929.py ├── 1108.py ├── 1480.py ├── 771.py ├── 1693.sql ├── 9.py ├── 2367.py ├── 1920.py ├── 1678.py ├── 1470.py ├── 202.py ├── 2149.py ├── 2160.py ├── 58.py ├── 1732.py ├── 88.py ├── 2114.py ├── 1528.py ├── 1342.py ├── 1672.py ├── 1512.py ├── 724.py ├── 1323.py ├── 66.py ├── 1389.py ├── 2011.py ├── 4.py ├── 13.py ├── 349.py ├── 1365.py ├── 2236.py ├── 1281.py ├── 268.py ├── 350.py ├── 412.py ├── 438.py ├── 1572.py ├── 27.py ├── 1221.py ├── 1431.py ├── 121.py ├── 73.py ├── 283.py ├── 2295.py ├── 26.py ├── 169.py ├── 17.py ├── 128.py ├── 2194.py ├── 3.py ├── 57.py ├── 1313.py ├── 205.py ├── 1603.py ├── 290.py ├── 1656.py ├── 53.py ├── 35.py ├── 153.py ├── 30.py ├── 347.py ├── 39.py ├── 41.py ├── 217.py ├── 154.py ├── 34.js ├── 31.py ├── 238.py ├── 125.py ├── 33.py ├── 1.py ├── 166.py ├── 1347.py ├── 242.py ├── 36.py ├── 49.py ├── 34.py ├── 81.py ├── cprob1.py └── cprob2.py ├── README.md └── HackerRank ├── README.md ├── output.txt ├── input.txt └── ChocolateFeast.py /LeetCode/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Problem Solving -------------------------------------------------------------------------------- /HackerRank/README.md: -------------------------------------------------------------------------------- 1 | # HackerRank -------------------------------------------------------------------------------- /HackerRank/output.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 3 | 5 4 | -------------------------------------------------------------------------------- /HackerRank/input.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 10 2 5 3 | 12 4 4 4 | 6 2 2 -------------------------------------------------------------------------------- /LeetCode/15.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # Medium 3 | # 15 4 | # 3Sum 5 | # https://leetcode.com/problems/3sum/ -------------------------------------------------------------------------------- /LeetCode/1757.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 2 | -- 1757 3 | -- Recyclable and Low Fat Products 4 | 5 | SELECT product_id FROM Products WHERE low_fats = 'Y' and recyclable = 'Y'; -------------------------------------------------------------------------------- /LeetCode/2235.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2235 3 | # Add Two Integers 4 | 5 | class Solution: 6 | def sum(self, num1: int, num2: int) -> int: 7 | return num1 + num2 8 | -------------------------------------------------------------------------------- /LeetCode/1929.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1929 3 | # Concatenation of Array 4 | 5 | class Solution: 6 | def getConcatenation(self, nums: List[int]) -> List[int]: 7 | return nums + nums -------------------------------------------------------------------------------- /LeetCode/1108.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1108 3 | # Defanging an IP Address 4 | 5 | class Solution: 6 | def defangIPaddr(self, address: str) -> str: 7 | return address.replace('.', '[.]') 8 | -------------------------------------------------------------------------------- /LeetCode/1480.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1480 3 | # Running Sum of 1d Array 4 | 5 | class Solution: 6 | def runningSum(self, nums): 7 | for i in range(1, len(nums)): 8 | nums[i] += nums[i-1] 9 | 10 | return nums -------------------------------------------------------------------------------- /LeetCode/771.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 771 3 | # Jewels and Stones 4 | 5 | class Solution: 6 | def numJewelsInStones(self, jewels: str, stones: str) -> int: 7 | jewels_set = set(jewels) 8 | return sum(s in jewels_set for s in stones) -------------------------------------------------------------------------------- /LeetCode/1693.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 2 | -- 1693 3 | -- Daily Leads and Partners 4 | 5 | SELECT date_id, make_name, COUNT(DISTINCT lead_id) AS 'unique_leads', COUNT(DISTINCT partner_id) AS 'unique_partners' 6 | FROM DailySales 7 | GROUP BY date_id, make_name; -------------------------------------------------------------------------------- /LeetCode/9.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 9 3 | # Palindrome Number 4 | 5 | class Solution: 6 | def isPalindrome(self, x: int) -> bool: 7 | if str(x) == str(x)[::-1]: 8 | return True 9 | 10 | return False 11 | -------------------------------------------------------------------------------- /LeetCode/2367.py: -------------------------------------------------------------------------------- 1 | # 2367 2 | # Number of Arithmetic Triplets 3 | # Easy 4 | # https://leetcode.com/problems/number-of-arithmetic-triplets/ 5 | 6 | def arithmeticTriplets(nums, diff): 7 | counts = set() 8 | return counts 9 | 10 | print(arithmeticTriplets(nums = [0,1,4,6,7,10], diff = 3)) -------------------------------------------------------------------------------- /LeetCode/1920.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1920 3 | # Build Array from Permutation 4 | 5 | class Solution: 6 | def buildArray(self, nums: List[int]) -> List[int]: 7 | ans = [] 8 | 9 | for i in range(len(nums)): 10 | ans.append(nums[nums[i]]) 11 | 12 | return ans 13 | -------------------------------------------------------------------------------- /LeetCode/1678.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1678 3 | # Goal Parser Interpretation 4 | # https://leetcode.com/problems/goal-parser-interpretation/ 5 | 6 | class Solution: 7 | def interpret(self, command: str) -> str: 8 | command = command.replace("()", "o") 9 | command = command.replace("(al)", "al") 10 | 11 | return command -------------------------------------------------------------------------------- /LeetCode/1470.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1470 3 | # Shuffle the Array 4 | 5 | class Solution: 6 | def shuffle(self, nums: List[int], n: int) -> List[int]: 7 | result = [] 8 | 9 | for i in range(0, n): 10 | result.append(nums[i]) 11 | result.append(nums[i+n]) 12 | 13 | return result 14 | -------------------------------------------------------------------------------- /LeetCode/202.py: -------------------------------------------------------------------------------- 1 | # 202 2 | # Happy Number 3 | # https://leetcode.com/problems/happy-number/ 4 | 5 | def is_happy(n): 6 | seen = set() 7 | 8 | while n not in seen: 9 | seen.add(n) 10 | n = sum(int(c)**2 for c in str(n)) 11 | 12 | return n == 1 13 | 14 | 15 | print(is_happy(n=19)) 16 | print(is_happy(n=1)) 17 | print(is_happy(n=9)) -------------------------------------------------------------------------------- /LeetCode/2149.py: -------------------------------------------------------------------------------- 1 | # 2149 2 | # Rearrange Array Elements by Sign 3 | # Medium 4 | # https://leetcode.com/problems/rearrange-array-elements-by-sign/ 5 | 6 | from typing import List 7 | 8 | 9 | class Solution: 10 | def rearrangeArray(self, nums: List[int]) -> List[int]: 11 | left = 0 12 | right = len(nums) - 1 13 | 14 | return nums -------------------------------------------------------------------------------- /LeetCode/2160.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2160 3 | # Minimum Sum of Four Digit Number After Splitting Digits 4 | 5 | class Solution: 6 | def minimumSum(self, num: int) -> int: 7 | arr = [int(val) for val in str(num)] 8 | arr.sort() 9 | a, b, c, d = arr 10 | return (a + b) * 10 + c + d 11 | 12 | print(Solution.minimumSum(Solution, 2932)) -------------------------------------------------------------------------------- /LeetCode/58.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 58. Length of Last Word 3 | # Easy 4 | # https://leetcode.com/problems/length-of-last-word/ 5 | 6 | def length_of_word(s): 7 | s = s.split(' ') 8 | new_list = [x for x in s if x != ''] 9 | 10 | return len(new_list[-1]) 11 | 12 | print(length_of_word("Hello World")) 13 | print(length_of_word(" fly me to the moon ")) -------------------------------------------------------------------------------- /LeetCode/1732.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1732 3 | # Find the Highest Altitude 4 | # https://leetcode.com/problems/find-the-highest-altitude/ 5 | 6 | class Solution: 7 | def largestAltitude(self, gain: List[int]) -> int: 8 | altitude = [0] 9 | 10 | for i in range(len(gain)): 11 | altitude.append(altitude[i] + gain[i]) 12 | 13 | return max(altitude) 14 | -------------------------------------------------------------------------------- /LeetCode/88.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 88 3 | # Merge Sorted Array 4 | # Easy 5 | # https://leetcode.com/problems/merge-sorted-array/ 6 | 7 | def merge(nums1, m, nums2, n): 8 | # temp = 9 | for i in range(m, len(nums1)): 10 | # print(i) 11 | nums1[i] = nums2[i-m] 12 | 13 | nums1.sort() 14 | 15 | return nums1 16 | 17 | print(merge(nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3)) -------------------------------------------------------------------------------- /LeetCode/2114.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2114 3 | # Maximum Number of Words Found in Sentences 4 | 5 | class Solution: 6 | def mostWordsFound(self, sentences: List[str]) -> int: 7 | max_count = 0 8 | 9 | for sentence in sentences: 10 | if len(sentence.split(' ')) > max_count: 11 | max_count = len(sentence.split(' ')) 12 | 13 | return max_count 14 | -------------------------------------------------------------------------------- /LeetCode/1528.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1528 3 | # Shuffle String 4 | # https://leetcode.com/problems/shuffle-string/ 5 | 6 | def restore_string(s, indices): 7 | temp_result = [None] * len(s) 8 | 9 | for i in range(len(s)): 10 | temp_result[indices[i]] = s[i] 11 | 12 | return ''.join(i for i in temp_result) 13 | 14 | print(restore_string('codeleet', [4,5,6,7,0,2,1,3])) 15 | print(restore_string('abc', [0,1,2])) -------------------------------------------------------------------------------- /LeetCode/1342.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1342 3 | # Number of Steps to Reduce a Number to Zero 4 | 5 | class Solution: 6 | def numberOfSteps(self, num: int) -> int: 7 | step = 0 8 | 9 | while num != 0: 10 | if num % 2 == 0: 11 | num = num // 2 12 | else: 13 | num = num - 1 14 | 15 | step += 1 16 | 17 | return step -------------------------------------------------------------------------------- /LeetCode/1672.py: -------------------------------------------------------------------------------- 1 | # 1672 2 | # Richest Customer Wealth 3 | # Easy 4 | # https://leetcode.com/problems/richest-customer-wealth/ 5 | 6 | def maximum_wealth(accounts): 7 | max_wealth = 0 8 | 9 | for account in accounts: 10 | if sum(account) > max_wealth: 11 | max_wealth = sum(account) 12 | return max_wealth 13 | 14 | print(maximum_wealth([[1,2,3],[3,2,1]])) 15 | print(maximum_wealth([[1,5],[7,3],[3,5]])) -------------------------------------------------------------------------------- /LeetCode/1512.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1512 3 | # Number of Good Pairs 4 | 5 | class Solution: 6 | def numIdenticalPairs(self, nums: List[int]) -> int: 7 | good_pairs = 0 8 | 9 | for i in range(0, (len(nums) - 1)): 10 | for j in range(i + 1, len(nums)): 11 | if i < j and nums[i] == nums[j]: 12 | good_pairs += 1 13 | 14 | return good_pairs 15 | -------------------------------------------------------------------------------- /LeetCode/724.py: -------------------------------------------------------------------------------- 1 | # 724 2 | # Find Pivot Index 3 | 4 | def pivotIndex(nums): 5 | pivot_index = -1 6 | 7 | for i in range(len(nums)): 8 | print(nums[i:], nums[:i]) 9 | if sum(nums[i+1:]) == sum(nums[:i]): 10 | print(nums[i:], nums[:i]) 11 | pivot_index = i 12 | 13 | return pivot_index 14 | 15 | print(pivotIndex([1,7,3,6,5,6])) 16 | # [-1,-1,0,0,-1,-1] -------------------------------------------------------------------------------- /LeetCode/1323.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1323 3 | # Maximum 69 Number 4 | # https://leetcode.com/problems/maximum-69-number/ 5 | 6 | class Solution: 7 | def maximum69Number (self, num: int) -> int: 8 | num = str(num) 9 | 10 | for i in range(len(num)): 11 | if num[i] == '6': 12 | num = num[:i] + '9' + num[i + 1:] 13 | break 14 | 15 | return int(num) 16 | -------------------------------------------------------------------------------- /LeetCode/66.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 66. Plus One 3 | # Easy 4 | # https://leetcode.com/problems/plus-one/ 5 | # Array, Math 6 | 7 | def plus_one(digits): 8 | # Simple solution 9 | # num = int(''.join(map(str, digits))) + 1 10 | # digits = [int(digit) for digit in str(num)] 11 | # return digits 12 | # Complex solution 13 | return [int(digit) for digit in str(int(''.join(map(str, digits)))+1)] 14 | 15 | 16 | print(plus_one([1,2,3])) -------------------------------------------------------------------------------- /LeetCode/1389.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1389 3 | # Create Target Array in the Given Order 4 | # https://leetcode.com/problems/create-target-array-in-the-given-order/submissions/ 5 | 6 | class Solution: 7 | def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: 8 | target = [] 9 | 10 | for i in range(len(index)): 11 | target.insert(index[i], nums[i]) 12 | 13 | return target 14 | -------------------------------------------------------------------------------- /LeetCode/2011.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2011 3 | # Final Value of Variable After Performing Operations 4 | 5 | class Solution: 6 | def finalValueAfterOperations(self, operations: List[str]) -> int: 7 | x = 0 8 | 9 | for opt in operations: 10 | if opt == '++X' or opt == 'X++': 11 | x += 1 12 | elif opt == '--X' or opt == 'X--': 13 | x -= 1 14 | 15 | return x 16 | -------------------------------------------------------------------------------- /LeetCode/4.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # Problem 4: Median of Two Sorted Arrays 3 | # https://leetcode.com/problems/median-of-two-sorted-arrays/ 4 | 5 | def find_median(nums1, nums2): 6 | nums = nums1 + nums2 7 | nums.sort() 8 | 9 | if len(nums) % 2 == 0: 10 | return (nums[len(nums) // 2] + nums[len(nums) // 2 - 1]) / 2 11 | else: 12 | return nums[len(nums) // 2] 13 | 14 | result = find_median([1, 2], [3, 4]) 15 | 16 | print(result) -------------------------------------------------------------------------------- /LeetCode/13.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 13 3 | # Roman to Integer 4 | 5 | def romanToInt(s: str) -> int: 6 | ROMAN_VALUE = {"I": 1, "II": 2, "III": 3, "IV": 4, "V": 5, "VI": 6, "VII": 7, "VIII": 8, "IX": 9, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000,} 7 | ROMAN_MAP = {"I": 1, "V": 5, "X": 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 8 | 9 | n = len(s) 10 | num = ROMAN_MAP[s[n - 1]] 11 | return num 12 | return n 13 | 14 | 15 | print(romanToInt("MCMXCIV")) 16 | -------------------------------------------------------------------------------- /LeetCode/349.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 349 3 | # Intersection of Two Arrays 4 | # Easy 5 | # https://leetcode.com/problems/intersection-of-two-arrays/ 6 | 7 | def insertion(nums1, nums2): 8 | result = [] 9 | nums1 = set(nums1) 10 | nums2 = set(nums2) 11 | 12 | for n in nums1: 13 | if n in nums2: 14 | result.append(n) 15 | 16 | return result 17 | 18 | print(insertion(nums1 = [1,2,2,1], nums2 = [2,2])) 19 | print(insertion(nums1 = [4,9,5], nums2 = [9,4,9,8,4])) -------------------------------------------------------------------------------- /LeetCode/1365.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1365 3 | # How Many Numbers Are Smaller Than the Current Number 4 | 5 | class Solution: 6 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: 7 | result = [] 8 | 9 | for i in range(0, len(nums)): 10 | c = 0 11 | for j in range(0, len(nums)): 12 | if i != j and nums[i] > nums[j]: 13 | c += 1 14 | 15 | result.append(c) 16 | 17 | return result -------------------------------------------------------------------------------- /LeetCode/2236.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2236 3 | # Root Equals Sum of Children 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode: 7 | # def __init__(self, val=0, left=None, right=None): 8 | # self.val = val 9 | # self.left = left 10 | # self.right = right 11 | class Solution: 12 | def checkTree(self, root: Optional[TreeNode]) -> bool: 13 | if root.val == (root.left.val + root.right.val): 14 | return True 15 | 16 | return False 17 | -------------------------------------------------------------------------------- /LeetCode/1281.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1281 3 | # Subtract the Product and Sum of Digits of an Integer 4 | # https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ 5 | 6 | class Solution: 7 | def subtractProductAndSum(self, n: int) -> int: 8 | products = 1 9 | summation = 0 10 | 11 | str_n = str(n) 12 | 13 | for i in str_n: 14 | products *= int(i) 15 | summation += int(i) 16 | 17 | return products - summation 18 | -------------------------------------------------------------------------------- /LeetCode/268.py: -------------------------------------------------------------------------------- 1 | # 268 2 | # Missing Number 3 | # https://leetcode.com/problems/missing-number/ 4 | 5 | def missing_number(nums): 6 | nums_list_in_range = [n for n in range(0, len(nums)+1)] 7 | 8 | return list(set(nums_list_in_range) - set(nums))[0] 9 | 10 | # # single line solution 11 | # def missing_number(nums): 12 | # return list(set(n for n in range(0, len(nums)+1)) - set(nums))[0] 13 | 14 | 15 | print(missing_number(nums=[3, 0, 1])) 16 | print(missing_number(nums=[0, 1])) 17 | print(missing_number(nums=[9,6,4,2,3,5,7,0,1])) -------------------------------------------------------------------------------- /LeetCode/350.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 350 3 | # Intersection of Two Arrays II 4 | # Easy 5 | # https://leetcode.com/problems/intersection-of-two-arrays-ii/ 6 | 7 | from typing import Counter 8 | 9 | 10 | def insertion(nums1, nums2): 11 | result = [] 12 | c = Counter(nums1) 13 | 14 | for n in nums2: 15 | if c[n] > 0: 16 | result.append(n) 17 | c[n] -= 1 18 | 19 | return result 20 | 21 | print(insertion(nums1 = [1,2,2,1], nums2 = [2,2])) 22 | print(insertion(nums1 = [4,9,5], nums2 = [9,4,9,8,4])) -------------------------------------------------------------------------------- /LeetCode/412.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 412 3 | # Fizz Buzz 4 | 5 | class Solution: 6 | def fizzBuzz(self, n: int) -> List[str]: 7 | answer = [] 8 | 9 | for i in range(1, n+1): 10 | if i % 3 == 0 and i % 5 == 0: 11 | answer.append("FizzBuzz") 12 | elif i % 3 == 0: 13 | answer.append("Fizz") 14 | elif i % 5 == 0: 15 | answer.append("Buzz") 16 | else: 17 | answer.append(str(i)) 18 | 19 | return answer 20 | -------------------------------------------------------------------------------- /LeetCode/438.py: -------------------------------------------------------------------------------- 1 | # 438 2 | # Find All Anagrams in a String 3 | # https://leetcode.com/problems/find-all-anagrams-in-a-string/ 4 | 5 | def find_anagrams(s, p): 6 | indexs = [] 7 | length_of_p = len(p) 8 | length_of_s = len(s) 9 | sorted_p = ''.join(sorted(p)) 10 | 11 | for x in range(length_of_s - length_of_p + 1): 12 | if sorted_p == ''.join(sorted(s[x:x+length_of_p])): 13 | indexs.append(x) 14 | 15 | return indexs 16 | 17 | 18 | print(find_anagrams(s = "cbaebabacd", p = "abc")) 19 | print(find_anagrams(s = "abab", p = "ab")) -------------------------------------------------------------------------------- /LeetCode/1572.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1572 3 | # Matrix Diagonal Sum 4 | # https://leetcode.com/problems/matrix-diagonal-sum/submissions/ 5 | 6 | class Solution: 7 | def diagonalSum(self, mat: List[List[int]]) -> int: 8 | start = 0 9 | end = len(mat) - 1 10 | result = 0 11 | 12 | for m in mat: 13 | if start == end: 14 | result += m[start] 15 | else: 16 | result += m[start] + m[end] 17 | 18 | start += 1 19 | end -= 1 20 | 21 | return result 22 | -------------------------------------------------------------------------------- /LeetCode/27.py: -------------------------------------------------------------------------------- 1 | # 27 2 | # Remove Element 3 | # Easy 4 | # https://leetcode.com/problems/remove-element/ 5 | # Array, Two Pointers 6 | 7 | from typing import List 8 | 9 | 10 | 11 | class Solution: 12 | def removeElement(self, nums: List[int], val: int) -> int: 13 | k = 0 14 | 15 | for i in range(len(nums)): 16 | if nums[i] != val: 17 | nums[k] = nums[i] 18 | k += 1 19 | 20 | return k 21 | 22 | 23 | print(Solution().removeElement(nums = [0,1,2,2,3,0,4,2], val = 2)) 24 | print(Solution().removeElement(nums = [3,2,2,3], val = 3)) -------------------------------------------------------------------------------- /LeetCode/1221.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1221 3 | # Split a String in Balanced Strings 4 | # https://leetcode.com/problems/split-a-string-in-balanced-strings/ 5 | 6 | 7 | class Solution: 8 | def balancedStringSplit(s: str): 9 | count = 0 10 | balance = 0 11 | 12 | for c in s: 13 | if c == 'L': 14 | balance += 1 15 | else: 16 | balance -= 1 17 | 18 | 19 | if balance == 0: 20 | count += 1 21 | 22 | return count 23 | 24 | 25 | string = "RLRRLLRLRL" 26 | print(Solution.balancedStringSplit(s=string)) -------------------------------------------------------------------------------- /LeetCode/1431.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1431 3 | # Kids With the Greatest Number of Candies 4 | 5 | class Solution: 6 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: 7 | result = [] 8 | max_candies = max(candies) 9 | 10 | for n in candies: 11 | if n + extraCandies >= max_candies: 12 | result.append(True) 13 | else: 14 | result.append(False) 15 | 16 | return result 17 | 18 | # return [True if n + extra_candies >= max_candies else False for n in candies] 19 | # another solution which takes more time. -------------------------------------------------------------------------------- /LeetCode/121.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 121 3 | # Best Time to Buy and Sell Stock 4 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 5 | 6 | class Solution: 7 | def maxProfit(self, prices: List[int]) -> int: 8 | profit = 0 9 | min_price = prices[0] 10 | 11 | for i in range(1, len(prices)): 12 | sell_price = prices[i] 13 | 14 | if sell_price - min_price > profit: 15 | profit = sell_price - min_price 16 | 17 | if sell_price < min_price: 18 | min_price = sell_price 19 | 20 | return profit 21 | -------------------------------------------------------------------------------- /LeetCode/73.py: -------------------------------------------------------------------------------- 1 | # 73 2 | # Set Matrix Zeroes 3 | # https://leetcode.com/problems/set-matrix-zeroes/ 4 | 5 | def set_zeros(matrix): 6 | m, n = len(matrix), len(matrix[0]) 7 | rows, cols = set(), set() 8 | 9 | for x in range(m): 10 | for y in range(n): 11 | if matrix[x][y] == 0: 12 | rows.add(x) 13 | cols.add(y) 14 | 15 | for x in range(m): 16 | for y in range(n): 17 | if x in rows or y in cols: 18 | matrix[x][y] = 0 19 | 20 | return matrix 21 | 22 | 23 | print(set_zeros(matrix = [[1,1,1],[1,0,1],[1,1,1]])) 24 | print(set_zeros(matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]])) -------------------------------------------------------------------------------- /LeetCode/283.py: -------------------------------------------------------------------------------- 1 | # 283 2 | # Move Zeroes 3 | # https://leetcode.com/problems/move-zeroes 4 | # Easy 5 | # Array, Two Pointer 6 | 7 | 8 | 9 | from typing import List 10 | 11 | 12 | 13 | class Solution: 14 | def moveZeroes(self, nums: List[int]) -> None: 15 | """ 16 | Do not return anything, modify nums in-place instead. 17 | """ 18 | for i in range(len(nums)-1): 19 | print(nums[i]) 20 | # if nums[i] == 0: 21 | # print('ZERO') 22 | # nums[i], nums[i+1] = nums[i+1], nums[i] 23 | 24 | # print(nums) 25 | 26 | return nums 27 | 28 | 29 | 30 | print(Solution().moveZeroes(nums = [0,1,0,3,12])) -------------------------------------------------------------------------------- /LeetCode/2295.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2295 3 | # Replace Elements in an Array 4 | # https://leetcode.com/problems/replace-elements-in-an-array/ 5 | 6 | def array_change(nums, operations): 7 | for operation in operations: 8 | value_to_find = operation[0] 9 | value_to_replace = operation[1] 10 | # nums[index] += value 11 | nums[nums.index(value_to_find)] = value_to_replace 12 | # print(nums) 13 | # print(nums.index(value_to_find)) 14 | 15 | return nums 16 | 17 | # print(array_change([1, 2, 3], [[2, 3], [1, 5]])) 18 | # print(array_change([1,2,4,6], [[1,3],[4,7],[6,1]])) 19 | # print(array_change([1,2], [[1,3],[2,1],[3,2]])) 20 | 21 | print(array_change()) -------------------------------------------------------------------------------- /LeetCode/26.py: -------------------------------------------------------------------------------- 1 | # 26 2 | # Remove Duplicates from Sorted Array 3 | # Easy 4 | # https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 5 | # Array, Two Pointer 6 | 7 | 8 | from typing import List 9 | 10 | 11 | # Solution: Two Pointer 12 | class Solution: 13 | def removeDuplicates(self, nums: List[int]) -> int: 14 | left = 1 15 | 16 | for right in range(1, len(nums)): 17 | if nums[right] != nums[right - 1]: 18 | nums[left] = nums[right] 19 | left += 1 20 | 21 | return left, nums 22 | 23 | 24 | 25 | 26 | print(Solution().removeDuplicates(nums = [1,1,2])) 27 | print(Solution().removeDuplicates(nums = [0,0,1,1,1,2,2,3,3,4])) -------------------------------------------------------------------------------- /LeetCode/169.py: -------------------------------------------------------------------------------- 1 | # 169 2 | # Majority Element 3 | # https://leetcode.com/problems/majority-element/description/ 4 | # Easy 5 | 6 | def majorityElement(nums): 7 | if not nums: 8 | return None 9 | 10 | if len(nums) == 1: 11 | return nums[0] 12 | 13 | counts = {} 14 | 15 | for n in nums: 16 | if n in counts: 17 | counts[n] += 1 18 | else: 19 | counts[n] = 1 20 | 21 | max_count = 0 22 | majority_element = None 23 | 24 | for n, c in counts.items(): 25 | if c > max_count: 26 | max_count = c 27 | majority_element = n 28 | 29 | return majority_element 30 | 31 | 32 | print(majorityElement(nums=[3,2,3])) 33 | print(majorityElement(nums=[2,2,1,1,1,2,2])) -------------------------------------------------------------------------------- /LeetCode/17.py: -------------------------------------------------------------------------------- 1 | # 17 2 | # Letter Combinations of a Phone Number 3 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 4 | # Medium 5 | 6 | def letterCombinations(digits: str): 7 | if not digits: 8 | return [] 9 | 10 | letters = { 11 | '2': 'abc', 12 | '3': 'def', 13 | '4': 'ghi', 14 | '5': 'jkl', 15 | '6': 'mno', 16 | '7': 'pqrs', 17 | '8': 'tuv', 18 | '9': 'wxyz', 19 | } 20 | 21 | combinations = [c for c in letters[digits[0]]] 22 | 23 | for d in digits[1:]: 24 | combinations = [comb + c for comb in combinations for c in letters[d]] 25 | 26 | return combinations 27 | 28 | 29 | print(letterCombinations(digits='')) 30 | print(letterCombinations(digits='23')) -------------------------------------------------------------------------------- /LeetCode/128.py: -------------------------------------------------------------------------------- 1 | # 128 2 | # Longest Consecutive Sequence 3 | # https://leetcode.com/problems/longest-consecutive-sequence/ 4 | # Medium 5 | # Array, Hash Table, Union Find 6 | 7 | from typing import List 8 | 9 | 10 | 11 | class Solution: 12 | def longestConsecutive(self, nums: List[int]) -> int: 13 | numSet = set(nums) 14 | longest = 0 15 | 16 | for n in nums: 17 | if (n-1) not in numSet: 18 | length = 0 19 | 20 | while (n+length) in numSet: 21 | length += 1 22 | 23 | longest = max(length, longest) 24 | 25 | return longest 26 | 27 | 28 | 29 | print(Solution().longestConsecutive(nums = [100,4,200,1,3,2])) 30 | print(Solution().longestConsecutive(nums = [0,3,7,2,5,8,4,6,0,1])) -------------------------------------------------------------------------------- /LeetCode/2194.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 2194 3 | # Cells in a Range on an Excel Sheet 4 | 5 | def cell_in_range(s): 6 | ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 7 | 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 8 | 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 9 | 10 | result = [] 11 | 12 | cell_start = s.split(":")[0] 13 | cell_end = s.split(":")[1] 14 | 15 | col_start = ALPHABET.index(cell_start[0]) 16 | col_end = ALPHABET.index(cell_end[0]) 17 | 18 | row_start = int(cell_start[1:]) 19 | row_end = int(cell_end[1:]) 20 | 21 | for x in range(col_start, col_end+1): 22 | for y in range(row_start, row_end+1): 23 | result.append(ALPHABET[x] + str(y)) 24 | 25 | return result 26 | 27 | print(cell_in_range("K1:L2")) 28 | print(cell_in_range("A1:F1")) -------------------------------------------------------------------------------- /LeetCode/3.py: -------------------------------------------------------------------------------- 1 | # 3 2 | # Longest Substring Without Repeating Characters 3 | # https://leetcode.com/problems/longest-substring-without-repeating-characters/ 4 | # Medium 5 | 6 | def lengthOfLongestSubstring(s): 7 | sub_str = "" 8 | max_length = -1 9 | 10 | if len(s) == 0: 11 | return 0 12 | elif len(s) == 1: 13 | return 1 14 | 15 | for c in list(s): 16 | current = "".join(c) 17 | 18 | if current in sub_str: 19 | sub_str = sub_str[sub_str.index(current) + 1:] 20 | 21 | sub_str = sub_str + "".join(c) 22 | 23 | max_length = max(len(sub_str), max_length) 24 | 25 | return max_length 26 | 27 | 28 | print(lengthOfLongestSubstring(s = "abcabcbb")) 29 | print(lengthOfLongestSubstring(s = "bbbbb")) 30 | print(lengthOfLongestSubstring(s = "pwwkew")) 31 | 32 | 33 | -------------------------------------------------------------------------------- /LeetCode/57.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 57. Insert Interval 3 | # Medium 4 | # https://leetcode.com/problems/insert-interval/ 5 | # Array 6 | 7 | def insert(intervals, newInterval): 8 | indexs = set() 9 | 10 | for x, interval in enumerate(intervals): 11 | print(x, interval, newInterval) 12 | if interval[1] >= newInterval[0]: 13 | print('Here', interval) 14 | indexs.add(x) 15 | 16 | for x, interval in enumerate(intervals): 17 | print(x, interval, newInterval) 18 | if interval[0] <= newInterval[1]: 19 | print('There', interval) 20 | indexs.add(x) 21 | 22 | print(indexs) 23 | 24 | return None 25 | 26 | 27 | print(insert(intervals = [[1,3],[6,9]], newInterval = [2,5])) 28 | print(insert(intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8])) 29 | -------------------------------------------------------------------------------- /LeetCode/1313.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1313 3 | # Decompress Run-Length Encoded List 4 | # https://leetcode.com/problems/decompress-run-length-encoded-list/ 5 | 6 | # Solution 1 7 | # Runtime: 122ms 8 | # Memory Usage: 14.4MB 9 | 10 | class Solution: 11 | def decompressRLElist(self, nums: List[int]) -> List[int]: 12 | result = [] 13 | 14 | for i in range(0, len(nums), 2): 15 | for j in range(nums[i]): 16 | result.append(nums[i+1]) 17 | 18 | return result 19 | 20 | # Solution 2 21 | # Runtime: 76ms 22 | # Memory Usage: 14.3MB 23 | class Solution: 24 | def decompressRLElist(self, nums: List[int]) -> List[int]: 25 | result = [] 26 | 27 | for i in range(0, len(nums), 2): 28 | result += [nums[i+1] for j in range(nums[i])] 29 | 30 | return result -------------------------------------------------------------------------------- /LeetCode/205.py: -------------------------------------------------------------------------------- 1 | # 205 2 | # Isomorphic Strings 3 | # https://leetcode.com/problems/isomorphic-strings/ 4 | 5 | def is_isomorphic(s1, s2): 6 | if len(s1) != len(s2): 7 | return False 8 | 9 | s1_map = {} 10 | s2_map = {} 11 | 12 | for c1, c2 in zip(s1, s2): 13 | # print('c1, c2: ', c1, c2) 14 | if c1 in s1_map: 15 | # print(s1_map[c1], c2) 16 | if s1_map[c1] != c2: 17 | return False 18 | else: 19 | s1_map[c1] = c2 20 | 21 | if c2 in s2_map: 22 | # print(s2_map[c2], c1) 23 | if s2_map[c2] != c1: 24 | return False 25 | else: 26 | s2_map[c2] = c1 27 | 28 | return True 29 | 30 | print(is_isomorphic(s1='egg', s2='add')) 31 | print(is_isomorphic(s1='foo', s2='bar')) 32 | print(is_isomorphic(s1='title', s2='paper')) -------------------------------------------------------------------------------- /LeetCode/1603.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1603 3 | # Design Parking System 4 | 5 | class ParkingSystem: 6 | 7 | def __init__(self, big: int, medium: int, small: int): 8 | self.big = big 9 | self.medium = medium 10 | self.small = small 11 | 12 | 13 | def addCar(self, carType: int) -> bool: 14 | if carType == 1 and self.big != 0: 15 | self.big -= 1 16 | return True 17 | 18 | if carType == 2 and self.medium != 0: 19 | self.medium -= 1 20 | return True 21 | 22 | if carType == 3 and self.small != 0: 23 | self.small -= 1 24 | return True 25 | 26 | return False 27 | 28 | 29 | 30 | # Your ParkingSystem object will be instantiated and called as such: 31 | # obj = ParkingSystem(big, medium, small) 32 | # param_1 = obj.addCar(carType) -------------------------------------------------------------------------------- /LeetCode/290.py: -------------------------------------------------------------------------------- 1 | # 290 2 | # Word Pattern 3 | # https://leetcode.com/problems/word-pattern/ 4 | 5 | def word_pattern(pattern, s): 6 | s = s.split(' ') 7 | 8 | if len(s) != len(pattern): 9 | return False 10 | 11 | words = {} 12 | seen_words = set() 13 | 14 | for index, c in enumerate(pattern): 15 | if c in words: 16 | if words[c] != s[index]: 17 | return False 18 | else: 19 | if s[index] in seen_words: 20 | return False 21 | 22 | words[c] = s[index] 23 | seen_words.add(s[index]) 24 | 25 | return True 26 | 27 | 28 | print(word_pattern(pattern = "abba", s = "dog cat cat dog")) 29 | print(word_pattern(pattern = "abba", s = "dog cat cat fish")) 30 | print(word_pattern(pattern = "aaaa", s = "dog cat cat dog")) 31 | print(word_pattern(pattern = "abba", s = "dog dog dog dog")) -------------------------------------------------------------------------------- /LeetCode/1656.py: -------------------------------------------------------------------------------- 1 | # 1656 2 | # Design an Ordered Stream 3 | # Easy 4 | # https://leetcode.com/problems/design-an-ordered-stream/ 5 | # Array, Hash Table, Design, Data Stream 6 | 7 | class OrderedStream: 8 | 9 | def __init__(self, n: int): 10 | self.list = [None] * n 11 | self.pointer = 0 12 | 13 | 14 | # def insert(self, idKey: int, value: str) -> List[str]: 15 | # pass 16 | def insert(self, idKey: int, value: str) -> list[str]: 17 | self.list[idKey-1] = value 18 | 19 | result = [] 20 | 21 | while self.pointer < len(self.list) and self.list[self.pointer] is not None: 22 | result.append(self.list[self.pointer]) 23 | self.pointer += 1 24 | 25 | return result 26 | 27 | 28 | 29 | # Your OrderedStream object will be instantiated and called as such: 30 | # obj = OrderedStream(n) 31 | # param_1 = obj.insert(idKey,value) -------------------------------------------------------------------------------- /LeetCode/53.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 53. Maximum Subarray 3 | # Easy 4 | # https://leetcode.com/problems/maximum-subarray/ 5 | 6 | # def max_sub_array(nums): 7 | # max_sum = nums[0] 8 | # current_sum = nums[0] 9 | # for i in range(1, len(nums)): 10 | # current_sum = max(nums[i], current_sum + nums[i]) 11 | # max_sum = max(max_sum, current_sum) 12 | # return max_sum 13 | 14 | # def max_sub_array(nums): 15 | # max_sum = 0 16 | # return max_sum 17 | 18 | def max_sub_array(nums): 19 | max_sub = nums[0] 20 | current_sum = 0 21 | 22 | for n in nums: 23 | if current_sum < 0: 24 | current_sum = 0 25 | 26 | current_sum += n 27 | 28 | max_sub = max(max_sub, current_sum) 29 | 30 | return max_sub 31 | 32 | print(max_sub_array([-2,1,-3,4,-1,2,1,-5,4])) 33 | print(max_sub_array([1])) 34 | print(max_sub_array([5,4,-1,7,8])) 35 | print(max_sub_array([-2,2,5,-11,6])) -------------------------------------------------------------------------------- /LeetCode/35.py: -------------------------------------------------------------------------------- 1 | # 35. Search Insert Position 2 | # Easy 3 | # Array, Binary Search 4 | # https://leetcode.com/problems/search-insert-position/ 5 | 6 | from typing import List 7 | 8 | import bisect 9 | 10 | class Solution: 11 | def searchInsert(self, nums: List[int], target: int) -> int: 12 | # single line solution 13 | # return bisect.bisect_left(nums, target) 14 | left, right = 0, len(nums) - 1 15 | 16 | while left <= right: 17 | mid = (left + right) // 2 18 | 19 | if nums[mid] == target: 20 | return mid 21 | elif nums[mid] > target: 22 | right = mid - 1 23 | else: 24 | left = mid + 1 25 | 26 | return left 27 | 28 | 29 | a = Solution() 30 | print(a.searchInsert(nums = [1,3,5,6], target = 5)) 31 | print(a.searchInsert(nums = [1,3,5,6], target = 2)) 32 | print(a.searchInsert(nums = [1,3,5,6], target = 7)) -------------------------------------------------------------------------------- /LeetCode/153.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 153. Find Minimum in Rotated Sorted Array 3 | # Medium 4 | # Array, Binary Search 5 | # https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 6 | 7 | from typing import List 8 | 9 | class Solution: 10 | def findMin(self, nums: List[int]) -> int: 11 | if len(nums) == 0: 12 | return -1 13 | 14 | if len(nums) == 1: 15 | return nums[0] 16 | 17 | left, right = 0, len(nums) - 1 18 | 19 | while left < right: 20 | mid = (left + right) // 2 21 | 22 | if mid > 0 and nums[mid] < nums[mid - 1]: 23 | return nums[mid] 24 | elif nums[left] <= nums[mid] and nums[mid] > nums[right]: 25 | left = mid + 1 26 | else: 27 | right = mid - 1 28 | 29 | return nums[left] 30 | 31 | 32 | a = Solution() 33 | print(a.findMin(nums = [3,4,5,1,2])) 34 | print(a.findMin(nums = [4,5,6,7,0,1,2])) 35 | print(a.findMin(nums = [11,13,15,17])) -------------------------------------------------------------------------------- /LeetCode/30.py: -------------------------------------------------------------------------------- 1 | # 30 2 | # Substring with Concatenation of All Words 3 | # https://leetcode.com/problems/substring-with-concatenation-of-all-words/ 4 | # Hard 5 | 6 | import itertools 7 | import re 8 | 9 | def findSubstring(s, words): 10 | positions = [] 11 | words = list(itertools.permutations(words)) 12 | final_words = [''.join(w) for w in words] 13 | 14 | for word in final_words: 15 | positions.extend([m.start() for m in re.finditer(word, s)]) 16 | # for word in final_words: 17 | # if word in s: 18 | # # positions.append(s.find(word)) 19 | 20 | return list(set(positions)) 21 | 22 | 23 | print(findSubstring(s = "barfoothefoobarman", words = ["foo","bar"])) 24 | print(findSubstring(s = "wordgoodgoodgoodbestword", words = ["word","good","best","good"])) 25 | # Output: [8, 8] 26 | # Result: [8] 27 | print(findSubstring(s = "foobarfoobar", words = ["foo","bar"])) 28 | # Output: [0,3] 29 | # Result: [0,3,6] 30 | print(findSubstring(s = "aaa", words = ["a","a"])) 31 | # Output: [0] 32 | # Result: [0,1] -------------------------------------------------------------------------------- /LeetCode/347.py: -------------------------------------------------------------------------------- 1 | # 347 2 | # Top K Frequent Elements 3 | # https://leetcode.com/problems/top-k-frequent-elements/description/ 4 | # Medium 5 | # Array, Hash Table, Divide and Conquer, Sorting, 6 | # Heap (Priority Queue), Bucket Sort, Counting, 7 | # Quickselect 8 | 9 | from typing import List 10 | 11 | 12 | # Time Complexity O(klogn) 13 | class Solution: 14 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 15 | count = {} 16 | freq = [[] for i in range(len(nums) + 1)] 17 | 18 | for n in nums: 19 | count[n] = 1 + count.get(n, 0) 20 | 21 | for n, c in count.items(): 22 | freq[c].append(n) 23 | 24 | result = [] 25 | 26 | for i in range(len(freq) - 1, 0, -1): 27 | for n in freq[i]: 28 | result.append(n) 29 | 30 | if len(result) == k: 31 | return result 32 | 33 | 34 | 35 | print(Solution().topKFrequent(nums = [1,1,1,2,2,3], k = 2)) 36 | print(Solution().topKFrequent(nums = [1], k = 1)) 37 | -------------------------------------------------------------------------------- /LeetCode/39.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 39. Combination Sum 3 | # https://leetcode.com/problems/combination-sum/ 4 | # Medium 5 | # Array, Backtracking 6 | 7 | 8 | from typing import List 9 | 10 | 11 | 12 | class Solution: 13 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 14 | results = [] 15 | 16 | def backtrack(index, current, total): 17 | if total == target: 18 | results.append(current.copy()) 19 | return 20 | 21 | if index >= len(candidates) or total > target: 22 | return 23 | 24 | current.append(candidates[index]) 25 | backtrack(index, current, total + candidates[index]) 26 | 27 | current.pop() 28 | backtrack(index + 1, current, total) 29 | 30 | backtrack(0, [], 0) 31 | 32 | return results 33 | 34 | 35 | a = Solution() 36 | 37 | print(a.combinationSum(candidates = [2,3,6,7], target = 7)) 38 | print(a.combinationSum(candidates = [2,3,5], target = 8)) 39 | print(a.combinationSum(candidates = [2], target = 1)) -------------------------------------------------------------------------------- /LeetCode/41.py: -------------------------------------------------------------------------------- 1 | # 41 2 | # First Missing Positive 3 | # https://leetcode.com/problems/first-missing-positive/ 4 | 5 | # TLE Solution, answer is right But TLE 6 | # def first_missing_positive(nums): 7 | # index = 1 8 | # nums = [x for x in nums if x > 0] 9 | # nums.sort() 10 | 11 | # for n in range(len(nums)): 12 | # if index in nums: 13 | # index += 1 14 | # else: 15 | # return index 16 | 17 | # return index 18 | 19 | def first_missing_positive(nums): 20 | n = len(nums) 21 | 22 | # rearranging elements for correcting position 23 | for i in range(n): 24 | while 0 < nums[i] <= n and nums[nums[i] - 1] != nums[i]: 25 | nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] 26 | 27 | # finding the missing number if that is not in correct position 28 | for i in range(n): 29 | if nums[i] != i + 1: 30 | return i + 1 31 | 32 | # when every elements is in correct position then the answer is length + 1 33 | return n + 1 34 | 35 | print(first_missing_positive(nums = [1,2,0])) 36 | print(first_missing_positive(nums = [3,4,-1,1])) 37 | print(first_missing_positive(nums = [7,8,9,11,12])) -------------------------------------------------------------------------------- /LeetCode/217.py: -------------------------------------------------------------------------------- 1 | # 217 2 | # https://leetcode.com/problems/contains-duplicate/description/ 3 | # Easy 4 | # Array, Hash Table, Sorting 5 | 6 | 7 | 8 | from typing import List 9 | 10 | 11 | # Previous accepted solution 12 | # class Solution: 13 | # def containsDuplicate(self, nums: List[int]) -> bool: 14 | # nums.sort() 15 | 16 | # for i in range(0, len(nums)-1): 17 | # if nums[i] == nums[i+1]: 18 | # return True 19 | 20 | # return False 21 | 22 | # Another solution 23 | # class Solution: 24 | # def containsDuplicate(self, nums: List[int]) -> bool: 25 | # hashset = set() 26 | 27 | # for n in nums: 28 | # if n in hashset: 29 | # return True 30 | 31 | # hashset.add(n) 32 | 33 | # return False 34 | 35 | 36 | # Another solution 37 | class Solution: 38 | def containsDuplicate(self, nums: List[int]) -> bool: 39 | return False if len(set(nums)) == len(nums) else True 40 | 41 | solution = Solution() 42 | 43 | print(solution.containsDuplicate(nums=[1, 2, 3, 1])) 44 | print(solution.containsDuplicate(nums=[1, 2, 3, 4])) 45 | print(solution.containsDuplicate(nums=[1,1,1,3,3,4,3,2,4,2])) -------------------------------------------------------------------------------- /LeetCode/154.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 154. Find Minimum in Rotated Sorted Array II 3 | # Array, Binary Search 4 | # https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ 5 | 6 | from typing import List 7 | 8 | 9 | 10 | class Solution: 11 | # def findMin(self, nums: List[int]) -> int: 12 | # return self.search(nums=nums, left=0, right=len(nums)-1) 13 | 14 | 15 | # def search(self, nums: List[int], left: int, right: int) -> int: 16 | # if left == right: 17 | # return nums[left] 18 | 19 | # mid = (left + right) // 2 20 | 21 | # if nums[mid] > nums[right]: 22 | # return self.search(nums=nums, left=mid+1, right=right) 23 | 24 | # elif nums[mid] < nums[right]: 25 | # return self.search(nums=nums, left=left, right=mid) 26 | 27 | # else: 28 | # left_min = self.search(nums=nums, left=left, right=mid) 29 | # right_min = self.search(nums=nums, left=mid+1, right=right) 30 | 31 | # return min(left_min, right_min) 32 | def findMind(self, nums: List[int]) -> int: 33 | pass 34 | 35 | 36 | a = Solution() 37 | 38 | print(a.findMin(nums = [1,3,5])) 39 | print(a.findMin(nums = [2,2,2,0,1])) 40 | print(a.findMin(nums = [1,1])) -------------------------------------------------------------------------------- /LeetCode/34.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number[]} 5 | */ 6 | 7 | // O(log n) solution 8 | let searchRange = function(nums, target) { 9 | left = binSearch(nums = nums, target = target, isLeftBias = true); 10 | right = binSearch(nums = nums, target = target, isLeftBias = false); 11 | 12 | return [left, right]; 13 | }; 14 | 15 | let binSearch = function (nums, target, isLeftBias) { 16 | let left = 0; 17 | let right = nums.length - 1; 18 | let index = -1; 19 | 20 | while (left <= right) { 21 | let mid = Math.floor((left + right) / 2); 22 | 23 | if (target > nums[mid]) { 24 | left = mid + 1; 25 | } else if (target < nums[mid]) { 26 | right = mid - 1; 27 | } else { 28 | index = mid; 29 | 30 | if (isLeftBias) { 31 | right = mid - 1; 32 | } else { 33 | left = mid + 1; 34 | } 35 | } 36 | } 37 | 38 | return index; 39 | }; 40 | 41 | console.log(searchRange(nums = [5, 7, 7, 8, 8, 10], target = 8)); 42 | console.log(searchRange(nums = [5, 7, 7, 8, 8, 10], target = 7)); 43 | console.log(searchRange(nums = [5, 7, 7, 8, 8, 10], target = 6)); 44 | console.log(searchRange(nums = [], target = 0)); -------------------------------------------------------------------------------- /LeetCode/31.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 31 3 | # Next Permutation 4 | # https://leetcode.com/problems/next-permutation 5 | # Medium 6 | # Array, Two Pointer 7 | 8 | 9 | 10 | from typing import List 11 | 12 | 13 | 14 | class Solution: 15 | def nextPermutation(self, nums: List[int]) -> None: 16 | """ 17 | Do not return anything, modify nums in-place instead. 18 | """ 19 | n = len(nums) 20 | 21 | if n == 1: 22 | return 23 | 24 | i = 1 25 | lastInc = -1 26 | 27 | # Finding peak of the last Ascending Order 28 | while i < n: 29 | if nums[i] > nums[i - 1]: 30 | lastInc = i 31 | i += 1 32 | 33 | # Check if Array is in Descending Order 34 | if lastInc == -1: 35 | for i in range(int(n/2)): 36 | nums[i], nums[n-i-1] = nums[n-i-1], nums[i] 37 | 38 | return 39 | 40 | # Find the element in the range (nums[lastInc-1] to nums[lastInc]) to the right 41 | index = lastInc 42 | 43 | for i in range(lastInc, n): 44 | if nums[i] > nums[lastInc-1] and nums[i] < nums[index]: 45 | index = i 46 | 47 | nums[lastInc-1], nums[index] = nums[index], nums[lastInc-1] 48 | 49 | nums[lastInc:] = sorted(nums[lastInc:]) 50 | 51 | return nums -------------------------------------------------------------------------------- /LeetCode/238.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 238 3 | # Product of Array Except Self 4 | # Medium 5 | # https://leetcode.com/problems/product-of-array-except-self/ 6 | # Array, Prefix Sum 7 | 8 | 9 | # # My First Attempt 10 | # def product(nums): 11 | # result = [] 12 | 13 | # # for i in range(0, len(nums)): 14 | # # p = 1 15 | 16 | # # for j in range(0, len(nums)): 17 | # # if i != j: 18 | # # p *= nums[j] 19 | 20 | # # result.append(p) 21 | # for i in range(0, len(nums)): 22 | # print(nums[~i]) 23 | 24 | # return result 25 | 26 | # print(product([1,2,3,4])) 27 | # print(product([-1,1,0,-3,3])) 28 | 29 | from typing import List 30 | 31 | 32 | # Time Complexity O(n), with no extra memory 33 | class Solution: 34 | def productExceptSelf(self, nums: List[int]) -> List[int]: 35 | result = [1] * len(nums) 36 | 37 | # from beginning to end 38 | prefix = 1 39 | for i in range(len(nums)): 40 | result[i] = prefix 41 | prefix *= nums[i] 42 | 43 | postfix = 1 44 | for i in range(len(nums) - 1, -1, -1): 45 | result[i] *= postfix 46 | postfix *= nums[i] 47 | 48 | return result 49 | 50 | 51 | print(Solution().productExceptSelf(nums = [1,2,3,4])) 52 | print(Solution().productExceptSelf(nums = [-1,1,0,-3,3])) 53 | -------------------------------------------------------------------------------- /LeetCode/125.py: -------------------------------------------------------------------------------- 1 | # 125 2 | # Valid Palindrome 3 | # Easy 4 | # https://leetcode.com/problems/valid-palindrome/description/ 5 | # Two Pointers, String 6 | 7 | 8 | # Solution 1 9 | # class Solution: 10 | # def isPalindrome(self, s: str) -> bool: 11 | # new_s = "" 12 | 13 | # for c in s: 14 | # if c.isalnum(): 15 | # new_s += c.lower() 16 | 17 | # return new_s == new_s[::-1] 18 | 19 | 20 | 21 | # Solution 2: Two pointer solution 22 | class Solution: 23 | def isPalindrome(self, s: str) -> bool: 24 | left, right = 0, len(s) - 1 25 | 26 | while left < right: 27 | while left < right and not self.isAlphaNum(s[left]): 28 | left += 1 29 | 30 | while left < right and not self.isAlphaNum(s[right]): 31 | right -= 1 32 | 33 | if s[left].lower() != s[right].lower(): 34 | return False 35 | 36 | left, right = left + 1, right - 1 37 | 38 | return True 39 | 40 | 41 | def isAlphaNum(self, c): 42 | return (ord('A') <= ord(c) <= ord('Z') or 43 | ord('a') <= ord(c) <= ord('z') or 44 | ord('0') <= ord(c) <= ord('9')) 45 | 46 | print(Solution().isPalindrome(s = "A man, a plan, a canal: Panama")) 47 | print(Solution().isPalindrome(s = "race a car")) 48 | print(Solution().isPalindrome(s = "rac a car")) -------------------------------------------------------------------------------- /LeetCode/33.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 33. Search in Rotated Sorted Array 3 | # Medium 4 | # Array, Binary Search 5 | # https://leetcode.com/problems/search-in-rotated-sorted-array/ 6 | 7 | def search(nums, target): 8 | # This is a solution, but with runtime complexity O(log n) which is not appropriate. 9 | # if target not in nums: 10 | # return -1 11 | 12 | # return nums.index(target) 13 | 14 | # O(log n) solution 15 | n = len(nums) 16 | left, right = 0, n-1 17 | 18 | # find the index of the smallest element 19 | while left < right: 20 | mid = (left + right) // 2 21 | 22 | if nums[mid] > nums[right]: 23 | left = mid + 1 24 | else: 25 | right = mid 26 | 27 | # set the bounds for the binary search 28 | if target <= nums[-1]: 29 | left, right = left, n - 1 30 | else: 31 | left, right = 0, left - 1 32 | 33 | # perform binary search 34 | while left <= right: 35 | mid = (left + right) // 2 36 | 37 | if nums[mid] == target: 38 | return mid 39 | elif nums[mid] < target: 40 | left = mid + 1 41 | else: 42 | right = mid - 1 43 | 44 | return -1 45 | 46 | print(search(nums = [4,5,6,7,0,1,2], target = 0)) 47 | print(search(nums = [5,6,7,0,1,2,4], target = 0)) 48 | print(search(nums = [4,5,6,7,0,1,2], target = 3)) 49 | print(search(nums = [1], target = 0)) -------------------------------------------------------------------------------- /LeetCode/1.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 1 3 | # Two Sum 4 | # https://leetcode.com/problems/two-sum/ 5 | # Array, Hash Table 6 | 7 | 8 | from typing import List 9 | 10 | # Solution 1 11 | # Time complexity: O(n^2) 12 | class Solution: 13 | def twoSum(self, nums: List[int], target: int) -> List[int]: 14 | for i in range(len(nums)-1): 15 | for j in range(i+1, len(nums)): 16 | if nums[i] + nums[j] == target: 17 | return [i, j] 18 | 19 | # Solution 2 20 | # Time complexity: O(n) 21 | class Solution: 22 | def twoSum(self, nums: List[int], target: int) -> List[int]: 23 | hash_map = {} 24 | 25 | for i in range(len(nums)): 26 | hash_map[nums[i]] = i 27 | 28 | for i in range(len(nums)): 29 | result = target - nums[i] 30 | 31 | if result in hash_map and hash_map[result] != i: 32 | return [i, hash_map[result]] 33 | 34 | 35 | # Solution 3 36 | # Time complexity: O(n) 37 | # Memory compexity: O(n) 38 | class Solution: 39 | def twoSum(self, nums: List[int], target: int) -> List[int]: 40 | prevMap = {} # Value: Index 41 | 42 | for i, n in enumerate(nums): 43 | diff = target - n 44 | 45 | if diff in prevMap: 46 | return [prevMap[diff], i] 47 | 48 | prevMap[n] = i 49 | 50 | return 51 | -------------------------------------------------------------------------------- /LeetCode/166.py: -------------------------------------------------------------------------------- 1 | # 166 2 | # Fraction to Recurring Decimal 3 | # https://leetcode.com/problems/fraction-to-recurring-decimal/ 4 | # Medium 5 | 6 | def fractionToDecimal(numerator: int, denominator: int): 7 | if denominator == 0: 8 | return '' 9 | 10 | if numerator == 0: 11 | return '0' 12 | 13 | sign = '' 14 | 15 | if (numerator < 0 and denominator > 0) or (numerator > 0 and denominator < 0): 16 | sign = '-' 17 | 18 | numerator = abs(numerator) 19 | denominator = abs(denominator) 20 | 21 | integer_part = numerator // denominator 22 | remainder = numerator % denominator 23 | 24 | if remainder == 0: 25 | return sign + str(integer_part) 26 | 27 | fractional_part = '' 28 | hash_table = {} 29 | index = 0 30 | 31 | while remainder != 0: 32 | if remainder in hash_table: 33 | index = hash_table[remainder] 34 | 35 | fractional_part = fractional_part[:index] + '(' + fractional_part[index:] + ')' 36 | 37 | break 38 | 39 | hash_table[remainder] = index 40 | index += 1 41 | 42 | numerator = remainder * 10 43 | fractional_part += str(numerator // denominator) 44 | remainder = numerator % denominator 45 | 46 | return sign + str(integer_part) + '.' + fractional_part 47 | 48 | 49 | 50 | 51 | 52 | print(fractionToDecimal(numerator=4, denominator=333)) 53 | print(fractionToDecimal(numerator=1, denominator=2)) 54 | print(fractionToDecimal(numerator=2, denominator=1)) -------------------------------------------------------------------------------- /LeetCode/1347.py: -------------------------------------------------------------------------------- 1 | # 1347 2 | # Minimum Number of Steps to Make Two Strings Anagram 3 | # https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/ 4 | # Medium 5 | 6 | from collections import Counter 7 | 8 | def min_steps(s, t): 9 | c1, c2 = Counter(s), Counter(t) 10 | 11 | # result = [value for key, value in c2.items()] 12 | # print(result) 13 | n = 0 14 | 15 | for c in c2: 16 | # print(c, c2[c]) 17 | if c in c1: 18 | print('if') 19 | print(c1[c], c2[c]) 20 | # n += c1[c] - c2[c] 21 | n += c2[c] - c1[c] 22 | else: 23 | print('else') 24 | n += c2[c] 25 | 26 | return n 27 | # sorted_s = sorted(s) 28 | # sorted_t = sorted(t) 29 | 30 | # # print(sorted_s) 31 | # # print(sorted_t) 32 | 33 | # counter = 0 34 | 35 | # # for x in range(len(sorted_s)): 36 | # # if sorted_s[x] != sorted_t[x]: 37 | # # counter += 1 38 | 39 | # dict_s = {} 40 | # dict_t = {} 41 | 42 | # for x in sorted_s: 43 | # if x in dict_s: 44 | # dict_s[x] += 1 45 | # else: 46 | # dict_s[x] = 1 47 | 48 | # for y in sorted_t: 49 | # if y in dict_t: 50 | # dict_t[y] += 1 51 | # else: 52 | # dict_t[y] = 1 53 | 54 | # # print(dict_s) 55 | # # print(dict_t) 56 | # for x, y in zip(dict_s, dict_t): 57 | # print(x, y) 58 | 59 | # return counter 60 | 61 | 62 | print(min_steps(s = "bab", t = "aba")) 63 | # print(min_steps(s = "leetcode", t = "practice")) -------------------------------------------------------------------------------- /LeetCode/242.py: -------------------------------------------------------------------------------- 1 | # 242 2 | # Valid Anagram 3 | # https://leetcode.com/problems/valid-anagram/ 4 | # Hash Table, String, Sorting 5 | 6 | # from typing import str 7 | 8 | # New solution 1 9 | # class Solution: 10 | # def isAnagram(self, s: str, t: str) -> bool: 11 | # if len(s) != len(t): 12 | # return False 13 | 14 | # countS, countT = {}, {} 15 | 16 | # for i in range(len(s)): 17 | # countS[s[i]] = 1 + countS.get(s[i], 0) 18 | # countT[t[i]] = 1 + countT.get(t[i], 0) 19 | 20 | # for c in countS: 21 | # if countS[c] != countT.get(c, 0): 22 | # return False 23 | 24 | # return True 25 | 26 | # New solution 2 27 | # from collections import Counter 28 | 29 | # class Solution: 30 | # def isAnagram(self, s: str, t: str) -> bool: 31 | # return Counter(s) == Counter(t) 32 | 33 | 34 | # New solution 3 35 | class Solution: 36 | def isAnagram(self, s: str, t: str) -> bool: 37 | return sorted(s) == sorted(t) 38 | 39 | solution = Solution() 40 | 41 | print(solution.isAnagram(s="anagram", t="nagaram")) 42 | print(solution.isAnagram(s="rat", t="car")) 43 | 44 | # Previous Solution 45 | # def is_anagram(s: str, t: str): 46 | # if len(s) != len(t): 47 | # return False 48 | 49 | # s_counts = {} 50 | # t_counts = {} 51 | 52 | # for c in s: 53 | # if c in s_counts: 54 | # s_counts[c] += 1 55 | # else: 56 | # s_counts[c] = 1 57 | 58 | # for c in t: 59 | # if c in t_counts: 60 | # t_counts[c] += 1 61 | # else: 62 | # t_counts[c] = 1 63 | 64 | # return s_counts == t_counts 65 | 66 | 67 | # print(is_anagram(s="anagram", t="nagaram")) 68 | # print(is_anagram(s="rat", t="car")) -------------------------------------------------------------------------------- /HackerRank/ChocolateFeast.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | # Easy 4 | # Implementation 5 | 6 | import math 7 | import os 8 | import random 9 | import re 10 | import sys 11 | 12 | # 13 | # Complete the 'chocolateFeast' function below. 14 | # 15 | # The function is expected to return an INTEGER. 16 | # The function accepts following parameters: 17 | # 1. INTEGER n 18 | # 2. INTEGER c 19 | # 3. INTEGER m 20 | # 21 | 22 | 23 | def chocolateFeast(n, c, m): 24 | chocolates = n // c 25 | wrappers = chocolates 26 | 27 | while wrappers >= m: 28 | new_chocolates = wrappers // m 29 | chocolates += new_chocolates 30 | wrappers = (wrappers % m) + new_chocolates 31 | 32 | return chocolates 33 | 34 | 35 | # if __name__ == '__main__': 36 | # fptr = open(os.environ['OUTPUT_PATH'], 'w') 37 | # t = int(input().strip()) 38 | 39 | # for t_itr in range(t): 40 | # first_multiple_input = input().rstrip().split() 41 | # n = int(first_multiple_input[0]) 42 | # c = int(first_multiple_input[1]) 43 | # m = int(first_multiple_input[2]) 44 | # result = chocolateFeast(n, c, m) 45 | # fptr.write(str(result) + '\n') 46 | 47 | # fptr.close() 48 | if __name__ == '__main__': 49 | with open('HackerRank/input.txt', 'r') as fptr: 50 | t = int(fptr.readline().strip()) 51 | 52 | results = [] 53 | for t_itr in range(t): 54 | first_multiple_input = fptr.readline().rstrip().split() 55 | 56 | n = int(first_multiple_input[0]) 57 | c = int(first_multiple_input[1]) 58 | m = int(first_multiple_input[2]) 59 | 60 | result = chocolateFeast(n, c, m) 61 | results.append(result) 62 | 63 | with open('HackerRank/output.txt', 'w') as fptr: 64 | for result in results: 65 | fptr.write(str(result) + '\n') 66 | -------------------------------------------------------------------------------- /LeetCode/36.py: -------------------------------------------------------------------------------- 1 | # 36 2 | # Valid Sudoku 3 | # https://leetcode.com/problems/valid-sudoku/ 4 | # Medium 5 | # Array, Hash Table, Matrix 6 | 7 | from typing import List 8 | import collections 9 | 10 | 11 | 12 | class Solution: 13 | def isValidSudoku(self, board: List[List[str]]) -> bool: 14 | cols = collections.defaultdict(set) # columns 15 | rows = collections.defaultdict(set) # rows 16 | squares = collections.defaultdict(set) # square, key = (r // 3, c // 3) 17 | 18 | for r in range(9): 19 | for c in range(9): 20 | if board[r][c] == '.': 21 | continue 22 | 23 | if board[r][c] in rows[r] or board[r][c] in cols[c] or board[r][c] in squares[(r // 3), (c // 3)]: 24 | return False 25 | 26 | rows[r].add(board[r][c]) 27 | cols[c].add(board[r][c]) 28 | squares[(r // 3), (c // 3)].add(board[r][c]) 29 | 30 | return True 31 | 32 | 33 | 34 | print(Solution().isValidSudoku(board = 35 | [["5","3",".",".","7",".",".",".","."] 36 | ,["6",".",".","1","9","5",".",".","."] 37 | ,[".","9","8",".",".",".",".","6","."] 38 | ,["8",".",".",".","6",".",".",".","3"] 39 | ,["4",".",".","8",".","3",".",".","1"] 40 | ,["7",".",".",".","2",".",".",".","6"] 41 | ,[".","6",".",".",".",".","2","8","."] 42 | ,[".",".",".","4","1","9",".",".","5"] 43 | ,[".",".",".",".","8",".",".","7","9"]])) 44 | 45 | print(Solution().isValidSudoku(board = 46 | [["8","3",".",".","7",".",".",".","."] 47 | ,["6",".",".","1","9","5",".",".","."] 48 | ,[".","9","8",".",".",".",".","6","."] 49 | ,["8",".",".",".","6",".",".",".","3"] 50 | ,["4",".",".","8",".","3",".",".","1"] 51 | ,["7",".",".",".","2",".",".",".","6"] 52 | ,[".","6",".",".",".",".","2","8","."] 53 | ,[".",".",".","4","1","9",".",".","5"] 54 | ,[".",".",".",".","8",".",".","7","9"]])) -------------------------------------------------------------------------------- /LeetCode/49.py: -------------------------------------------------------------------------------- 1 | # 49 2 | # Group Anagrams 3 | # https://leetcode.com/problems/group-anagrams/ 4 | 5 | 6 | # My own solution 7 | # def group_anagrams(strs): 8 | # anagrams = {} 9 | 10 | # for s in strs: 11 | # sorted_str = ''.join(sorted(s)) 12 | 13 | # if sorted_str in anagrams: 14 | # anagrams[sorted_str].append(s) 15 | # else: 16 | # anagrams[sorted_str] = [s] 17 | 18 | # return anagrams.values() 19 | 20 | # print(group_anagrams(strs = ["eat","tea","tan","ate","nat","bat"])) 21 | # print(group_anagrams(strs = [""])) 22 | # print(group_anagrams(strs = ["a"])) 23 | 24 | # ChatGPT solution 25 | # from collections import defaultdict 26 | 27 | # class Solution: 28 | # def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 29 | # # Create a defaultdict to store the anagrams 30 | # anagrams = defaultdict(list) 31 | 32 | # # Iterate through the list of strings 33 | # for s in strs: 34 | # # Sort the characters of the string 35 | # sorted_str = ''.join(sorted(s)) 36 | # # Add the original string to the list of anagrams for the sorted string 37 | # anagrams[sorted_str].append(s) 38 | 39 | # # Return the values of the defaultdict 40 | # return anagrams.values() 41 | 42 | # Time Complexity = O(m * n * 26) = O(m * n) 43 | # Here m = number of the input string 44 | # Here n = average length of each string 45 | from typing import List 46 | from collections import defaultdict 47 | 48 | class Solution: 49 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 50 | result = defaultdict(list) # mapping charCount to List of Anagrams 51 | 52 | for s in strs: 53 | count = [0] * 26 # a TO z 54 | 55 | for c in s: 56 | count[ord(c) - ord("a")] += 1 57 | 58 | result[tuple(count)].append(s) 59 | 60 | return result.values() 61 | 62 | 63 | 64 | print(Solution().groupAnagrams(strs = ["eat","tea","tan","ate","nat","bat"])) 65 | print(Solution().groupAnagrams(strs = [""])) 66 | print(Solution().groupAnagrams(strs = ["a"])) -------------------------------------------------------------------------------- /LeetCode/34.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 34. Find First and Last Position of Element in Sorted Array 3 | # Medium 4 | # Array, Binary Search 5 | # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 6 | 7 | # O(log n) solution 8 | from typing import List 9 | 10 | class Solution: 11 | def searchRange(self, nums: List[int], target: int) -> List[int]: 12 | left = self.binSearch(nums=nums, target=target, leftBias=True) 13 | right = self.binSearch(nums=nums, target=target, leftBias=False) 14 | 15 | return [left, right] 16 | 17 | # leftBiased = [True/False], if false, result is rightBiased 18 | def binSearch(self, nums, target, leftBias): 19 | left, right = 0, len(nums) - 1 20 | index = -1 21 | 22 | while left <= right: 23 | mid = (left + right) // 2 24 | 25 | if target > nums[mid]: 26 | left = mid + 1 27 | elif target < nums[mid]: 28 | right = mid - 1 29 | else: 30 | index = mid 31 | 32 | if leftBias: 33 | right = mid - 1 34 | else: 35 | left = mid + 1 36 | 37 | return index 38 | 39 | 40 | a = Solution() 41 | 42 | print(a.searchRange(nums = [5,7,7,8,8,10], target = 8)) 43 | print(a.searchRange(nums = [5,7,7,8,8,10], target = 7)) 44 | print(a.searchRange(nums = [5,7,7,8,8,10], target = 6)) 45 | print(a.searchRange(nums = [], target = 0)) 46 | 47 | # Explain 1 48 | # nums = [5,7,7,8,8,10], target = 8 49 | # leftBias = True 50 | # left = 0, right = 5 51 | # mid = (0+5) // 2 = 2 52 | # 8 > 7, so left = 2 + 1 = 3 53 | # mid = (3+5) // 2 = 4 54 | # 8 == 8, so index = 4 55 | # leftBias is True, so right = 4 - 1 = 3, left = 3 56 | # mid = 3 57 | # 8 ==8, so index = 3 58 | # left and right is equal, so loop break 59 | # return 3 60 | # nums = [5,7,7,8,8,10], target = 8 61 | # leftBias = False 62 | # left = 0, right = 5 63 | # mid = (0+5) // 2 = 2 64 | # 8 > 7, so left = 2 + 1 = 3 65 | # mid = 4 66 | # 8 == 8, so index = 4 67 | # leftBias is False, so, left = 3 + 1, right = 5 68 | # mid = (4+5) // 2 = 4 69 | # 8 == 8, so index = 4 70 | # leftBias is False, so left = 4 + 1 = 5, right = 5 71 | # 8 < 10, so left = 5 + 1 72 | # left is equal or greater than right, so break 73 | # return 4 -------------------------------------------------------------------------------- /LeetCode/81.py: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | # 81. Search in Rotated Sorted Array II 3 | # Medium 4 | # Array, Binary Search 5 | # https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ 6 | 7 | from typing import List 8 | 9 | class Solution: 10 | def search(self, nums: List[int], target: int) -> bool: 11 | # Simple solution 1 12 | # if target in nums: 13 | # return True 14 | 15 | # return False 16 | # More simple solution 2 17 | # return True if target in nums else False 18 | 19 | # Algorithmic solution 3 20 | # left, right = 0, len(nums) - 1 21 | 22 | # while left <= right: 23 | # if nums[left] == target or nums[right] == target: 24 | # return True 25 | 26 | # elif target > nums[left]: 27 | # while left < right and nums[left+1] == nums[left]: 28 | # left += 1 29 | 30 | # left += 1 31 | 32 | # elif target < nums[right]: 33 | # while left < right and nums[right-1] == nums[right]: 34 | # right -= 1 35 | 36 | # right -= 1 37 | 38 | # else: 39 | # break 40 | 41 | # return False 42 | 43 | # Algorithm solution 4, O(logn) solution 44 | # Algorithm: 45 | # 1. Initialize two pointers, 'left' and 'right', where 'left' points to 46 | # the first element of the array and 'right' points to the last element 47 | # of the array. 48 | # 2. While 'left' is less than or equal to 'right', repeat steps 3 49 | # through 6: 50 | # 3. Compute the middle element of the array as 'mid' = (left + right) / 2. 51 | # 4. If the middle element is equal to the target, return 'true'. 52 | # 5. If the left half of the array is sorted, i.e., nums[left] <= nums[mid], 53 | # then check if the target is in the left half, i.e., nums[left] <= target < nums[mid], 54 | # and adjust the 'right' pointer accordingly. 55 | # 6. If the right half of the array is sorted, i.e., nums[mid] <= nums[right], 56 | # then check if the target is in the right half, i.e., nums[mid] < target <= nums[right], 57 | # and adjust the 'left' pointer accordingly. 58 | # 7. If the target is not found after the while loop, return 'false'. 59 | left, right = 0, len(nums) - 1 60 | 61 | while left <= right: 62 | mid = (left + right) // 2 63 | 64 | if nums[mid] == target: 65 | return True 66 | 67 | if nums[left] == nums[mid] and nums[right] == nums[mid]: 68 | left += 1 69 | right -= 1 70 | elif nums[left] <= nums[mid]: 71 | if nums[left] <= target < nums[mid]: 72 | right = mid - 1 73 | else: 74 | left = mid + 1 75 | else: 76 | if nums[mid] < target <= nums[right]: 77 | left = mid + 1 78 | else: 79 | right = mid - 1 80 | 81 | return False 82 | 83 | 84 | 85 | a = Solution() 86 | 87 | print(a.search(nums = [2,5,6,0,0,1,2], target = 0)) 88 | print(a.search(nums = [2,5,6,0,0,1,2], target = 3)) 89 | print(a.search(nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1], target = 2)) -------------------------------------------------------------------------------- /LeetCode/cprob1.py: -------------------------------------------------------------------------------- 1 | def max_depth(s): 2 | depth = 0 3 | max_depth = 0 4 | 5 | for c in s: 6 | if c in '<': 7 | depth += 1 8 | max_depth = max(max_depth, depth) 9 | elif c in '>': 10 | depth -= 1 11 | # if depth > max_depth: 12 | # max_depth = depth 13 | 14 | return max_depth 15 | 16 | s = '< <<>> <<>> >' 17 | s = '<<><><<<>>><<>>>' 18 | s = '<<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<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<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<' 19 | print(max_depth(s)) -------------------------------------------------------------------------------- /LeetCode/cprob2.py: -------------------------------------------------------------------------------- 1 | def count_brackets(s): 2 | left = s.count('<') 3 | right = s.count('>') 4 | 5 | print('left: ', left) 6 | print('right: ', right) 7 | 8 | return abs(left-right) 9 | 10 | # def count_brackets(s, left_count, right_count): 11 | # if s == '': 12 | # return abs(left_count - right_count) 13 | # # if not s: 14 | # # return abs(left_count - right_count) 15 | 16 | # if s[0] == '<': 17 | # left_count += 1 18 | # elif s[0] == '>': 19 | # right_count += 1 20 | 21 | # return count_brackets(s[1:], left_count, right_count) 22 | # # return abs(left_count - right_count) 23 | 24 | s = '<<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>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<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<<<<<<<<<<>>>>>><<<<<<<' 25 | # s = '< <<>> <<>> >' 26 | # s = '<<><><<<>>><<>>>' 27 | print(count_brackets(s)) 28 | # print(count_brackets(s, 0, 0)) --------------------------------------------------------------------------------