├── .gitignore ├── .pre-commit-config.yaml ├── Programming-Solutions ├── 01-Two-Sum-EASY.py ├── 02-Add-Two-Numbers-MEDIUM.py ├── 03-Longest-Substring-Without-Repeating-Characters-MEDIUM.py ├── 09-Palindrome-Number-EASY.py ├── 118-Pascals-Triangle-EASY.py ├── 119-Pascals-Triangle-II-EASY.py ├── 121-Best-Time-to-Buy-and-Sell-Stock-EASY.py ├── 125-Valid-Palindrome-EASY.py ├── 128-Longest-Consecutive-Sequence-MEDIUM.py ├── 13-Roman-to-Integer-EASY.py ├── 136-Single-Number-EASY.py ├── 14-Longest-Common-Prefix-EASY.py ├── 1476-Subrectangle-Queries-MEDIUM.py ├── 168-Excel-Sheet-Column-Title-EASY.py ├── 169-Majority-Element-EASY.py ├── 171-Excel-Sheet-Column-Number-EASY.py ├── 1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation-EASY.py ├── 1929-Concatenation-of-Array-EASY.py ├── 20-Valid-Parenthesis-EASY.py ├── 202-Happy-Number-EASY.py ├── 2022-Convert-1D-Array-Into-2D-Array-EASY.py ├── 217-Contains-Duplicates-EASY.py ├── 228-Summary-Ranges-EASY.py ├── 238-Product-of-Array-Except-Self-MEDIUM.py ├── 258-Add-Digits-EASY.py ├── 26-Remove-Duplicates-from-Sorted-Array-EASY.py ├── 268-Missing-Number-EASY.py ├── 27-Remove-Element-EASY.py ├── 28-Implement-strStr()-EASY.py ├── 287-Find-the-Duplicate-Number-MEDIUM.py ├── 303-Range-Sum-Query-EASY.py ├── 338-Counting-Bits-EASY.py ├── 35-Search-Insert-Position-EASY.py ├── 378-Kth-Smallest-Element-in-Sorted-Matrix-MEDIUM.py ├── 410-Split-Array-Largest-Sum-HARD.py ├── 442-Find-All-Duplicates-in-an-Array-MEDIUM.py ├── 448-Find-All-Numbers-Disappeared-Array-EASY.py ├── 48-Rotate-Image-MEDIUM.py ├── 53-Maximum-Subarray.EASY.py ├── 54-Spiral-Matrix-MEDIUM.py ├── 58-Lenght-of-Last-Word-EASY.py ├── 66-Plus-One-EASY.py ├── 67-Add-Binary-EASY.py ├── 69-Sqrt(x)-EASY.py ├── 7-Reverse-Integer-MEDIUM.py ├── 70-Climbing-Stairs-EASY.py ├── 704-Binary-Search-EASY.py ├── 73-Set-Matrix-Zeroes-MEDIUM.py ├── 744-Find-Smallest-Letter-Greater-Than-Target-EASY.py ├── 844-Backspace-String-Compare-EASY.py ├── 852-Peak-Index-in-a-Mountain-Array-EASY.py └── 977-Squares-of-a-Sorted-Array-EASY.py ├── README.md ├── images └── leetcode.png ├── leetcode_exercises.ipynb └── pyproject.toml /.gitignore: -------------------------------------------------------------------------------- 1 | *venv/ 2 | *.egg-info/ 3 | */.DS_Store 4 | *.pyc 5 | build/ 6 | __pycache__/ 7 | .ipynb_checkpoints/ 8 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v4.5.0 4 | hooks: 5 | - id: check-yaml 6 | - id: end-of-file-fixer 7 | - id: trailing-whitespace 8 | - repo: https://github.com/psf/black 9 | rev: 23.12.1 10 | hooks: 11 | - id: black 12 | - id: black-jupyter 13 | - repo: https://github.com/pycqa/isort 14 | rev: 5.13.2 15 | hooks: 16 | - id: isort 17 | name: isort (python) 18 | args: ["--profile", "black", "--filter-files"] 19 | - repo: https://github.com/pre-commit/mirrors-prettier 20 | rev: "v4.0.0-alpha.8" 21 | hooks: 22 | - id: prettier 23 | additional_dependencies: 24 | - prettier 25 | - prettier-plugin-svelte 26 | exclude: (CHANGELOG.md)$ 27 | # - repo: https://github.com/codespell-project/codespell 28 | # rev: v2.2.6 29 | # hooks: 30 | # - id: codespell 31 | # exclude: (package.*.json|.ipynb|CHANGELOG.md)$ 32 | -------------------------------------------------------------------------------- /Programming-Solutions/01-Two-Sum-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/two-sum/ 3 | """ 4 | 5 | 6 | def twoSum(nums, target): 7 | seen = {} 8 | for i, value in enumerate(nums): 9 | remaining = target - nums[i] 10 | 11 | if remaining in seen: 12 | return [seen[remaining], i] 13 | 14 | seen[value] = i 15 | 16 | 17 | def main(): 18 | test_cases = [([2, 7, 11, 15], 9), ([3, 2, 4], 6), ([3, 3], 6)] 19 | 20 | for i in test_cases: 21 | print(twoSum(i[0], i[1])) 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /Programming-Solutions/02-Add-Two-Numbers-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/add-two-numbers/ 3 | """ 4 | 5 | 6 | # Definition for singly-linked list. 7 | class ListNode: 8 | def __init__(self, val=0, next=None): 9 | self.val = val 10 | self.next = next 11 | 12 | 13 | # Converting a list to a linked list 14 | def lst2link(lst): 15 | cur = dummy = ListNode(0) 16 | for e in lst: 17 | cur.next = ListNode(e) 18 | cur = cur.next 19 | return dummy.next 20 | 21 | 22 | # Adding numbers of two linked lists 23 | def addTwoNumbers(l1, l2): 24 | ans = [] 25 | dummy = cur = ListNode(0) 26 | carry = 0 27 | while l1 or l2 or carry: 28 | if l1: 29 | carry += l1.val 30 | l1 = l1.next 31 | if l2: 32 | carry += l2.val 33 | l2 = l2.next 34 | cur.next = ListNode(carry % 10) 35 | cur = cur.next 36 | carry //= 10 37 | ans.append(cur.val) 38 | return dummy.next, ans 39 | 40 | 41 | def main(): 42 | test_cases = [ 43 | [[2, 4, 3], [5, 6, 4]], 44 | [[0], [0]], 45 | [[2, 4, 6], [3, 5, 7]], 46 | [[9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9]], 47 | ] 48 | for i, j in test_cases: 49 | l1 = lst2link(i) 50 | l2 = lst2link(j) 51 | 52 | # Print results 53 | obj, ans = addTwoNumbers(l1, l2) 54 | print(ans) 55 | 56 | 57 | if __name__ == "__main__": 58 | main() 59 | -------------------------------------------------------------------------------- /Programming-Solutions/03-Longest-Substring-Without-Repeating-Characters-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/longest-substring-without-repeating-characters/ 3 | """ 4 | 5 | 6 | def lengthOfLongestSubstring(s): 7 | strSet = set() 8 | start = output = 0 9 | 10 | for index in range(len(s)): 11 | while s[index] in strSet: 12 | strSet.remove(s[start]) 13 | start += 1 14 | strSet.add(s[index]) 15 | output = max(output, index - start + 1) 16 | return output 17 | 18 | 19 | def main(): 20 | test_cases = [ 21 | 'pwwkew', 22 | 'abcabcbb', 23 | 'bbbbbbb', 24 | 'dvdf', 25 | 'ckilbkd', 26 | 'abba', 27 | 'abac', 28 | '', 29 | 'x' 30 | ] 31 | for s in test_cases: 32 | print(lengthOfLongestSubstring(s)) 33 | 34 | 35 | if __name__ == '__main__': 36 | main() 37 | -------------------------------------------------------------------------------- /Programming-Solutions/09-Palindrome-Number-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/palindrome-number/ 3 | """ 4 | 5 | 6 | def palindrome_loop(string): 7 | string = str(string) 8 | j = -1 9 | 10 | for i in range(len(string)//2): 11 | if string[i] == string[j]: 12 | j -= 1 13 | continue 14 | else: 15 | return 'no' 16 | 17 | return 'yes' 18 | 19 | 20 | def palindrome(string): 21 | string = str(string) 22 | inv = string[::-1] 23 | 24 | if string == inv: 25 | return 'true' 26 | else: 27 | return 'false' 28 | 29 | 30 | def main(): 31 | test_cases = { 32 | ('rotor'), 33 | (101), 34 | ('10000001'), 35 | ('Hannah'), 36 | (100000000000010000000000001) 37 | } 38 | for i in test_cases: 39 | print(palindrome_loop(i)) 40 | 41 | print() 42 | test = [ 43 | (121), 44 | (-121), 45 | (10) 46 | ] 47 | for i in test: 48 | print(palindrome(i)) 49 | 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /Programming-Solutions/118-Pascals-Triangle-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/pascals-triangle/ 3 | """ 4 | 5 | 6 | def generate(num): 7 | ans = [] 8 | 9 | for i in range(1, num+1): 10 | c, pascal = 1, [] 11 | for j in range(1, i+1): 12 | pascal.append(c) 13 | c = c * (i-j)//j 14 | ans.append(pascal) 15 | return ans 16 | 17 | 18 | def pascal_triangle(num): 19 | """ 20 | :param num: int 21 | :return: list 22 | if numRows = 5 23 | [ 24 | [1], 25 | [1,1], 26 | [1,2,1], 27 | [1,3,3,1], 28 | [1,4,6,4,1] 29 | ] 30 | """ 31 | res = [[1]] 32 | for i in range(1, num): 33 | temp1 = res[-1] + [0] 34 | temp2 = [0] + res[-1] 35 | var = [] 36 | for j in range(len(temp1)): 37 | var.append(temp1[j] + temp2[j]) 38 | res.append(var) 39 | # res.append([temp1[j] + temp2[j] for j in range(len(temp1))]) 40 | return res[:num] 41 | 42 | 43 | def main(): 44 | test_cases = [ 45 | 5, 46 | 1, 47 | 0, 48 | 7 49 | ] 50 | for num in test_cases: 51 | print(generate(num)) 52 | print(pascal_triangle(num)) 53 | 54 | 55 | if __name__ == '__main__': 56 | main() 57 | -------------------------------------------------------------------------------- /Programming-Solutions/119-Pascals-Triangle-II-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/pascals-triangle-ii/ 3 | """ 4 | 5 | 6 | def getRow(row): 7 | ans = [[1]] 8 | for i in range(1, row+1): 9 | temp1 = ans[-1] + [0] 10 | temp2 = [0] + ans[-1] 11 | var, pascal = 0, [] 12 | for j in range(len(temp1)): 13 | var = temp1[j] + temp2[j] 14 | pascal.append(var) 15 | ans.append(pascal) 16 | 17 | return ans[-1] 18 | 19 | 20 | def main(): 21 | test_cases = [ 22 | 3, 23 | 1, 24 | 0, 25 | 7 26 | ] 27 | for num in test_cases: 28 | print(getRow(num)) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /Programming-Solutions/121-Best-Time-to-Buy-and-Sell-Stock-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 3 | """ 4 | 5 | 6 | def maxProfit(prices): 7 | buy = sell = 0 8 | max_profit = 0 9 | for p in range(len(prices)): 10 | if prices[p] < prices[buy]: 11 | buy = p 12 | else: 13 | sell = p 14 | max_profit = max(max_profit, prices[sell] - prices[buy]) 15 | return max_profit 16 | 17 | 18 | def main(): 19 | test_cases = [ 20 | [7, 1, 5, 3, 6, 4], 21 | [2, 4, 1], 22 | [7, 6, 4, 3, 1] 23 | ] 24 | for prices in test_cases: 25 | print(maxProfit(prices)) 26 | 27 | 28 | if __name__ == '__main__': 29 | main() 30 | -------------------------------------------------------------------------------- /Programming-Solutions/125-Valid-Palindrome-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/valid-palindrome/ 3 | """ 4 | 5 | 6 | def isPalindrome(s): 7 | # Converting uppercase letters into lowercase and removing non-alphanumeric characters 8 | pal = '' 9 | for i in s: 10 | if i.isalnum(): 11 | pal += i.lower() 12 | 13 | for i in range(len(pal)): 14 | if pal[i] == pal[-i - 1]: 15 | continue 16 | else: 17 | return False 18 | return True 19 | 20 | 21 | def is_palindrome_pointers(s): 22 | l, r = 0, len(s)-1 23 | while l < r: 24 | if not s[l].isalnum(): 25 | l += 1 26 | elif not s[r].isalnum(): 27 | r -= 1 28 | else: 29 | if s[l].lower() != s[r].lower(): 30 | return False 31 | else: 32 | l += 1 33 | r -= 1 34 | return True 35 | 36 | 37 | def main(): 38 | test_cases = [ 39 | "A man, a plan, a canal: Panama", 40 | "race a car", 41 | "0P" 42 | ] 43 | for string in test_cases: 44 | print(isPalindrome(string)) 45 | print(is_palindrome_pointers(string)) 46 | 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /Programming-Solutions/128-Longest-Consecutive-Sequence-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/longest-consecutive-sequence/ 3 | """ 4 | 5 | 6 | def longest_consecutive_naive(nums): 7 | if len(nums) == 0: 8 | return 0 9 | 10 | nums = sorted(set(nums)) 11 | seq, temp = [], [nums[0]] 12 | 13 | for i in range(1, len(nums)): 14 | if nums[i] == nums[i - 1] + 1: 15 | temp.append(nums[i]) 16 | else: 17 | seq.append(temp) 18 | temp = [nums[i]] 19 | 20 | seq.append(temp) 21 | return max([len(i) for i in seq]) 22 | 23 | 24 | def longest_consecutive(num): 25 | num = set(num) 26 | maxLen = 0 27 | while num: 28 | n = num.pop() 29 | i = n+1 30 | l1, l2 = 0, 0 31 | while i in num: 32 | num.remove(i) 33 | i += 1 34 | l1 += 1 35 | i = n-1 36 | while i in num: 37 | num.remove(i) 38 | i -= 1 39 | l2 += 1 40 | maxLen = max(maxLen, l1+l2+1) 41 | return maxLen 42 | 43 | 44 | def main(): 45 | test_cases = [ 46 | [100, 101, 4, 200, 1, 3, 2], 47 | [0, 3, 7, 2, 5, 8, 4, 6, 0, 1] 48 | ] 49 | for nums in test_cases: 50 | print(longest_consecutive_naive(nums)) 51 | print(longest_consecutive(nums)) 52 | 53 | 54 | if __name__ == '__main__': 55 | main() 56 | -------------------------------------------------------------------------------- /Programming-Solutions/13-Roman-to-Integer-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/roman-to-integer/ 3 | """ 4 | 5 | 6 | def romanToInt(s: str) -> int: 7 | dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 8 | # temp array to store the values of each symbol from dictionary 9 | values = [dict[i] for i in s] 10 | output, i = 0, 0 11 | 12 | # Loop though temp array 13 | while i < len(values): 14 | # If i == last index of elements in temp array, return total output + element 15 | if i == len(values)-1: 16 | return output + values[i] 17 | # If next element is greater than current element, subtract next element with current, and skip next element 18 | elif values[i+1] > values[i]: 19 | output += values[i+1] - values[i] 20 | i += 2 21 | # Otherwise, add element to output 22 | else: 23 | output += values[i] 24 | i += 1 25 | return output 26 | 27 | 28 | if __name__ == '__main__': 29 | test_cases = [ 30 | ('I'), 31 | ('III'), 32 | ('IX'), 33 | ('XIV'), 34 | ('XXIV'), 35 | ('LVIII'), 36 | ('MCMXCIV') 37 | ] 38 | for roman in test_cases: 39 | print(romanToInt(roman)) 40 | -------------------------------------------------------------------------------- /Programming-Solutions/136-Single-Number-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/single-number/ 3 | """ 4 | 5 | 6 | def singleNumber(nums): 7 | dic = {} 8 | for n in nums: 9 | if n not in dic: 10 | dic[n] = 1 11 | else: 12 | dic[n] += 1 13 | return min(dic, key=dic.get) 14 | 15 | 16 | def main(): 17 | test_cases = [ 18 | [2, 2, 1], 19 | [4, 1, 2, 1, 2], 20 | [1] 21 | ] 22 | for test in test_cases: 23 | print(singleNumber(test)) 24 | 25 | 26 | if __name__ == '__main__': 27 | main() 28 | -------------------------------------------------------------------------------- /Programming-Solutions/14-Longest-Common-Prefix-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/longest-common-prefix/ 3 | 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | If there is no common prefix, return an empty string "". 6 | """ 7 | 8 | 9 | # ['flower', 'flow', 'flight'] 10 | # compare first letter of first word with first letter of second word 11 | # create temp variable to store letter 12 | ## if both letters are the same -> continue 13 | ## else -> break 14 | 15 | 16 | def commonPrefix(strs): 17 | res = "" 18 | shortest = min(strs, key=len) 19 | for i in range(len(shortest)): 20 | for j in range(len(strs)): 21 | if strs[j][i] != shortest[i]: 22 | return res 23 | res += shortest[i] 24 | return res 25 | 26 | 27 | def longestCommonPrefix(strs): 28 | if not strs: 29 | return "" 30 | 31 | for i, letter_group in enumerate(zip(*strs)): 32 | if len(set(letter_group)) > 1: 33 | return strs[0][:i] 34 | else: 35 | return min(strs) 36 | 37 | 38 | if __name__ == '__main__': 39 | strs = [ 40 | (['flower', 'flow', 'flight']), 41 | (["a"]), 42 | (['dog', 'racecar', 'car']), 43 | ([""]) 44 | ] 45 | 46 | for lst in strs: 47 | print(longestCommonPrefix(lst)) 48 | 49 | for lst in strs: 50 | print(commonPrefix(lst)) 51 | -------------------------------------------------------------------------------- /Programming-Solutions/1476-Subrectangle-Queries-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/subrectangle-queries/ 3 | """ 4 | 5 | 6 | class SubrectangleQueries: 7 | def __init__(self, rectangle): 8 | self.rectangle = rectangle 9 | 10 | def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: 11 | for i in range(row1, row2 + 1): 12 | for j in range(col1, col2 + 1): 13 | self.rectangle[i][j] = newValue 14 | 15 | def getValue(self, row: int, col: int) -> int: 16 | return self.rectangle[row][col] 17 | 18 | 19 | def main(): 20 | global obj 21 | test_cases = [ 22 | (["SubrectangleQueries", "getValue", "updateSubrectangle", "getValue", "getValue", "updateSubrectangle", 23 | "getValue", "getValue"], 24 | [[[1, 2, 1], [4, 3, 4], [3, 2, 1], [1, 1, 1]], 25 | [0, 2], 26 | [0, 0, 3, 2, 5], 27 | [0, 2], 28 | [3, 1], 29 | [3, 0, 3, 2, 10], 30 | [3, 1], [0, 2]]), 31 | (["SubrectangleQueries", "getValue", "updateSubrectangle", "getValue", "getValue", "updateSubrectangle", 32 | "getValue"], 33 | [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], 34 | [0, 0], 35 | [0, 0, 2, 2, 100], 36 | [0, 0], 37 | [2, 2], 38 | [1, 1, 2, 2, 20], 39 | [2, 2]]) 40 | ] 41 | output = [] 42 | for array in test_cases: 43 | iteration = [] 44 | for string in range(len(array[0])): 45 | if array[0][string] == "SubrectangleQueries": 46 | rectangle = array[1][0] 47 | obj = SubrectangleQueries(rectangle) 48 | iteration.append('null') 49 | elif array[0][string] == "getValue": 50 | row = array[1][string][0] 51 | col = array[1][string][1] 52 | iteration.append(obj.getValue(row, col)) 53 | # print(f"getValue: {obj.getValue(row, col)}") 54 | else: 55 | row1 = array[1][string][0] 56 | col1 = array[1][string][1] 57 | row2 = array[1][string][2] 58 | col2 = array[1][string][3] 59 | newValue = array[1][string][4] 60 | obj.updateSubrectangle(row1, col1, row2, col2, newValue) 61 | iteration.append('null') 62 | # print(f'update: {obj.updateSubrectangle(row1, col1, row2, col2, newValue)}') 63 | output.append(iteration) 64 | for i in output: 65 | print(i) 66 | 67 | 68 | if __name__ == '__main__': 69 | main() 70 | 71 | 72 | # Your SubrectangleQueries object will be instantiated and called as such: 73 | # obj = SubrectangleQueries(rectangle) 74 | # obj.updateSubrectangle(row1,col1,row2,col2,newValue) 75 | # param_2 = obj.getValue(row,col) 76 | -------------------------------------------------------------------------------- /Programming-Solutions/168-Excel-Sheet-Column-Title-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/excel-sheet-column-title/ 3 | """ 4 | import string 5 | 6 | 7 | def convertToTitle(x): 8 | z = dict((i, k) for i, k in enumerate(string.ascii_uppercase)) 9 | ans = "" 10 | while x > 0: 11 | x -= 1 12 | y = x % 26 13 | x = x // 26 14 | ans = str(z[y]) + ans 15 | return ans 16 | 17 | 18 | def main(): 19 | test_cases = [ 20 | 1, 21 | 28, 22 | 701 23 | ] 24 | for num in test_cases: 25 | print(convertToTitle(num)) 26 | 27 | 28 | if __name__ == '__main__': 29 | main() 30 | -------------------------------------------------------------------------------- /Programming-Solutions/169-Majority-Element-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/majority-element/ 3 | """ 4 | 5 | 6 | def majorityElement(nums): 7 | d = {} 8 | for elem in range(len(nums)): 9 | if nums[elem] not in d.keys(): 10 | d[nums[elem]] = 1 11 | else: 12 | d[nums[elem]] += 1 13 | return max(d, key=d.get) 14 | 15 | 16 | # Using the Boyer Moore algorithm 17 | def majority_element_boyer_moore(nums): 18 | res, times = 0, 0 19 | for i in nums: 20 | if times == 0: 21 | res = i 22 | if i == res: 23 | times += 1 24 | else: 25 | times -= 1 26 | return res 27 | 28 | 29 | def main(): 30 | test_cases = [ 31 | [3, 2, 3], # output: 3 32 | [2, 2, 1, 1, 1, 2, 2], # output: 2 33 | [3, 3, 4] # output: 3 34 | ] 35 | for array in test_cases: 36 | print(majorityElement(array)) 37 | print(majority_element_boyer_moore(array)) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Programming-Solutions/171-Excel-Sheet-Column-Number-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/excel-sheet-column-number/ 3 | """ 4 | 5 | 6 | def titleToNumber(columnTitle): 7 | ans, pos = 0, 0 8 | for letter in reversed(columnTitle): 9 | digit = ord(letter) - 64 10 | ans += digit * 26 ** pos 11 | pos += 1 12 | 13 | return ans 14 | 15 | 16 | def main(): 17 | test_cases = [ 18 | "A", # 1 19 | "B", # 2 20 | "AA", # 27 21 | "AB", # 28 22 | "ZA", # 677 23 | "ZY", # 701 24 | "AAA", # 703 25 | "FAB", # 4084 26 | "ZAA", # 17603 (26*26*26+27) 27 | "FXSHRXW" # 2,147,483,647 28 | ] 29 | for string in test_cases: 30 | print(titleToNumber(string)) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /Programming-Solutions/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/ 3 | """ 4 | 5 | 6 | # Using for loops to rotate the matrix 7 | def findRotation(matrix, target): 8 | n = len(matrix[0]) 9 | for _ in range(4): 10 | if matrix == target: 11 | return True 12 | else: 13 | for i in range(len(matrix)): 14 | for j in range(n): 15 | matrix[i].append(matrix[-j - 1].pop(0)) 16 | return False 17 | 18 | 19 | # Using zip() to rotate the matrix 20 | def find_rotation_simple(matrix, target): 21 | for _ in range(4): 22 | if matrix == target: 23 | return True 24 | else: 25 | matrix = [list(a) for a in zip(*matrix[::-1])] 26 | return False 27 | 28 | 29 | def main(): 30 | test_cases = [ 31 | ([[0, 1], [1, 0]], [[1, 0], [0, 1]]), 32 | ([[0, 1], [1, 1]], [[1, 0], [0, 1]]), 33 | ([[0, 0, 0], [0, 1, 0], [1, 1, 1]], [[1, 1, 1], [0, 1, 0], [0, 0, 0]]) 34 | ] 35 | for matrix, target in test_cases: 36 | print(findRotation(matrix, target)) 37 | # print(find_rotation_simple(matrix, target)) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Programming-Solutions/1929-Concatenation-of-Array-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/concatenation-of-array/ 3 | """ 4 | 5 | 6 | def getConcatenation(nums: list[int]) -> list[int]: 7 | return nums + nums 8 | 9 | 10 | def main(): 11 | test_cases = [ 12 | [1, 2, 1], 13 | [1, 3, 2, 1], 14 | [2, 4, 6, 7, 7] 15 | ] 16 | for array in test_cases: 17 | print(getConcatenation(array)) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /Programming-Solutions/20-Valid-Parenthesis-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/valid-parentheses/ 3 | 4 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | 6 | An input string is valid if: 7 | - Open brackets must be closed by the same type of brackets. 8 | - Open brackets must be closed in the correct order. 9 | 10 | Input: s = "()" 11 | Output: true 12 | """ 13 | 14 | 15 | def isValid(s): 16 | # Dictionary of parenthesis pairs 17 | dic = {'(': ')', '[': ']', '{': '}'} 18 | res = [] 19 | # Iterate over each parenthesis in string 20 | for c in s: 21 | # Append parenthesis value to array if in dictionary 22 | if c in dic: 23 | res.append(c) 24 | # Check if parenthesis value corresponds to its key 25 | else: 26 | if len(res) and dic[res[-1]] == c: 27 | del res[-1] 28 | # Return False if parenthesis value is not in the dictionary 29 | else: 30 | return False 31 | # Return True is res list is empty 32 | return res == [] 33 | 34 | 35 | if __name__ == '__main__': 36 | strs = [ 37 | '()[]{}', 38 | '{[()]}', 39 | '[)', 40 | '([)]', 41 | '(', 42 | "[]()(()" 43 | ] 44 | 45 | for string in strs: 46 | print(isValid(string)) 47 | -------------------------------------------------------------------------------- /Programming-Solutions/202-Happy-Number-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/happy-number/ 3 | """ 4 | 5 | 6 | def isHappy(n): 7 | nums = [i for i in str(n)] 8 | counter = 0 9 | if int(nums[0]) > 0: 10 | while nums != '1' and counter < 1000: 11 | nums = sum([int(i)**2 for i in nums]) 12 | nums = str(nums) 13 | counter += 1 14 | if nums == '1' and counter < 1000: 15 | return True 16 | return False 17 | 18 | 19 | def main(): 20 | test_cases = [ 21 | 19, 22 | 2 23 | ] 24 | for i in test_cases: 25 | print(isHappy(i)) 26 | 27 | 28 | if __name__ == '__main__': 29 | main() 30 | -------------------------------------------------------------------------------- /Programming-Solutions/2022-Convert-1D-Array-Into-2D-Array-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/convert-1d-array-into-2d-array/ 3 | """ 4 | import numpy as np 5 | 6 | 7 | def construct2DArray(original, m, n): 8 | array = [] 9 | if len(original) == m*n: 10 | for i in range(0, len(original), n): 11 | array.append(original[i:i+n]) 12 | return array 13 | 14 | 15 | def construct2DArrayNumPy(original, m, n): 16 | if len(original) != m*n: 17 | return [] 18 | 19 | array = np.array(original).reshape(m, n) 20 | return array 21 | 22 | 23 | def main(): 24 | test_cases = [ 25 | ([1, 2, 3, 4], 2, 2), 26 | ([1, 2, 3], 1, 3), 27 | ([1, 2], 1, 1) 28 | ] 29 | for array, m, n in test_cases: 30 | print(construct2DArray(array, m, n)) 31 | # print(construct2DArrayNumPy(array, m, n)) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /Programming-Solutions/217-Contains-Duplicates-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/contains-duplicate/ 3 | """ 4 | 5 | 6 | def containsDuplicates(nums): 7 | numSet = set(nums) 8 | if len(nums) == len(numSet): 9 | return False 10 | return True 11 | 12 | 13 | def main(): 14 | test_cases = [ 15 | [1, 2, 3, 1], 16 | [1, 2, 3, 4], 17 | [1, 1, 1, 3, 3, 4, 3, 2, 4, 2] 18 | ] 19 | for test in test_cases: 20 | print(containsDuplicates(test)) 21 | 22 | 23 | if __name__ == '__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /Programming-Solutions/228-Summary-Ranges-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/summary-ranges/ 3 | """ 4 | 5 | 6 | def summaryRanges(nums): 7 | ranges = [] 8 | for i in nums: 9 | if ranges and ranges[-1][1] == i - 1: 10 | ranges[-1][1] = i 11 | else: 12 | ranges.append([i, i]) 13 | return [f"{a}->{b}" if len(set([a, b])) > 1 else f"{a}" for a, b in ranges] 14 | 15 | 16 | def main(): 17 | test_cases = [ 18 | [7], 19 | [0, 1, 2, 4, 5, 7], 20 | [0, 2, 3, 4, 6, 8, 9], 21 | [0, 1, 3, 4, 5, 7, 8, 9] 22 | ] 23 | for test in test_cases: 24 | print(summaryRanges(test)) 25 | 26 | 27 | if __name__ == '__main__': 28 | main() 29 | -------------------------------------------------------------------------------- /Programming-Solutions/238-Product-of-Array-Except-Self-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/product-of-array-except-self/ 3 | """ 4 | 5 | 6 | # Naive function 7 | def product_except_self_naive(nums): 8 | ans = [] 9 | for i in range(len(nums)): 10 | prod = 1 11 | for j in range(len(nums)): 12 | if i != j: 13 | prod = prod*nums[j] 14 | ans.append(prod) 15 | return ans 16 | 17 | 18 | # 2*O(n) runtime 19 | def productExceptSelf(nums): 20 | ans = [1] * len(nums) 21 | pre = 1 22 | for i in range(len(nums)): 23 | ans[i] = pre 24 | pre *= nums[i] 25 | post = 1 26 | for j in range(len(nums)-1, -1, -1): 27 | ans[j] *= post 28 | post *= nums[j] 29 | return ans 30 | 31 | 32 | # O(n) runtime 33 | def productExceptSelf_fast(nums): 34 | ans = [1] * len(nums) 35 | pre = 1 36 | post = 1 37 | for i in range(len(nums)): 38 | ans[i] *= pre 39 | pre *= nums[i] 40 | ans[~i] *= post 41 | post *= nums[~i] 42 | return ans 43 | 44 | 45 | def main(): 46 | test_cases = [ 47 | [1, 2, 3, 4], 48 | [-1, 1, 0, -3, 3], 49 | [0, 0], 50 | [2, 3, 4, 5], 51 | [1, 2, 3, 4, 5] 52 | ] 53 | for array in test_cases: 54 | # print(product_except_self_naive(array)) 55 | print(productExceptSelf(array)) 56 | print(productExceptSelf_fast(array)) 57 | 58 | 59 | if __name__ == '__main__': 60 | main() 61 | -------------------------------------------------------------------------------- /Programming-Solutions/258-Add-Digits-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/add-digits/ 3 | """ 4 | 5 | 6 | def addDigits(num): 7 | num = str(num) 8 | n = "" 9 | while len(n) != 1: 10 | n = str(sum([int(i) for i in num])) 11 | num = n 12 | return int(n) 13 | 14 | 15 | if __name__ == '__main__': 16 | print(addDigits(38)) 17 | -------------------------------------------------------------------------------- /Programming-Solutions/26-Remove-Duplicates-from-Sorted-Array-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 3 | """ 4 | 5 | 6 | def removeDuplicates(nums): 7 | # k is slow pointer 8 | k = 0 9 | for n in nums: 10 | if n != nums[k]: 11 | # increment slow pointer once 12 | k += 1 13 | nums[k] = n 14 | 15 | return k + 1 16 | 17 | 18 | if __name__ == '__main__': 19 | nums = [1, 1, 2] 20 | print(removeDuplicates(nums)) 21 | -------------------------------------------------------------------------------- /Programming-Solutions/268-Missing-Number-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/missing-number/ 3 | """ 4 | 5 | 6 | def missingNumber(nums): 7 | length = len(nums) + 1 8 | for i in range(length): 9 | if i not in nums: 10 | return i 11 | 12 | 13 | # One liner 14 | def missingNumber2(nums): 15 | return len(nums) * (len(nums) + 1) // 2 - sum(nums) 16 | 17 | 18 | def main(): 19 | test_cases = [ 20 | [3, 0, 1], 21 | [0, 1], 22 | [9, 6, 4, 2, 3, 5, 7, 0, 1], 23 | [1] 24 | ] 25 | for test in test_cases: 26 | print(missingNumber(test)) 27 | # print(missingNumber2(test)) 28 | 29 | 30 | if __name__ == '__main__': 31 | main() 32 | -------------------------------------------------------------------------------- /Programming-Solutions/27-Remove-Element-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/remove-element/ 3 | """ 4 | 5 | 6 | def removeElement(nums, val): 7 | i = 0 8 | while i < len(nums): 9 | if nums[i] == val: 10 | nums.pop(i) 11 | else: 12 | i += 1 13 | return len(nums) 14 | 15 | 16 | if __name__ == '__main__': 17 | nums = [3, 2, 2, 3] 18 | val = 3 19 | print(removeElement(nums, val)) 20 | -------------------------------------------------------------------------------- /Programming-Solutions/28-Implement-strStr()-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/implement-strstr/ 3 | """ 4 | 5 | 6 | def strStr(haystack, needle): 7 | if needle in haystack and len(needle) >= 1: 8 | return haystack.find(needle) 9 | elif needle in haystack: 10 | return 0 11 | else: 12 | return -1 13 | 14 | 15 | def strStr2(haystack, needle): 16 | nl, ml = len(needle), len(haystack) 17 | if nl == 0: 18 | return nl 19 | if ml < nl: 20 | return -1 21 | for i in range(ml - nl + 1): 22 | if haystack[i:i + nl] == needle: 23 | return i 24 | return -1 25 | 26 | 27 | if __name__ == '__main__': 28 | haystack = ['hello', 'aaaaa', "", "", "a", "mississippi"] 29 | needle = ['ll', 'bba', "", "a", "", "issip"] 30 | 31 | for word in range(len(haystack)): 32 | print(strStr(haystack[word], needle[word])) 33 | # print(strStr2(haystack[word], needle[word])) 34 | -------------------------------------------------------------------------------- /Programming-Solutions/287-Find-the-Duplicate-Number-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/find-the-duplicate-number/ 3 | """ 4 | 5 | 6 | def findDuplicate(nums): 7 | d = {} 8 | for i in nums: 9 | if i not in d: 10 | d[i] = 1 11 | else: 12 | return i 13 | 14 | 15 | def main(): 16 | test_cases = [ 17 | [1, 3, 4, 2, 2], 18 | [3, 1, 3, 4, 2], 19 | [2, 4, 6, 7, 7] 20 | ] 21 | for array in test_cases: 22 | print(findDuplicate(array)) 23 | 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /Programming-Solutions/303-Range-Sum-Query-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/range-sum-query-immutable/ 3 | """ 4 | 5 | 6 | class NumArray: 7 | def __init__(self, nums): 8 | self.nums = nums 9 | 10 | def sumRange(self, left: int, right: int) -> int: 11 | sumNums = 0 12 | for i in range(left, right + 1): 13 | sumNums += self.nums[i] 14 | return sumNums 15 | return sum(self.nums[i:j+1]) 16 | 17 | 18 | def main(): 19 | test_cases = [ 20 | [[-2, 0, 3, -5, 2, -1], [0, 2], [2, 5], [0, 5]], 21 | [[1, 2, 3, 4, 5, 6, 7], [0, 3], [3, 6], [1, 5]] 22 | ] 23 | for nums in test_cases: 24 | numArray = NumArray(nums[0]) 25 | print(numArray.nums) 26 | print(numArray.sumRange(left=nums[1][0], right=nums[1][1])) 27 | print(numArray.sumRange(left=nums[2][0], right=nums[2][1])) 28 | print(numArray.sumRange(left=nums[3][0], right=nums[3][1])) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | 34 | # Your NumArray object will be instantiated and called as such: 35 | # obj = NumArray(nums) 36 | # param_1 = obj.sumRange(left,right) 37 | # 38 | # ["NumArray", "sumRange", "sumRange", "sumRange"] 39 | # [[[-2, 0, 3, -5, 2, -1]], [0,2], [2,5], [0,5]] 40 | -------------------------------------------------------------------------------- /Programming-Solutions/338-Counting-Bits-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/counting-bits/ 3 | """ 4 | 5 | 6 | # Naive way 7 | def countBits_naive(n): 8 | bit, ans = [], [] 9 | for i in range(n + 1): 10 | bit.append(str(bin(i).split('b')[1])) 11 | 12 | for i in bit: 13 | count = 0 14 | if '1' in i: 15 | for j in i: 16 | if j == '1': 17 | count += 1 18 | ans.append(count) 19 | else: 20 | ans.append(0) 21 | return ans 22 | 23 | 24 | # Using slicing 25 | def countBits_slicing(n): 26 | ans = [0] 27 | while len(ans) <= n: 28 | ans += [i + 1 for i in ans] 29 | return ans[:n + 1] 30 | 31 | 32 | # Simple solution 33 | def countBits(n): 34 | ans = [] 35 | for i in range(n + 1): 36 | ans.append(int(bin(i)[2:].count('1'))) 37 | return ans 38 | 39 | 40 | def main(): 41 | test_cases = [2, 5, 15] 42 | for n in test_cases: 43 | print(countBits_naive(n)) 44 | print(countBits_slicing(n)) 45 | print(countBits(n)) 46 | 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /Programming-Solutions/35-Search-Insert-Position-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/search-insert-position/ 3 | 4 | Given a sorted array of distinct integers and a target value, return the index if the target is found. 5 | If not, return the index where it would be if it were inserted in order. 6 | You must write an algorithm with O(log n) runtime complexity. 7 | """ 8 | 9 | 10 | # Binary Search algorithm 11 | def searchInsert(array, target): 12 | start, end = 0, len(array)-1 13 | 14 | if array[end] < target: 15 | return end + 1 16 | elif array[start] > target: 17 | return start 18 | 19 | # Iterate over array while start is less than end 20 | while start <= end: 21 | mid = (start + end) // 2 22 | if array[mid] == target: 23 | return mid 24 | elif array[mid] < target: 25 | start = mid + 1 26 | else: 27 | end = mid - 1 28 | 29 | min_idx, max_idx = min(start, mid, end), max(start, mid, end) 30 | if array[min_idx] < target < array[max_idx]: 31 | return min_idx + 1 32 | else: 33 | return max_idx 34 | 35 | 36 | # SIMPLER SOLUTION 37 | def searchInsert2(nums, target): 38 | low = 0 39 | high = len(nums) - 1 40 | while low <= high: 41 | mid = (low + high) // 2 42 | if nums[mid] == target: 43 | return mid 44 | elif nums[mid] < target: 45 | low = mid + 1 46 | else: 47 | high = mid - 1 48 | return low 49 | 50 | 51 | def main(): 52 | array = [1, 3, 5, 6, 9] 53 | target = [0, 1, 2, 3, 4, 5, 7, 10] 54 | 55 | for t in target: 56 | print(searchInsert(array, t), searchInsert2(array, t)) 57 | 58 | 59 | if __name__ == '__main__': 60 | main() 61 | -------------------------------------------------------------------------------- /Programming-Solutions/378-Kth-Smallest-Element-in-Sorted-Matrix-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 3 | """ 4 | import bisect 5 | 6 | 7 | # Naive approach 8 | def kth_smallest_naive(matrix, k): 9 | array = sorted([matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i]))]) 10 | return array[k - 1] 11 | 12 | 13 | # Binary search 14 | def kth_smallest_binary_search(matrix, k): 15 | low, high = matrix[0][0], matrix[-1][-1] 16 | while low < high: 17 | mid = (low + high) // 2 18 | if sum(bisect.bisect_right(row, mid) for row in matrix) < k: 19 | low = mid + 1 20 | else: 21 | high = mid 22 | return low 23 | 24 | 25 | # Sorting approach 26 | def kth_smallest_sorting(matrix, k): 27 | array = [] 28 | for row in matrix: 29 | array += row 30 | return sorted(array)[k - 1] 31 | 32 | 33 | def main(): 34 | test_cases = [ 35 | ([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8), # 13 36 | ([[-5]], 1), # -5 37 | ([[1, 2], [1, 3]], 2), # 1 38 | ([[1, 2], [1, 3]], 1), # 1 39 | ([[1, 2], [1, 3]], 4), # 3 40 | ([[1, 2], [3, 3]], 1), # 1 41 | ([[1, 2], [1, 3]], 3), # 2 42 | ([[1, 2], [1, 3]], 2) # 1 43 | ] 44 | for matrix, k in test_cases: 45 | print(kth_smallest_naive(matrix, k)) 46 | print(kth_smallest_binary_search(matrix, k)) 47 | print(kth_smallest_sorting(matrix, k)) 48 | print() 49 | 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /Programming-Solutions/410-Split-Array-Largest-Sum-HARD.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/split-array-largest-sum/ 3 | """ 4 | 5 | 6 | def split_array_naive(nums, m): 7 | if not nums: 8 | return 0 9 | elif m == 1: 10 | return sum(nums) 11 | else: 12 | min_result = float('inf') 13 | for j in range(1, len(nums) + 1): 14 | left, right = sum(nums[:j]), split_array_naive(nums[j:], m - 1) 15 | min_result = min(min_result, max(left, right)) 16 | return min_result 17 | 18 | 19 | def split_array(nums, m): 20 | lo, hi = max(nums), sum(nums) 21 | while lo < hi: 22 | mid = (lo + hi) // 2 23 | tot, cnt = 0, 1 24 | for num in nums: 25 | if tot + num <= mid: 26 | tot += num 27 | else: 28 | tot = num 29 | cnt += 1 30 | if cnt > m: 31 | lo = mid + 1 32 | else: 33 | hi = mid 34 | return hi 35 | 36 | 37 | def main(): 38 | test_cases = [ 39 | ([7, 2, 5, 10, 8], 2), # 18 40 | ([1, 2, 3, 4, 5], 2), # 9 41 | ([1, 4, 4], 3), # 4 42 | ([1, 2, 3, 4, 5], 1) # 15 43 | ] 44 | for nums, m in test_cases: 45 | print(split_array_naive(nums, m)) 46 | # print(split_array(nums, m)) 47 | 48 | 49 | if __name__ == '__main__': 50 | main() 51 | -------------------------------------------------------------------------------- /Programming-Solutions/442-Find-All-Duplicates-in-an-Array-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/find-all-duplicates-in-an-array/ 3 | """ 4 | 5 | 6 | def findDuplicates(nums): 7 | dic = {} 8 | lst = [] 9 | for i in nums: 10 | if i not in dic: 11 | dic[i] = 1 12 | else: 13 | lst.append(i) 14 | return lst 15 | 16 | 17 | def main(): 18 | test_cases = [ 19 | [4, 3, 2, 7, 8, 2, 3, 1], 20 | [1, 1, 2], 21 | [1] 22 | ] 23 | for array in test_cases: 24 | print(findDuplicates(array)) 25 | 26 | 27 | if __name__ == '__main__': 28 | main() 29 | -------------------------------------------------------------------------------- /Programming-Solutions/448-Find-All-Numbers-Disappeared-Array-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 3 | """ 4 | 5 | 6 | def findDisappearedNumbers(nums): 7 | setNum = set(nums) 8 | arr = [] 9 | for i in range(1, len(nums)+1): 10 | if i not in setNum: 11 | arr.append(i) 12 | return arr 13 | 14 | 15 | def main(): 16 | test_cases = [ 17 | [4, 3, 2, 7, 8, 2, 3, 1], 18 | [1, 1] 19 | ] 20 | for test in test_cases: 21 | print(findDisappearedNumbers(test)) 22 | 23 | 24 | if __name__ == '__main__': 25 | main() 26 | -------------------------------------------------------------------------------- /Programming-Solutions/48-Rotate-Image-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/rotate-image/ 3 | """ 4 | 5 | 6 | def rotate_naive(matrix): 7 | ans = [] 8 | for i in range(len(matrix)): 9 | temp = [] 10 | for j in range(len(matrix[i])): 11 | temp.append(matrix[-j-1][i]) 12 | ans.append(temp) 13 | return ans 14 | 15 | 16 | # Rotate the matrix in-place 17 | def rotate(matrix): 18 | length = len(matrix[0]) 19 | for i in range(len(matrix)): 20 | for j in range(length): 21 | matrix[i].append(matrix[-j-1].pop(0)) 22 | return matrix 23 | 24 | 25 | # One-liner solution 26 | def rotate_simple(matrix): 27 | return list(zip(*matrix[::-1])) 28 | 29 | 30 | def main(): 31 | test_cases = [ 32 | [[1, 2, 3], [4, 5, 6], [7, 8, 9]], # [[7,4,1],[8,5,2],[9,6,3]] 33 | [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] 34 | ] 35 | for matrix in test_cases: 36 | # print(rotate_naive(matrix)) 37 | print(rotate(matrix)) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Programming-Solutions/53-Maximum-Subarray.EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/maximum-subarray/ 3 | """ 4 | 5 | 6 | def max_subarray_naive(nums): 7 | total, max_total = 0, nums[0] 8 | 9 | for i in range(len(nums)): 10 | for j in range(i+1, len(nums)+1): 11 | total = sum(nums[i:j]) 12 | max_total = max(total, max_total) 13 | 14 | return max_total 15 | 16 | 17 | def max_subarray_fast(nums): 18 | for i in range(1, len(nums)): 19 | nums[i] = max(nums[i - 1] + nums[i], nums[i]) 20 | return max(nums) 21 | 22 | 23 | def main(): 24 | # Test cases 25 | test_cases = [ 26 | [-2, 1, -3, 4, -1, 2, 1, -5, 4], 27 | [1], 28 | [5, 4, -1, 7, 8] 29 | ] 30 | for nums in test_cases: 31 | print(max_subarray_naive(nums), max_subarray_fast(nums)) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /Programming-Solutions/54-Spiral-Matrix-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/spiral-matrix/ 3 | """ 4 | 5 | 6 | def spiralOrder(matrix): 7 | rows = len(matrix)-1 8 | cols = len(matrix[0])-1 9 | spiral = [] 10 | i, j = 0, 0 11 | bound = [0, rows] 12 | side = [0, cols] 13 | 14 | # 4 movements: left, down, right, up 15 | while len(spiral) < (rows+1)*(cols+1): 16 | # 1. Going right 17 | while i == side[0] and j <= side[1]: 18 | spiral.append(matrix[i][j]) 19 | j += 1 20 | j -= 1 21 | bound[0] += 1 # update boundary 22 | # 2. Going down 23 | while j == side[1] and i < bound[1]: 24 | i += 1 25 | spiral.append(matrix[i][j]) 26 | j -= 1 27 | side[1] -= 1 # update side 28 | # 3. Going left 29 | while i == bound[1] and j >= side[0]: 30 | spiral.append(matrix[i][j]) 31 | j -= 1 32 | j += 1 33 | bound[1] -= 1 34 | # 4. Going up 35 | while j == side[0] and i > bound[0]: 36 | i -= 1 37 | spiral.append(matrix[i][j]) 38 | side[0] += 1 39 | j += 1 40 | 41 | return spiral[:(rows+1)*(cols+1)] 42 | 43 | 44 | def spiralOrder_simple(matrix): 45 | return matrix and [*matrix.pop(0)] + spiralOrder_simple([*zip(*matrix)][::-1]) 46 | 47 | 48 | def main(): 49 | test_cases = [ 50 | [[1, 2, 3], [4, 5, 6], [7, 8, 9]], 51 | [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 52 | ] 53 | for matrix in test_cases: 54 | print(spiralOrder(matrix)) 55 | print(spiralOrder_simple(matrix)) 56 | 57 | 58 | if __name__ == '__main__': 59 | main() 60 | -------------------------------------------------------------------------------- /Programming-Solutions/58-Lenght-of-Last-Word-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/length-of-last-word/ 3 | """ 4 | 5 | 6 | def lengthOfLastWord(s: str) -> int: 7 | # Split string by blank spaces and reverse string 8 | split = s.split(' ')[::-1] 9 | 10 | # Iterate over the string list 11 | for i in range(len(split)): 12 | # Keep iterative over blank space until find a word 13 | if len(split[i]) < 1: 14 | continue 15 | # Return length of the word 16 | else: 17 | return len(split[i]) 18 | 19 | 20 | # Simple solution using strip() 21 | def lengthOfLastWordSimple(s: str) -> int: 22 | s = s.strip().split() 23 | return len(s[-1]) 24 | 25 | 26 | # Main function with test cases 27 | def main(): 28 | strings = [ 29 | 'Hello World', 30 | " fly me to the moon ", 31 | "luffy is still joyboy" 32 | ] 33 | for s in strings: 34 | print(lengthOfLastWord(s)) 35 | # print(lengthOfLastWordSimple(s)) 36 | 37 | 38 | # Call main function 39 | if __name__ == '__main__': 40 | main() 41 | -------------------------------------------------------------------------------- /Programming-Solutions/66-Plus-One-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/plus-one/ 3 | """ 4 | 5 | 6 | def plusOne(digits: list[int]) -> list[int]: 7 | string = '' 8 | for i in digits: 9 | string += str(i) 10 | 11 | string = str(int(string) + int('1')) 12 | 13 | return [int(i) for i in str(string)] 14 | 15 | 16 | def plusOneComprehension(digits): 17 | # Converting integers to strings 18 | string = [str(i) for i in digits] 19 | # Adding 1 to the total number 20 | add = str(int(''.join(string)) + 1) 21 | # Return list of integers 22 | return [int(i) for i in add] 23 | 24 | 25 | def main(): 26 | test_cases = [ 27 | [1, 2, 3], 28 | [4, 3, 2, 1], 29 | [9] 30 | ] 31 | for nums in test_cases: 32 | print(plusOne(nums)) 33 | print(plusOneComprehension(nums)) 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /Programming-Solutions/67-Add-Binary-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/add-binary/ 3 | """ 4 | 5 | 6 | def addBinary(a, b): 7 | output = bin(int(a, 2) + int(b, 2)) 8 | return output.split('b')[1] 9 | 10 | 11 | def main(): 12 | a, b = '11', '1' 13 | print(addBinary(a, b)) 14 | 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /Programming-Solutions/69-Sqrt(x)-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/sqrtx/ 3 | """ 4 | 5 | 6 | def mySqrt(x: int) -> int: 7 | for num in range(x+1): 8 | if num * num == x: 9 | return num 10 | elif num*num > x: 11 | return num-1 12 | 13 | 14 | # Using binary search to find the sqrt(x) 15 | def binarySqrt(x): 16 | low = 0 17 | high = x 18 | while low <= high: 19 | mid = (low + high) // 2 20 | if mid * mid == x: 21 | return mid 22 | elif mid * mid > x: 23 | output = mid - 1 24 | high = mid - 1 25 | else: 26 | output = mid 27 | low = mid + 1 28 | return output 29 | 30 | 31 | def main(): 32 | test_cases = [5, 4, 6, 8, 16, 144, 160, 0, 1, 2, 3] 33 | for n in test_cases: 34 | print(mySqrt(n), binarySqrt(n)) 35 | 36 | 37 | if __name__ == '__main__': 38 | main() -------------------------------------------------------------------------------- /Programming-Solutions/7-Reverse-Integer-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/reverse-integer/ 3 | """ 4 | 5 | 6 | def reverse(x: int) -> int: 7 | # Reverse x 8 | x = str(x) 9 | if x[0] == '-': 10 | x = int('-' + x[::-1][:-1]) 11 | else: 12 | x = int(x[::-1]) 13 | # Check if x is outside the signed 32-bit integer range 14 | if -2 ** 31 <= x <= 2 ** 31: 15 | return x 16 | else: 17 | return 0 18 | 19 | 20 | def main(): 21 | test_cases = [ 22 | 123, 23 | -123, 24 | 120, 25 | 1534236469 26 | ] 27 | for num in test_cases: 28 | print(reverse(num)) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /Programming-Solutions/70-Climbing-Stairs-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/climbing-stairs/ 3 | """ 4 | 5 | 6 | def climbStairs(n: int) -> int: 7 | a, b = 0, 1 8 | for _ in range(n): 9 | a, b = b, a+b 10 | 11 | return b 12 | 13 | 14 | def main(): 15 | test_cases = [1, 2, 3, 4, 5, 6, 7, 8] 16 | for i in test_cases: 17 | print(climbStairs(i)) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /Programming-Solutions/704-Binary-Search-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/binary-search/ 3 | """ 4 | 5 | 6 | def search(nums, target): 7 | low, high = 0, len(nums)-1 8 | 9 | while low <= high: 10 | mid = (low + high) // 2 11 | if nums[mid] == target: 12 | return mid 13 | elif nums[mid] < target: 14 | low = mid + 1 15 | else: 16 | high = mid - 1 17 | return -1 18 | 19 | 20 | def main(): 21 | test_cases = [ 22 | [[-1, 0, 3, 5, 9, 12], 9], 23 | [[-1, 0, 3, 5, 9, 12], 2], 24 | [[-1, 0, 3, 5, 9, 12], 13] 25 | ] 26 | for nums, target in test_cases: 27 | print(search(nums, target)) 28 | 29 | 30 | if __name__ == '__main__': 31 | main() 32 | -------------------------------------------------------------------------------- /Programming-Solutions/73-Set-Matrix-Zeroes-MEDIUM.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/set-matrix-zeroes/ 3 | """ 4 | import numpy as np 5 | 6 | 7 | def setZeroes_NumPy(matrix): 8 | row = [] 9 | col = [] 10 | for i in range(len(matrix)): 11 | for j in range(len(matrix[i])): 12 | if matrix[i][j] == 0: 13 | # matrix[i] = [0]*len(matrix[i]) 14 | row.append(i) 15 | col.append(j) 16 | mat = np.array(matrix) 17 | for i in col: 18 | mat[:, i] = 0 19 | for i in row: 20 | mat[i] = 0 21 | return mat 22 | 23 | 24 | def setZeroes(matrix): 25 | row, col = [], [] 26 | # Iterate over array and identify rows and columns with zeros 27 | for i in range(len(matrix)): 28 | for j in range(len(matrix[i])): 29 | if matrix[i][j] == 0: 30 | row.append(i) 31 | col.append(j) 32 | # Modify entire rows and columns in matrix 33 | for i in range(len(matrix)): 34 | for j in range(len(matrix[i])): 35 | if j in col: 36 | matrix[i][j] = 0 37 | if i in row: 38 | matrix[i] = [0] * len(matrix[i]) 39 | 40 | return matrix 41 | 42 | 43 | def main(): 44 | test_cases = [ 45 | [[1, 1, 1], [1, 0, 1], [1, 1, 1]], 46 | [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]] 47 | ] 48 | for matrix in test_cases: 49 | print(setZeroes_NumPy(matrix)) 50 | print(setZeroes(matrix)) 51 | 52 | 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /Programming-Solutions/744-Find-Smallest-Letter-Greater-Than-Target-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/find-smallest-letter-greater-than-target/ 3 | """ 4 | 5 | 6 | def nextGreatestLetter(letters, target): 7 | if target < letters[0] or target >= letters[-1]: 8 | return letters[0] 9 | 10 | low, high = 0, len(letters)-1 11 | 12 | while low <= high: 13 | mid = (low + high) // 2 14 | if letters[mid] <= target and mid+1 < len(letters): 15 | low = mid + 1 16 | else: 17 | high = mid - 1 18 | return letters[low] 19 | 20 | 21 | def main(): 22 | test_cases = [ 23 | [["c", "f", "j"], "a"], 24 | [["c", "f", "j"], "c"], 25 | [["c", "f", "j"], "d"], 26 | [["c", "f", "j"], "j"], 27 | [["c", "f", "j"], "g"], 28 | [["e", 'e', "e", "e", "e", "e", "n", "n", "n", "n"], "e"] 29 | ] 30 | for letters, target in test_cases: 31 | print(nextGreatestLetter(letters, target)) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /Programming-Solutions/844-Backspace-String-Compare-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/backspace-string-compare/ 3 | """ 4 | 5 | 6 | def backspaceCompare(s, t): 7 | s_arr, t_arr = [], [] 8 | for i in range(len(s)): 9 | if s[i] == '#' and len(s_arr) > 0: 10 | s_arr.pop() 11 | elif s[i] != '#': 12 | s_arr.append(s[i]) 13 | 14 | for i in range(len(t)): 15 | if t[i] == '#' and len(t_arr) > 0: 16 | t_arr.pop() 17 | elif t[i] != '#': 18 | t_arr.append(t[i]) 19 | 20 | if s_arr == t_arr: 21 | return True 22 | return False 23 | 24 | 25 | def main(): 26 | test_cases = [ 27 | ('ab#c', 'ad#c'), 28 | ('ab##', 'c#d#'), 29 | ('a#c', 'b'), 30 | ("a##c", "#a#c") 31 | ] 32 | for s, t in test_cases: 33 | print(backspaceCompare(s, t)) 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /Programming-Solutions/852-Peak-Index-in-a-Mountain-Array-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/peak-index-in-a-mountain-array/ 3 | """ 4 | 5 | 6 | def peakIndexInMountainArray_Naive(arr): 7 | return arr.index(max(arr)) 8 | 9 | 10 | def peakIndexInMountainArray(arr): 11 | low, high = 0, len(arr)-1 12 | while low <= high: 13 | mid = (low + high) // 2 14 | if arr[mid-1] < arr[mid] > arr[mid+1] and mid <= len(arr)-1: 15 | return mid 16 | elif arr[mid] < arr[mid+1]: 17 | low = mid + 1 18 | else: 19 | high = mid - 1 20 | 21 | 22 | def main(): 23 | test_cases = [ 24 | [0, 1, 0], 25 | [0, 2, 1, 0], 26 | [0, 1, 2, 3, 1, 0] 27 | ] 28 | for array in test_cases: 29 | # print(peakIndexInMountainArray_Naive(array)) 30 | print(peakIndexInMountainArray(array)) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /Programming-Solutions/977-Squares-of-a-Sorted-Array-EASY.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/squares-of-a-sorted-array/ 3 | """ 4 | 5 | 6 | # Simple way to solve the problem 7 | def sortedSquares(nums): 8 | nums = [i**2 for i in nums] 9 | return sorted(nums) 10 | 11 | 12 | # Another way to solve the problem 13 | def sorted_squares(nums): 14 | ans = [0] * len(nums) 15 | l, r = 0, len(nums)-1 16 | while l <= r: 17 | low, high = abs(nums[l]), abs(nums[r]) 18 | if low > high: 19 | ans[r - l] = low * low 20 | l += 1 21 | else: 22 | ans[r - l] = high * high 23 | r -= 1 24 | return ans 25 | 26 | 27 | def main(): 28 | test_cases = [ 29 | [-4, -1, 0, 3, 10], 30 | [-7, -3, 2, 3, 11], 31 | [-3, -1, 4, 7, 12] 32 | ] 33 | for array in test_cases: 34 | print(sortedSquares(array)) 35 | print(sorted_squares(array)) 36 | 37 | 38 | if __name__ == '__main__': 39 | main() 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | Repo for storing my progress in solving [**LeetCode**](https://leetcode.com/problemset/all/) programming problems. 4 | 5 | ![leetcode-banner](/images/leetcode.png) 6 | 7 | ## Quickstart 8 | 9 | Install the pre-commit hooks for formatting code: 10 | 11 | ```bash 12 | pre-commit install 13 | ``` 14 | 15 | Install packages to the .venv: 16 | 17 | ```bash 18 | sudo pip install -r requirements.txt 19 | ``` 20 | 21 | Install the package in "editable" mode, which means changes to the Python files will be immediately available without needing to reinstall the package. 22 | 23 | ```bash 24 | pip install -e . 25 | ``` 26 | 27 | 30 | 31 | ## Easy problems 32 | 33 | | Programming Solution | LeetCode link | 34 | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | 35 | | 01. [Two Sum](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/01-Two-Sum-EASY.py) | [two-sum](https://leetcode.com/problems/two-sum/) | 36 | | 09. [Padindrome Number](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/09-Palindrome-Number-EASY.py) | [palindrome-number](https://leetcode.com/problems/palindrome-number/) | 37 | | 13. [Roman to Integer](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/13-Roman-to-Integer-EASY.py) | [roman-to-integer](https://leetcode.com/problems/roman-to-integer/) | 38 | | 14. [Longest Common Prefix](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/14-Most-Common-Prefix-EASY.py) | [longest-common-prefix](https://leetcode.com/problems/longest-common-prefix/) | 39 | | 20. [Valid Parentheses](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/20-Valid-Parenthesis-EASY.py) | [valid-parentheses](https://leetcode.com/problems/valid-parentheses/) | 40 | | 26. [Remove Duplicates From Sorted Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/26-Remove-Duplicates-from-Sorted-Array-EASY.py) | [remove-duplicates-from-sorted-array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | 41 | | 27. [Remove Element](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/27-Remove-Element-EASY.py) | [remove-element](https://leetcode.com/problems/remove-element/) | 42 | | 28. [Implement strStr()]() | [implement-strStr()](https://leetcode.com/problems/implement-strstr/) | 43 | | 35. [Search Insert Position](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/35-Search-Insert-Position-EASY.py) | [search-insert-position](https://leetcode.com/problems/search-insert-position/) | 44 | | 53. [Maximum Subarray](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/53-Maximum-Subarray.EASY.py) | [maximum-subarray](https://leetcode.com/problems/maximum-subarray/) | 45 | | 58. [Lenght of Last Word](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/58-Lenght-of-Last-Word-EASY.py) | [lenght-of-last-word](https://leetcode.com/problems/length-of-last-word/) | 46 | | 66. [Plus One](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/66-Plus-One-EASY.py) | [plus-one](https://leetcode.com/problems/plus-one/) | 47 | | 67. [Add Binary](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/67-Add-Binary-EASY.py) | [add-binary](https://leetcode.com/problems/add-binary/) | 48 | | 69. [Sqrt(x)]() | [sqrt(x)](https://leetcode.com/problems/sqrtx/) | 49 | | 70. [Climbing Stairs](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/70-Climbing-Stairs-EASY.py) | [climbing-stairs](https://leetcode.com/problems/climbing-stairs/) | 50 | | 118. [Pascals Triangle](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/118-Pascals-Triangle-EASY.py) | [pascals-triangle](https://leetcode.com/problems/pascals-triangle/) | 51 | | 119. [Pascals Triangle II](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/119-Pascals-Triangle-II-EASY.py) | [pascals-triangle-II](https://leetcode.com/problems/pascals-triangle-ii/) | 52 | | 121. [Best Time to Buy and Sell Stock](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/121-Best-Time-to-Buy-and-Sell-Stock-EASY.py) | [best-time-to-buy-and-sell-stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | 53 | | 125. [Valid Palindrome](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/125-Valid-Palindrome-EASY.py) | [valid-palindrome](https://leetcode.com/problems/valid-palindrome/) | 54 | | 136. [Single Number](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/136-Single-Number-EASY.py) | [single-number](https://leetcode.com/problems/single-number/) | 55 | | 168. [Excel Sheet Column Title](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/168-Excel-Sheet-Column-Title-EASY.py) | [excel-sheet-column-title](https://leetcode.com/problems/excel-sheet-column-title/) | 56 | | 169. [Majority Element](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/169-Majority-Element-EASY.py) | [majority-element](https://leetcode.com/problems/majority-element/) | 57 | | 171. [Excel Sheet Column Number](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/171-Excel-Sheet-Column-Number-EASY.py) | [excel-sheet-column-number](https://leetcode.com/problems/excel-sheet-column-number/) | 58 | | 202. [Happy Number](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/202-Happy-Number-EASY.py) | [happy-number](https://leetcode.com/problems/happy-number/) | 59 | | 217. [Contains Duplicate](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/217-Contains-Duplicates-EASY.py) | [contains-duplicate](https://leetcode.com/problems/contains-duplicate/) | 60 | | 228. [Summary Ranges](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/228-Summary-Ranges-EASY.py) | [summary-ranges](https://leetcode.com/problems/summary-ranges/) | 61 | | 258. [Add Digits](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/258-Add-Digits-EASY.py) | [add-digits](https://leetcode.com/problems/add-digits/) | 62 | | 268. [Missing Number](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/268-Missing-Number-EASY.py) | [missing-number](https://leetcode.com/problems/missing-number/) | 63 | | 303. [Range Sum Query](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/303-Range-Sum-Query-EASY.py) | [range-sum-query](https://leetcode.com/problems/range-sum-query-immutable/) | 64 | | 338. [Counting Bits](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/338-Counting-Bits-EASY.py) | [counting-bits](https://leetcode.com/problems/counting-bits/) | 65 | | 448. [Find All Numbers Disappeared in Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/448-Find-All-Numbers-Disappeared-Array-EASY.py) | [find-all-numbers-disappeared-in-array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | 66 | | 704. [Binary Search](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/704-Binary-Search-EASY.py) | [binary-search](https://leetcode.com/problems/binary-search/) | 67 | | 744. [Find Smallest Letter Greater Than Target](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/744-Find-Smallest-Letter-Greater-Than-Target-EASY.py) | [find-smallest-letter-greater-than-target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) | 68 | | 844. [Backspace String Compare](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/844-Backspace-String-Compare-EASY.py) | [backspace-string-compare](https://leetcode.com/problems/backspace-string-compare/) | 69 | | 852. [Peak Index in a Mountain Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/852-Peak-Index-in-a-Mountain-Array-EASY.py) | [peak-index-in-a-mountain-array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | 70 | | 977. [Squares of a Sorted Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/977-Squares-of-a-Sorted-Array-EASY.py) | [squares-of-a-sorted-array](https://leetcode.com/problems/squares-of-a-sorted-array/) | 71 | | 1886. [Determine Whether Matrix Can Be Obtained By Rotation](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/1886-Determine-Whether-Matrix-Can-Be-Obtained-By-Rotation-EASY.py) | [determine-whether-matrix-can-be-obtained-by-rotation](https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/) | 72 | | 1929. [Concatenation of Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/1929-Concatenation-of-Array-EASY.py) | [concatenation-of-array](https://leetcode.com/problems/concatenation-of-array/) | 73 | | 2022. [Convert 1D Array Into 2D Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/2022-Convert-1D-Array-Into-2D-Array-EASY.py) | [convert-1d-array-into-2d-array](https://leetcode.com/problems/convert-1d-array-into-2d-array/) | 74 | 75 |
76 | 77 | ## Medium problems 78 | 79 | | Programming Solution | LeetCode link | 80 | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | 81 | | 02. [Add Two Numbers](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/02-Add-Two-Numbers-MEDIUM.py) | [add-two-numbers](https://leetcode.com/problems/add-two-numbers/) | 82 | | 03. [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [longest-substring-without-repeating-characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | 83 | | 07. [Reverse Integer](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/7-Reverse-Integer-MEDIUM.py) | [reverse-integer](https://leetcode.com/problems/reverse-integer/) | 84 | | 48. [Rotate Image](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/48-Rotate-Image-MEDIUM.py) | [rotate-image](https://leetcode.com/problems/rotate-image/) | 85 | | 54. [Spiral Matrix](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/54-Spiral-Matrix-MEDIUM.py) | [spiral-matrix](https://leetcode.com/problems/spiral-matrix/) | 86 | | 73. [Set Matrix Zeroes](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/73-Set-Matrix-Zeroes-MEDIUM.py) | [set-matrix-zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | 87 | | 128. [Longest Consecutive Sequence](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/128-Longest-Consecutive-Sequence-MEDIUM.py) | [longest-consecutive-sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | 88 | | 238. [Product of Array Except Self](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/238-Product-of-Array-Except-Self-MEDIUM.py) | [product-of-array-except-self](https://leetcode.com/problems/product-of-array-except-self/) | 89 | | 287. [Find the Duplicate Number](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/287-Find-the-Duplicate-Number-MEDIUM.py) | [find-the-duplicate-number](https://leetcode.com/problems/find-the-duplicate-number/) | 90 | | 378. [Kth Smallest Element in a Sorted Matrix](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/378-Kth-Smallest-Element-in-Sorted-Matrix-MEDIUM.py) | [kth-smallest-element-in-a-sorted-matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | 91 | | 442. [Find All Duplicates in an Array](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/442-Find-All-Duplicates-in-an-Array-MEDIUM.py) | [find-all-duplicates-in-an-array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | 92 | | 1476. [Subrectangle Queries](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/1476-Subrectangle-Queries-MEDIUM.py) | [subrectangle-queries](https://leetcode.com/problems/subrectangle-queries/) | 93 | 94 |
95 | 96 | ## Hard problems 97 | 98 | | Programming Solution | LeetCode link | 99 | | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | 100 | | 410. [Split Array Largest Sum](https://github.com/murilogustineli/LeetCode/blob/main/Programming-Solutions/410-Split-Array-Largest-Sum-HARD.py) | [split-array-largest-sum](https://leetcode.com/problems/split-array-largest-sum/) | 101 | 102 | 105 | -------------------------------------------------------------------------------- /images/leetcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murilogustineli/leetcode/143fce1c5d2b701f3fd5eb847c71a8677b571db0/images/leetcode.png -------------------------------------------------------------------------------- /leetcode_exercises.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# LeetCode Exercises" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "data": { 17 | "text/plain": [ 18 | "['apple', 'app', 'peach', 'plea']" 19 | ] 20 | }, 21 | "execution_count": 1, 22 | "metadata": {}, 23 | "output_type": "execute_result" 24 | } 25 | ], 26 | "source": [ 27 | "def can_construct(word, s):\n", 28 | " \"\"\"Check if the word can be constructed from the string while keeping the order.\"\"\"\n", 29 | " it = iter(s)\n", 30 | " return all(char in it for char in word)\n", 31 | "\n", 32 | "\n", 33 | "def filter_constructible_words(word_list, s):\n", 34 | " \"\"\"Return the list of words that can be constructed from the string s.\"\"\"\n", 35 | " return [word for word in word_list if can_construct(word, s)]\n", 36 | "\n", 37 | "\n", 38 | "# Example usage\n", 39 | "word_list = [\"apple\", \"app\", \"peach\", \"plea\", \"leap\", \"banana\"]\n", 40 | "s = \"applppleaechbn\"\n", 41 | "\n", 42 | "# This will return ['apple', 'app', 'plea', 'leap']\n", 43 | "result = filter_constructible_words(word_list, s)\n", 44 | "result" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 2, 50 | "metadata": {}, 51 | "outputs": [ 52 | { 53 | "data": { 54 | "text/plain": [ 55 | "'banana'" 56 | ] 57 | }, 58 | "execution_count": 2, 59 | "metadata": {}, 60 | "output_type": "execute_result" 61 | } 62 | ], 63 | "source": [ 64 | "def can_construct(word, s):\n", 65 | " for i in s:\n", 66 | " if i in word:\n", 67 | " return True\n", 68 | "\n", 69 | "\n", 70 | "def filter(word_list, s):\n", 71 | " words = []\n", 72 | " for word in word_list:\n", 73 | " if can_construct(word, s):\n", 74 | " words.append(word)\n", 75 | " return word\n", 76 | "\n", 77 | "\n", 78 | "words = filter(word_list, s)\n", 79 | "words" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 3, 85 | "metadata": {}, 86 | "outputs": [ 87 | { 88 | "name": "stdout", 89 | "output_type": "stream", 90 | "text": [ 91 | "['this', 'is', 'a', 'test']\n" 92 | ] 93 | } 94 | ], 95 | "source": [ 96 | "def word_break(s, lexicon):\n", 97 | " n = len(s)\n", 98 | " dp = [0] * (n + 1) # Probability of best segmentation\n", 99 | " prev = [-1] * (n + 1) # Backtracking for reconstruction\n", 100 | " dp[0] = 1 # Base case: empty string has a segmentation with probability 1\n", 101 | "\n", 102 | " def is_valid_word(word):\n", 103 | " return word in lexicon\n", 104 | "\n", 105 | " def get_probability(words):\n", 106 | " # Placeholder: Should return the language model's probability of the sequence of words\n", 107 | " return 1.0\n", 108 | "\n", 109 | " # Fill dp table\n", 110 | " for i in range(1, n + 1):\n", 111 | " for j in range(i):\n", 112 | " word = s[j:i]\n", 113 | " if is_valid_word(word) and dp[j] > 0:\n", 114 | " prob = dp[j] * get_probability(word)\n", 115 | " if prob > dp[i]:\n", 116 | " dp[i] = prob\n", 117 | " prev[i] = j\n", 118 | "\n", 119 | " # Reconstruct the best segmentation\n", 120 | " if dp[n] == 0:\n", 121 | " return None # No valid segmentation\n", 122 | " words = []\n", 123 | " i = n\n", 124 | " while i > 0:\n", 125 | " words.append(s[prev[i] : i])\n", 126 | " i = prev[i]\n", 127 | " words.reverse()\n", 128 | "\n", 129 | " return words\n", 130 | "\n", 131 | "\n", 132 | "# Example usage\n", 133 | "lexicon = {\"a\", \"is\", \"test\", \"thesis\", \"this\"}\n", 134 | "sequence = \"thisisatest\"\n", 135 | "result = word_break(sequence, lexicon)\n", 136 | "print(result)" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 4, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "def threeSum(nums: list[int]) -> list[list[int]]:\n", 146 | " output = []\n", 147 | " distinct = []\n", 148 | " nums.sort()\n", 149 | " i, j, k = 0, 1, 2\n", 150 | " for i in range(0, len(nums) - 2):\n", 151 | " for j in range(1, len(nums) - 1):\n", 152 | " for k in range(2, len(nums)):\n", 153 | " list_nums = [nums[i], nums[j], nums[k]]\n", 154 | " sum_nums = sum(list_nums)\n", 155 | " if i != j and i != k and j != k and sum_nums == 0:\n", 156 | " if set(list_nums) not in distinct:\n", 157 | " distinct.append(set(list_nums))\n", 158 | " output.append(list_nums)\n", 159 | " return output" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": 5, 165 | "metadata": {}, 166 | "outputs": [ 167 | { 168 | "data": { 169 | "text/plain": [ 170 | "[[-1, -1, 2], [-1, 0, 1]]" 171 | ] 172 | }, 173 | "execution_count": 5, 174 | "metadata": {}, 175 | "output_type": "execute_result" 176 | } 177 | ], 178 | "source": [ 179 | "nums = [-1, 0, 1, 2, -1, -4]\n", 180 | "threeSum(nums=nums)" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": 6, 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [ 189 | "def isPalindrome(s: str) -> bool:\n", 190 | " pal = \"\"\n", 191 | " for char in s.lower():\n", 192 | " if char.isalnum():\n", 193 | " pal += char\n", 194 | " for i in range(len(pal)):\n", 195 | " if pal[i] == pal[-i - 1]:\n", 196 | " continue\n", 197 | " else:\n", 198 | " return False\n", 199 | " return True" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": 7, 205 | "metadata": {}, 206 | "outputs": [ 207 | { 208 | "name": "stdout", 209 | "output_type": "stream", 210 | "text": [ 211 | "True\n" 212 | ] 213 | } 214 | ], 215 | "source": [ 216 | "s = \"A man, a plan, a canal: Panama\"\n", 217 | "ans = isPalindrome(s)\n", 218 | "print(ans)" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": 8, 224 | "metadata": {}, 225 | "outputs": [], 226 | "source": [ 227 | "def binary_search(arr, target):\n", 228 | " assert target <= len(arr) - 1\n", 229 | " low, high = 0, len(arr) - 1\n", 230 | " mid = 0\n", 231 | "\n", 232 | " while low <= high:\n", 233 | " mid = (low + high) // 2\n", 234 | " if arr[mid] < target:\n", 235 | " low = mid + 1\n", 236 | " elif arr[mid] > target:\n", 237 | " high = mid - 1\n", 238 | " else:\n", 239 | " return mid\n", 240 | " return -1" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": 9, 246 | "metadata": {}, 247 | "outputs": [ 248 | { 249 | "name": "stdout", 250 | "output_type": "stream", 251 | "text": [ 252 | "[0, 1, 2, 4, 5, 6, 7, 8, 9, 11, 14, 15, 17, 20]\n", 253 | "-1\n" 254 | ] 255 | } 256 | ], 257 | "source": [ 258 | "arr = [0, 1, 2, 4, 5, 6, 7, 8, 9, 11, 14, 15, 17, 20]\n", 259 | "ans = binary_search(arr, target=3)\n", 260 | "print(arr)\n", 261 | "print(ans)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": 10, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "def calPoints(operations: list[str]) -> int:\n", 271 | " output = []\n", 272 | " for op in range(len(operations)):\n", 273 | " try:\n", 274 | " if type(int(operations[op])):\n", 275 | " new_score = int(operations[op])\n", 276 | " except:\n", 277 | " pass\n", 278 | " if operations[op] == \"D\":\n", 279 | " new_score = output[-1] * 2\n", 280 | " if operations[op] == \"C\":\n", 281 | " output.pop()\n", 282 | " continue\n", 283 | " if operations[op] == \"+\":\n", 284 | " new_score = output[-1] + output[-2]\n", 285 | " output.append(new_score)\n", 286 | " return sum(output)" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 11, 292 | "metadata": {}, 293 | "outputs": [ 294 | { 295 | "data": { 296 | "text/plain": [ 297 | "30" 298 | ] 299 | }, 300 | "execution_count": 11, 301 | "metadata": {}, 302 | "output_type": "execute_result" 303 | } 304 | ], 305 | "source": [ 306 | "ops = [\"5\", \"2\", \"C\", \"D\", \"+\"]\n", 307 | "calPoints(ops)" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": 12, 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "def isValid(s: str) -> bool:\n", 317 | " stack = []\n", 318 | " mapping = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}\n", 319 | " for i in range(len(s)):\n", 320 | " if s[i] in mapping:\n", 321 | " stack.append(s[i])\n", 322 | " else:\n", 323 | " if len(stack) and mapping[stack[-1]] == s[i]:\n", 324 | " stack.pop()\n", 325 | " else:\n", 326 | " return False\n", 327 | " return stack == []" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 13, 333 | "metadata": {}, 334 | "outputs": [ 335 | { 336 | "data": { 337 | "text/plain": [ 338 | "False" 339 | ] 340 | }, 341 | "execution_count": 13, 342 | "metadata": {}, 343 | "output_type": "execute_result" 344 | } 345 | ], 346 | "source": [ 347 | "s = \"]\"\n", 348 | "isValid(s)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 14, 354 | "metadata": {}, 355 | "outputs": [], 356 | "source": [ 357 | "class MinStack:\n", 358 | " def __init__(self):\n", 359 | " self.arr = []\n", 360 | " self.min_stack = []\n", 361 | "\n", 362 | " def push(self, val: int) -> None:\n", 363 | " self.arr.append(val)\n", 364 | " if not self.min_stack or val <= self.min_stack[-1]:\n", 365 | " self.min_stack.append(val)\n", 366 | "\n", 367 | " def pop(self) -> None:\n", 368 | " if self.arr:\n", 369 | " if self.arr[-1] == self.min_stack[-1]:\n", 370 | " self.min_stack.pop()\n", 371 | " self.arr.pop()\n", 372 | "\n", 373 | " def top(self) -> int:\n", 374 | " if self.arr:\n", 375 | " return self.arr[-1]\n", 376 | " return None\n", 377 | "\n", 378 | " def getMin(self) -> int:\n", 379 | " if self.min_stack:\n", 380 | " return self.min_stack[-1]\n", 381 | " return None" 382 | ] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "execution_count": 15, 387 | "metadata": {}, 388 | "outputs": [ 389 | { 390 | "data": { 391 | "text/plain": [ 392 | "[0]" 393 | ] 394 | }, 395 | "execution_count": 15, 396 | "metadata": {}, 397 | "output_type": "execute_result" 398 | } 399 | ], 400 | "source": [ 401 | "minstack = MinStack()\n", 402 | "minstack.push(0)\n", 403 | "minstack.arr" 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": 16, 409 | "metadata": {}, 410 | "outputs": [ 411 | { 412 | "name": "stdout", 413 | "output_type": "stream", 414 | "text": [ 415 | "4\n" 416 | ] 417 | } 418 | ], 419 | "source": [ 420 | "def math_challenge(num1, num2):\n", 421 | " while num2 != 0:\n", 422 | " num1, num2 = num2, num1 % num2\n", 423 | " return num1\n", 424 | "\n", 425 | "\n", 426 | "# Example usage\n", 427 | "num1 = 12\n", 428 | "num2 = 16\n", 429 | "print(math_challenge(num1, num2))" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": 17, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "def ArrayChallenge(arr):\n", 439 | " sort_arr = sorted(arr)\n", 440 | " max1, max2 = sort_arr[-1], sort_arr[-2]\n", 441 | " prod = max1 * max2\n", 442 | " sum_arr = sum(arr) * 2\n", 443 | " if prod > sum_arr:\n", 444 | " return \"true\"\n", 445 | " return \"false\"" 446 | ] 447 | }, 448 | { 449 | "cell_type": "code", 450 | "execution_count": 18, 451 | "metadata": {}, 452 | "outputs": [], 453 | "source": [ 454 | "def ArrayChallenge(arr):\n", 455 | " # Initialize the two largest numbers\n", 456 | " if len(arr) < 2:\n", 457 | " return \"false\" # Not enough elements to form a pair\n", 458 | " max1 = float(\"-inf\")\n", 459 | " max2 = float(\"-inf\")\n", 460 | " # Initialize the sum\n", 461 | " total_sum = 0\n", 462 | " for num in arr:\n", 463 | " # Update the total sum\n", 464 | " total_sum += num\n", 465 | " # Update the two largest numbers\n", 466 | " if num > max1:\n", 467 | " max2 = max1\n", 468 | " max1 = num\n", 469 | " elif num > max2:\n", 470 | " max2 = num\n", 471 | " print(max1, max2)\n", 472 | " # Calculate the product of the two largest numbers\n", 473 | " product = max1 * max2\n", 474 | " # Calculate double the total sum\n", 475 | " double_sum = 2 * total_sum\n", 476 | " # Compare the product with the doubled sum\n", 477 | " if product > double_sum:\n", 478 | " return \"true\"\n", 479 | " return \"false\"" 480 | ] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": 19, 485 | "metadata": {}, 486 | "outputs": [ 487 | { 488 | "name": "stdout", 489 | "output_type": "stream", 490 | "text": [ 491 | "2 -inf\n", 492 | "5 2\n", 493 | "6 5\n", 494 | "6 5\n", 495 | "26 6\n", 496 | "26 6\n", 497 | "26 6\n", 498 | "26 6\n", 499 | "26 6\n", 500 | "26 6\n", 501 | "true\n" 502 | ] 503 | } 504 | ], 505 | "source": [ 506 | "# Example usage\n", 507 | "arr = [2, 5, 6, -6, 26, 2, 3, 6, 5, 3]\n", 508 | "print(ArrayChallenge(arr))" 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": 3, 514 | "metadata": {}, 515 | "outputs": [ 516 | { 517 | "name": "stdout", 518 | "output_type": "stream", 519 | "text": [ 520 | "http://www.example.com\n" 521 | ] 522 | } 523 | ], 524 | "source": [ 525 | "import requests\n", 526 | "\n", 527 | "logfile1 = \"https://public.karat.io/content/urls2.txt\"\n", 528 | "logfile2 = \"https://public.karat.io/content/q015/single_url.txt\"\n", 529 | "\n", 530 | "\n", 531 | "def get_logfile(input_file):\n", 532 | " response = requests.get(input_file)\n", 533 | " return response.text\n", 534 | "\n", 535 | "\n", 536 | "def count_values(log_file):\n", 537 | " results = {}\n", 538 | " for log in log_file:\n", 539 | " if log not in results:\n", 540 | " results[log] = 1\n", 541 | " else:\n", 542 | " results[log] += 1\n", 543 | " return results\n", 544 | "\n", 545 | "\n", 546 | "output = get_logfile(logfile2).split(\"\\n\")\n", 547 | "results = count_values(output)\n", 548 | "max_output = max(results, key=results.get)\n", 549 | "print(max_output)" 550 | ] 551 | }, 552 | { 553 | "cell_type": "code", 554 | "execution_count": null, 555 | "metadata": {}, 556 | "outputs": [], 557 | "source": [] 558 | }, 559 | { 560 | "cell_type": "code", 561 | "execution_count": null, 562 | "metadata": {}, 563 | "outputs": [], 564 | "source": [] 565 | } 566 | ], 567 | "metadata": { 568 | "kernelspec": { 569 | "display_name": ".venv", 570 | "language": "python", 571 | "name": "python3" 572 | }, 573 | "language_info": { 574 | "codemirror_mode": { 575 | "name": "ipython", 576 | "version": 3 577 | }, 578 | "file_extension": ".py", 579 | "mimetype": "text/x-python", 580 | "name": "python", 581 | "nbconvert_exporter": "python", 582 | "pygments_lexer": "ipython3", 583 | "version": "3.11.6" 584 | } 585 | }, 586 | "nbformat": 4, 587 | "nbformat_minor": 2 588 | } 589 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "leetcode" 3 | version = "0.0.1" 4 | authors = [{ name = "Murilo Gustineli", email = "murilogustineli@gmail.com" }] 5 | description = "LeetCode helper package" 6 | readme = "README.md" 7 | requires-python = ">=3.8" 8 | 9 | [project.urls] 10 | Homepage = "https://github.com/murilogustineli/leetcode" 11 | Issues = "https://github.com/murilogustineli/leetcode/issues" 12 | 13 | [build-system] 14 | requires = ["setuptools>=61.0"] 15 | build-backend = "setuptools.build_meta" 16 | 17 | [tool.setuptools.dynamic] 18 | dependencies = { file = "requirements.txt" } 19 | 20 | [tool.setuptools.packages.find] 21 | where = ["."] 22 | include = ["leetcode"] 23 | namespaces = false 24 | --------------------------------------------------------------------------------