├── 0001-Two-Sum.py ├── 0002-Add-Two-Numbers.py ├── 0003-Longest-Substring-Without-Repeating-Characters.py ├── 0004-Median-of-Two-Sorted-Arrays.py ├── 0005-Longest-Palindromic-Substring.py ├── 0006-ZigZag-Conversion.py ├── 0009-Palindrome-Number.py ├── 0011-Container-With-Most-Water.py ├── 0012-Integer-to-Roman.py ├── 0013-Roman-to-Integer.py ├── 0014-Longest-Common-Prefix.py ├── 0017-Letter-Combinations-of-a-Phone-Number.py ├── 0019-Remove-Nth-Node-From-End-of-List.py ├── 0020-Valid-Parentheses.py ├── 0021-Merge-Two-Sorted-Lists.py ├── 0022-Generate-Parentheses.py ├── 0023-Merge-k-Sorted-Lists.py ├── 0024-Swap-Nodes-in-Pairs.py ├── 0026-Remove-Duplicates-from-Sorted-Array.py ├── 0027-Remove-Element.py ├── 0029-Divide-Two-Integers.py ├── 0031-Next-Permutation.py ├── 0033-Search-in-Rotated-Sorted-Array.py ├── 0034-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py ├── 0035-Search-Insert-Position.py ├── 0038-Count-and-Say.py ├── 0039-Combination-Sum.py ├── 0046-Permutations.py ├── 0048-Rotate-Image.py ├── 0049-Group-Anagrams.py ├── 0053-Maximum-Subarray.py ├── 0055-Jump-Game.py ├── 0056-Merge-Intervals.py ├── 0066-Plus-One.py ├── 0067-Add-Binary.py ├── 0069-Sqrt(x).py ├── 0070-Climbing-Stairs.py ├── 0072-Edit-Distance.py ├── 0074-Search-a-2D-Matrix.py ├── 0075-Sort-Colors.py ├── 0078-Subsets.py ├── 0079-Word-Search.py ├── 0088-Merge-Sorted-Array.py ├── 0091-Decode-Ways.py ├── 0094-Binary-Tree-Inorder-Traversal.py ├── 0100-Same-Tree.py ├── 0102-Binary-Tree-Level-Order-Traversal.py ├── 0107-Binary-Tree-Level-Order-Traversal-II.py ├── 0118-Pascal-Triangle.py ├── 0121-Best-Time-To-Buy-and-Sell-Stock.py ├── 0122-Best-Time-To-Buy-and-Sell-Stock-II.py ├── 0125-Valid-Palindrome.py ├── 0131-Palindrome-Partitioning.py ├── 0136-Single-Number.py ├── 0138-Copy-List-with-Random-Pointer.py ├── 0141-Linked-List-Cycle.py ├── 0143-Reorder-List.py ├── 0144-Binary-Tree-Preorder-Traversal.py ├── 0145-Binary-Tree-Postorder-Traversal.py ├── 0151-Reverse-Words-in-a-String.py ├── 0152-Maximum-Product-Subarray.py ├── 0153-Find-Minimum-in-Rotated-Sorted-Array.py ├── 0155-Min-Stack.py ├── 0160-Intersection-of-Two-Linked-List.py ├── 0169-Majority-Element.py ├── 0172-Factorial-Trailing-Zeroes.py ├── 0189-Rotate-Array.py ├── 0191-Number-of-1-Bits.py ├── 0198-House-Robber.py ├── 0202-Happy-Number.py ├── 0203-Remove-Linked-List-Elements.py ├── 0204-Count-Primes.py ├── 0205-Isomorphic-Strings.py ├── 0206-Reverse-Linked-List.py ├── 0208-Implement-Trie-(Prefix-Tree).py ├── 0217-Contains-Duplicate.py ├── 0219-Contains-Duplicate-II.py ├── 0225-Implement-Stack-using-Queue.py ├── 0226-Invert-Binary-Tree.py ├── 0227-Basic-Calculator-II.py ├── 0230-Kth-Smallest-Element-in-a-BST.py ├── 0231-Power-of-Two.py ├── 0232-Implement-Queue-using-Stacks.py ├── 0234-Palindrome-Linked-List.py ├── 0237-Delete-Node-in-a-Linked-List.py ├── 0238-Product-of-Array-Except-Self.py ├── 0242-Valid-Anagram.py ├── 0258-Add-Digits.py ├── 0268-Missing-Number.py ├── 0278-First-Bad-Version.py ├── 0283-Move-Zeroes.py ├── 0287-Find-the-Duplicate-Number.py ├── 0292-Nim-Game.py ├── 0322-Coin-Change.py ├── 0328-Odd-Even-Linked-List.py ├── 0344-Reverse-String.py ├── 0345-Reverse-Vowels-of-a-String.py ├── 0347-Top-K-Frequent-Elements.py ├── 0349-Intersection-Of-Two-Arrays.py ├── 0350-Intersection-of-Two-Arrays-II.py ├── 0367-Valid-Perfect-Square.py ├── 0371-Sum-of-Two-Integers.py ├── 0373-Find-K-Pairs-with-Smallest-Sums.py ├── 0383-Ransom-Note.py ├── 0385-Mini-Parser.py ├── 0387-First-Unique-Characcter-in-a-String.py ├── 0392-Is-Subsequence.py ├── 0402-Remove-K-Digits.py ├── 0412-Fizz-Buzz.py ├── 0443-String-Compression.py ├── 0448-Find-All-Numbers-Disappeared-in-an-Array.py ├── 0451-Sort-Characters-By-Frequency.py ├── 0463-Island-Perimeter.py ├── 0476-Number-Complement.py ├── 0496-Next-Greater-Element-I.py ├── 0500-Keyboard-Row.py ├── 0503-Next-Greater-Element-II.py ├── 0525-Contiguous-Array.py ├── 0540-Single-Element-in-a-Sorted-Array.py ├── 0543-Diameter-of-Binary-Tree.py ├── 0557-Reverse-Words-in-a-String-III.py ├── 0560-Subarray-Sum-Equals-K.py ├── 0605-Can-Place-Flowers.py ├── 0617-Merge-Two-Binary-Trees.py ├── 0657-Robot-Return-to-Origin.py ├── 0665-Non-decreasing-Array.py ├── 0674-Longest-Continuous-Increasing-Subsequence.py ├── 0678-Valid-Parenthesis-String.py ├── 0692-Top-K-Frequent-Words.py ├── 0700-Search-in-a-Binary-Search-Tree.py ├── 0704-Binary-Search.py ├── 0705-Design-HashSet.py ├── 0707-Design-Linked_list.py ├── 0709-To-Lower-Case.py ├── 0724- Find-Pivot-Index.py ├── 0733-Flood-Fill.py ├── 0739-Daily-Temperatures.py ├── 0771-Jewels-and-Stones.py ├── 0844-Backspace-String-Compare.py ├── 0849-Maximize-Distance-to-Closest-Person.py ├── 0852-Peak-Index-In-A-Mountain-Array.py ├── 0856-Score-of-Parentheses.py ├── 0872-Leaf-Similar-Trees.py ├── 0876-Middle-of-the-Linked-List.py ├── 0881-Boats-to-Save-People.py ├── 0890-Find-and-Replace-Pattern.py ├── 0929-Unique-Email-Addresses.py ├── 0941-Valid-Mountain-Array.py ├── 0961-N-Repeated-Element-in-Size-2N-Array.py ├── 0981-Time-Based-Key-Value-Store.py ├── 0993-Cousins-in-Binary-Tree.py ├── 0997-Find-the-Town-Judge.py ├── 1014-Best-Sightseeing-Pair.py ├── 1021-Remove-Outermost-Parentheses.py ├── 1029-Two-City-Scheduling.py ├── 1046-Last-Stone-Weight.py ├── 1047-Remove-All-Adjacent-Duplicates-In-String.py ├── 1051-Height-Checker.py ├── 1108-Defanging-an-IP-Address.py ├── 1137-N-th-Tribonacci-Number.py ├── 1160-Find-Words-That-Can-Be-Formed-by-Characters.py ├── 1189-Maximum-Number-of-Ballons.py ├── 1207-Unique-Number-of-Occurences.py ├── 1281-Subtract-the-Product-and-Sum-of-Digits-of-an-integer.py ├── 1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers.py ├── 1356-Sort-Integers-by-The-Number-of-1-Bits.py ├── 1360-Number-of-Days-Between-Two-Days.py ├── 1362-Closest-Divisors.py ├── 1366-Rank-Teams-by-Votes.py ├── 1370-Increasing-Decreasing-String.py ├── 1374-Generate-a-String-With-Characters-That-Have-Odd-Counts.py ├── 1380-Lucky-Numbers-in-a-Matrix.py ├── 1399-Count-Largest-Group.py ├── 1400-Construct-K-Palindrome-Strings.py ├── 1401-Circle-and-Rectangle-Overlapping.py ├── 1426-Counting-Elements.py ├── 1427-Perform-String-Shifts.py ├── 1431-Kids-With-the-Greatest-Number-of-Candies.py ├── 1432-Max-Difference-You-Can-Get-From-Changing-an-Integer.py ├── 1433-Check-If-a-String-Can-Break-Another-String.py ├── 1480-Running-Sum-of-1d-Array.py ├── 1991-Find-the-Middle-Index-in-Array.py └── README.md /0001-Two-Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | Example: 7 | Given nums = [2, 7, 11, 15], target = 9, 8 | 9 | Because nums[0] + nums[1] = 2 + 7 = 9, 10 | return [0, 1]. 11 | ''' 12 | 13 | from typing import List 14 | 15 | # Using Hash Tables 16 | 17 | class Solution: 18 | def twoSum(self, nums: List[int], target: int) -> List[int]: 19 | dict = {} 20 | for i in range(len(nums)): 21 | temp = target-nums[i] 22 | if temp in dict: 23 | return [dict[temp], i] 24 | dict.update({nums[i] : i}) 25 | 26 | # Using Hash Tables (New) 27 | 28 | class Solution: 29 | def twoSum(self, nums: List[int], target: int) -> List[int]: 30 | d = {} 31 | for index, num in enumerate(nums): 32 | if target - num in d.keys(): 33 | return [d[target - num], index] 34 | else: 35 | d[num] = index 36 | 37 | # Check Custom Input 38 | 39 | s = Solution() 40 | answer = s.twoSum([3,2,1,5], 8) # [0,3] 41 | print(answer) -------------------------------------------------------------------------------- /0002-Add-Two-Numbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 3 | 4 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 5 | 6 | Example: 7 | 8 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 9 | Output: 7 -> 0 -> 8 10 | Explanation: 342 + 465 = 807. 11 | ''' 12 | 13 | # Definition for singly-linked list. 14 | 15 | class ListNode: 16 | def __init__(self, val=0, next=None): 17 | self.val = val 18 | self.next = next 19 | 20 | class Solution: 21 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 22 | cur = res = ListNode() 23 | carry = 0 24 | while l1 or l2 or carry: 25 | if l1: 26 | carry += l1.val 27 | l1 = l1.next 28 | if l2: 29 | carry += l2.val 30 | l2 = l2.next 31 | carry, value = carry // 10, carry % 10 32 | cur.next = ListNode(value) 33 | cur = cur.next 34 | return res.next 35 | 36 | # Check Custom Input 37 | 38 | s = Solution() 39 | 40 | l1_node1 = ListNode(2) 41 | l1_node2 = ListNode(4) 42 | l1_node3 = ListNode(3) 43 | 44 | l1_node1.next = l1_node2 45 | l1_node2.next = l1_node3 46 | 47 | l2_node1 = ListNode(5) 48 | l2_node2 = ListNode(6) 49 | l2_node3 = ListNode(4) 50 | 51 | l2_node1.next = l2_node2 52 | l2_node2.next = l2_node3 53 | 54 | answer = s.addTwoNumbers(l1_node1, l2_node1) 55 | 56 | while answer: 57 | print(answer.val) 58 | answer = answer.next -------------------------------------------------------------------------------- /0003-Longest-Substring-Without-Repeating-Characters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the length of the longest substring without repeating characters. 3 | 4 | Example 1: 5 | 6 | Input: "abcabcbb" 7 | Output: 3 8 | Explanation: The answer is "abc", with the length of 3. 9 | 10 | Example 2: 11 | 12 | Input: "bbbbb" 13 | Output: 1 14 | Explanation: The answer is "b", with the length of 1. 15 | 16 | Example 3: 17 | 18 | Input: "pwwkew" 19 | Output: 3 20 | Explanation: The answer is "wke", with the length of 3. 21 | Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 22 | ''' 23 | 24 | from typing import List 25 | 26 | # Two Pointers and Hash Set 27 | 28 | class Solution: 29 | def lengthOfLongestSubstring(self, s: str) -> int: 30 | left = right = maxx = 0 31 | 32 | char = set() 33 | 34 | while right < len(s): 35 | if s[right] in char: 36 | char.remove(s[left]) 37 | left += 1 38 | else: 39 | char.add(s[right]) 40 | right += 1 41 | maxx = max(len(char), maxx) 42 | 43 | return maxx 44 | 45 | # Two Pointers and Hash Table 46 | 47 | class Solution: 48 | def lengthOfLongestSubstring(self, s: str) -> int: 49 | left = right = max_len = 0 50 | d = {} 51 | while left < len(s) and right < len(s): 52 | if s[right] in d: 53 | left = max(left, d[s[right]] + 1) 54 | d[s[right]] = right 55 | max_len = max(max_len, right - left + 1) 56 | right += 1 57 | return max_len 58 | 59 | # Custom Input Check 60 | 61 | s = Solution() 62 | answer = s.lengthOfLongestSubstring("nishant") # 6 63 | print(answer) -------------------------------------------------------------------------------- /0004-Median-of-Two-Sorted-Arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 3 | 4 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 5 | 6 | You may assume nums1 and nums2 cannot be both empty. 7 | 8 | Example 1: 9 | 10 | nums1 = [1, 3] 11 | nums2 = [2] 12 | 13 | The median is 2.0 14 | 15 | Example 2: 16 | 17 | nums1 = [1, 2] 18 | nums2 = [3, 4] 19 | 20 | The median is (2 + 3)/2 = 2.5 21 | ''' 22 | class Solution: 23 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 24 | m, n = len(nums1), len(nums2) 25 | if m > n: 26 | nums1, nums2, m, n = nums2, nums1, n, m 27 | if not n: 28 | return 29 | 30 | imin, imax, half_len = 0, m, (m + n + 1) // 2 31 | while imin <= imax: 32 | i = (imin + imax) // 2 33 | j = half_len - i 34 | if i < m and nums2[j - 1] > nums1[i]: 35 | imin = i + 1 36 | elif i > 0 and nums1[i - 1] > nums2[j]: 37 | imax = i - 1 38 | else: 39 | if not i: 40 | max_left = nums2[j - 1] 41 | elif not j: 42 | max_left = nums1[i - 1] 43 | else: 44 | max_left = max(nums1[i - 1], nums2[j - 1]) 45 | 46 | if (m + n) % 2 == 1: 47 | return max_left 48 | 49 | if i == m: 50 | min_right = nums2[j] 51 | elif j == n: 52 | min_right = nums1[i] 53 | else: 54 | min_right = min(nums1[i], nums2[j]) 55 | 56 | return (max_left + min_right) / 2.0 57 | -------------------------------------------------------------------------------- /0005-Longest-Palindromic-Substring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 3 | 4 | Example 1: 5 | 6 | Input: "babad" 7 | Output: "bab" 8 | Note: "aba" is also a valid answer. 9 | 10 | Example 2: 11 | 12 | Input: "cbbd" 13 | Output: "bb" 14 | ''' 15 | class Solution: 16 | def longestPalindrome(self, s: str) -> str: 17 | if not s: 18 | return "" 19 | 20 | start = end = 0 21 | 22 | for i in range(len(s)): 23 | length = self.expand_from_mid(s, i, i) 24 | length1 = self.expand_from_mid(s, i, i + 1) 25 | length = max(length, length1) 26 | if length > end - start: 27 | start = i - (length - 1) // 2 28 | end = i + length // 2 29 | 30 | return s[start : end + 1] 31 | 32 | def expand_from_mid(self, s, left, right): 33 | 34 | while left >= 0 and right < len(s) and s[left] == s[right]: 35 | left -= 1 36 | right += 1 37 | 38 | return right - left - 1 -------------------------------------------------------------------------------- /0006-ZigZag-Conversion.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 3 | 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: "PAHNAPLSIIGYIR" 8 | 9 | Write the code that will take a string and make this conversion given a number of rows: 10 | 11 | string convert(string s, int numRows); 12 | Example 1: 13 | 14 | Input: s = "PAYPALISHIRING", numRows = 3 15 | Output: "PAHNAPLSIIGYIR" 16 | Example 2: 17 | 18 | Input: s = "PAYPALISHIRING", numRows = 4 19 | Output: "PINALSIGYAHRPI" 20 | Explanation: 21 | 22 | P I N 23 | A L S I G 24 | Y A H R 25 | P I 26 | ''' 27 | class Solution: 28 | def convert(self, s: str, numRows: int) -> str: 29 | if numRows == 1: 30 | return s 31 | 32 | res = '' 33 | n = len(s) 34 | cycle_len = 2 * numRows - 2 35 | 36 | for i in range(numRows): 37 | j = 0 38 | while j + i < n: 39 | res += s[j + i] 40 | if i != 0 and i != numRows - 1 and j + cycle_len - i < n: 41 | res += s[j + cycle_len - i] 42 | j += cycle_len 43 | return res 44 | -------------------------------------------------------------------------------- /0009-Palindrome-Number.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/palindrome-number/ 2 | 3 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 4 | 5 | # Example 1: 6 | # Input: 121 7 | # Output: true 8 | 9 | # Example 2: 10 | # Input: -121 11 | # Output: false 12 | # Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 13 | 14 | # Example 3: 15 | # Input: 10 16 | # Output: false 17 | # Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 18 | 19 | # Follow up: 20 | # Coud you solve it without converting the integer to a string? 21 | 22 | # Method 1 (Meeting in the Middle and Comparing) 23 | 24 | class Solution: 25 | def isPalindrome(self, x: int) -> bool: 26 | if (x<0 or (x%10 == 0 and x!=0)): #Negative or Ending with 0 but not 0 cases 27 | return False 28 | rev = 0 29 | while(x>rev): 30 | rev = (rev*10)+(x%10) 31 | x=x//10 32 | return rev==x or rev//10==x #Removing middle digit from a number with odd length using rev//10 33 | 34 | # Method 2 (Reversing and Comparing) 35 | 36 | class Solution: 37 | def isPalindrome(self, x: int) -> bool: 38 | if x < 0 or (x != 0 and not (x % 10)): 39 | return False 40 | integer, res = x, 0 41 | while integer > 0: 42 | res = res * 10 + (integer % 10) 43 | integer //= 10 44 | print(res) 45 | return res == x -------------------------------------------------------------------------------- /0011-Container-With-Most-Water.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 3 | n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 4 | Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | 6 | Note: You may not slant the container and n is at least 2. 7 | 8 | Example: 9 | 10 | Input: [1,8,6,2,5,4,8,3,7] 11 | Output: 49 12 | ''' 13 | 14 | from typing import List 15 | 16 | # Two Pointers 17 | 18 | class Solution: 19 | def maxArea(self, height: List[int]) -> int: 20 | start, end, max_area = 0, len(height) - 1 , 0 21 | while start < end: 22 | max_area = max((end - start) * min(height[start], height[end]), max_area) 23 | if height[start] < height[end]: 24 | start += 1 25 | else: 26 | end -= 1 27 | return max_area 28 | 29 | # Custom Input Check 30 | 31 | s = Solution() 32 | answer = s.maxArea([2, 1, 1, 2]) # 6 33 | print(answer) -------------------------------------------------------------------------------- /0012-Integer-to-Roman.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 3 | 4 | Symbol Value 5 | I 1 6 | V 5 7 | X 10 8 | L 50 9 | C 100 10 | D 500 11 | M 1000 12 | 13 | For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. 14 | 15 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 16 | 17 | I can be placed before V (5) and X (10) to make 4 and 9. 18 | X can be placed before L (50) and C (100) to make 40 and 90. 19 | C can be placed before D (500) and M (1000) to make 400 and 900. 20 | 21 | Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 22 | 23 | Example 1: 24 | 25 | Input: 3 26 | Output: "III" 27 | 28 | Example 2: 29 | 30 | Input: 4 31 | Output: "IV" 32 | 33 | Example 3: 34 | 35 | Input: 9 36 | Output: "IX" 37 | 38 | Example 4: 39 | 40 | Input: 58 41 | Output: "LVIII" 42 | Explanation: L = 50, V = 5, III = 3. 43 | 44 | Example 5: 45 | 46 | Input: 1994 47 | Output: "MCMXCIV" 48 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 49 | ''' 50 | class Solution: 51 | def intToRoman(self, num: int) -> str: 52 | d = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'} 53 | 54 | res = '' 55 | 56 | for i in d: 57 | res += (num // i) * d[i] 58 | num %= i 59 | 60 | return res 61 | -------------------------------------------------------------------------------- /0014-Longest-Common-Prefix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: strs = ["flower","flow","flight"] 11 | Output: "fl" 12 | Example 2: 13 | 14 | Input: strs = ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= strs.length <= 200 22 | 0 <= strs[i].length <= 200 23 | strs[i] consists of only lowercase English letters. 24 | ''' 25 | 26 | # Method 1 (Comparing each String) 27 | 28 | class Solution: 29 | def longestCommonPrefix(self, strs: List[str]) -> str: 30 | if not strs: 31 | return "" 32 | lcp = strs[0] 33 | for index in range(1, len(strs)): 34 | lcp = self.sub_compare(lcp, strs[index]) 35 | if not lcp: 36 | return "" 37 | return lcp 38 | 39 | def sub_compare(self, s1, s2): 40 | res = "" 41 | if len(s2) < len(s1): 42 | s1, s2 = s2, s1 43 | for index, char in enumerate(s1): 44 | if char == s2[index]: 45 | res += char 46 | else: 47 | break 48 | return res -------------------------------------------------------------------------------- /0019-Remove-Nth-Node-From-End-of-List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, remove the n-th node from the end of list and return its head. 3 | 4 | Example: 5 | 6 | Given linked list: 1->2->3->4->5, and n = 2. 7 | 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | Note: 10 | 11 | Given n will always be valid. 12 | 13 | Follow up: 14 | 15 | Could you do this in one pass? 16 | ''' 17 | # Definition for singly-linked list. 18 | 19 | class ListNode: 20 | def __init__(self, val=0, next=None): 21 | self.val = val 22 | self.next = next 23 | 24 | class Solution: 25 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 26 | first = last = head 27 | for _ in range(n): 28 | last = last.next 29 | if not last: 30 | return first.next 31 | while last.next: 32 | last = last.next 33 | first = first.next 34 | first.next = first.next.next 35 | return head 36 | 37 | # Check Custom Input 38 | 39 | s = Solution() 40 | 41 | node1 = ListNode(1) 42 | node2 = ListNode(3) 43 | node3 = ListNode(5) 44 | node4 = ListNode(7) 45 | 46 | node1.next = node2 47 | node2.next = node3 48 | node3.next = node4 49 | 50 | answer = s.removeNthFromEnd(node1, 2) # 1 => 3 => 7 51 | 52 | while answer: 53 | print(answer.val) 54 | answer = answer.next -------------------------------------------------------------------------------- /0020-Valid-Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | Note that an empty string is also considered valid. 9 | 10 | Example 1: 11 | 12 | Input: "()" 13 | Output: true 14 | Example 2: 15 | 16 | Input: "()[]{}" 17 | Output: true 18 | Example 3: 19 | 20 | Input: "(]" 21 | Output: false 22 | Example 4: 23 | 24 | Input: "([)]" 25 | Output: false 26 | Example 5: 27 | 28 | Input: "{[]}" 29 | Output: true 30 | ''' 31 | 32 | # Time Complexity: O(n) 33 | # Space Complexity: O(n) 34 | 35 | # Solution using Stack 36 | 37 | class Solution: 38 | def isValid(self, s: str) -> bool: 39 | if len(s) % 2: 40 | return False 41 | parens = {'(' : ')', '{' : '}', '[' : ']'} 42 | stack = [] 43 | for paren in s: 44 | if paren in parens.keys(): 45 | stack.append(paren) 46 | elif not stack or paren != parens[stack.pop()]: 47 | return False 48 | return not stack -------------------------------------------------------------------------------- /0021-Merge-Two-Sorted-Lists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 3 | 4 | Example: 5 | 6 | Input: 1->2->4, 1->3->4 7 | Output: 1->1->2->3->4->4 8 | ''' 9 | 10 | # Definition for singly-linked list. 11 | 12 | class ListNode: 13 | def __init__(self, val = 0, next = None): 14 | self.val = val 15 | self.next = None 16 | 17 | #Iterative 18 | #Time Complexity - O(n+m), Space Complexity - O(1) 19 | 20 | class Solution: 21 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 22 | cur_node = pre_node = ListNode() 23 | while list1 and list2: 24 | if list1.val < list2.val: 25 | cur_node.next = list1 26 | list1 = list1.next 27 | else: 28 | cur_node.next = list2 29 | list2 = list2.next 30 | cur_node = cur_node.next 31 | cur_node.next = list1 if list1 else list2 32 | return pre_node.next 33 | 34 | #Recursive 35 | #Time Complexity - O(n+m), Space Complexity - O(n+m) 36 | 37 | class Solution: 38 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 39 | if not l1 or not l2: return l1 or l2 40 | if l1.val <= l2.val: 41 | l1.next = self.mergeTwoLists(l1.next, l2) 42 | return l1 43 | else: 44 | l2.next = self.mergeTwoLists(l2.next, l1) 45 | return l2 46 | 47 | # Custom Input Check 48 | 49 | s = Solution() 50 | 51 | l1_1 = ListNode(1) 52 | l1_2 = ListNode(2) 53 | l1_3 = ListNode(4) 54 | 55 | l1_1.next = l1_2 56 | l1_2.next = l1_3 57 | 58 | # l1: 1 => 2 => 4 59 | 60 | l2_1 = ListNode(1) 61 | l2_2 = ListNode(3) 62 | l2_3 = ListNode(4) 63 | 64 | l2_1.next = l2_2 65 | l2_2.next = l2_3 66 | 67 | # l2: 1 => 3 => 4 68 | 69 | answer = s.mergeTwoLists(l1_1, l2_1) 70 | 71 | while answer: 72 | print(answer.val) 73 | answer = answer.next -------------------------------------------------------------------------------- /0022-Generate-Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | [ 7 | "((()))", 8 | "(()())", 9 | "(())()", 10 | "()(())", 11 | "()()()" 12 | ] 13 | ''' 14 | class Solution: 15 | def generateParenthesis(self, n: int) -> List[str]: 16 | res = [] 17 | 18 | def backtrack(res, s, opening, closing, max_pairs): 19 | if len(s) == max_pairs * 2: 20 | res.append(s) 21 | return 22 | if opening < max_pairs: 23 | backtrack(res, s + '(', opening + 1, closing, max_pairs) 24 | if closing < opening: 25 | backtrack(res, s + ')', opening, closing + 1, max_pairs) 26 | 27 | backtrack(res, "", 0, 0, n) 28 | return res -------------------------------------------------------------------------------- /0024-Swap-Nodes-in-Pairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | You may not modify the values in the list's nodes, only nodes itself may be changed. 5 | 6 | 7 | 8 | Example: 9 | 10 | Given 1->2->3->4, you should return the list as 2->1->4->3. 11 | ''' 12 | # Definition for singly-linked list. 13 | # class ListNode: 14 | # def __init__(self, val=0, next=None): 15 | # self.val = val 16 | # self.next = next 17 | class Solution: 18 | def swapPairs(self, head: ListNode) -> ListNode: 19 | temp = ListNode() 20 | temp.next = head 21 | cur = temp 22 | 23 | while cur.next and cur.next.next: 24 | cur.next.next, cur.next, cur.next.next = cur.next.next.next, cur.next.next, cur.next 25 | cur = cur.next.next 26 | 27 | return temp.next 28 | -------------------------------------------------------------------------------- /0026-Remove-Duplicates-from-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | Example 1: 7 | 8 | Given nums = [1,1,2], 9 | 10 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 11 | 12 | It doesn't matter what you leave beyond the returned length. 13 | Example 2: 14 | 15 | Given nums = [0,0,1,1,1,2,2,3,3,4], 16 | 17 | Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. 18 | 19 | It doesn't matter what values are set beyond the returned length. 20 | Clarification: 21 | 22 | Confused why the returned value is an integer but your answer is an array? 23 | 24 | Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. 25 | 26 | Internally you can think of this: 27 | 28 | // nums is passed in by reference. (i.e., without making a copy) 29 | int len = removeDuplicates(nums); 30 | 31 | // any modification to nums in your function would be known by the caller. 32 | // using the length returned by your function, it prints the first len elements. 33 | for (int i = 0; i < len; i++) { 34 | print(nums[i]); 35 | } 36 | ''' 37 | class Solution: 38 | def removeDuplicates(self, nums: List[int]) -> int: 39 | if not nums: return 0 40 | pre, nex = 0, 1 41 | while nex < len(nums): 42 | if nums[nex] != nums[pre]: 43 | pre += 1 44 | nums[pre] = nums[nex] 45 | nex += 1 46 | return pre + 1 47 | -------------------------------------------------------------------------------- /0027-Remove-Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums and a value val, remove all instances of that value in-place and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 7 | 8 | Example 1: 9 | Given nums = [3,2,2,3], val = 3, 10 | 11 | Your function should return length = 2, with the first two elements of nums being 2. 12 | 13 | It doesn't matter what you leave beyond the returned length. 14 | 15 | Example 2: 16 | Given nums = [0,1,2,2,3,0,4,2], val = 2, 17 | 18 | Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. 19 | 20 | Note that the order of those five elements can be arbitrary. 21 | 22 | It doesn't matter what values are set beyond the returned length. 23 | Clarification: 24 | 25 | Confused why the returned value is an integer but your answer is an array? 26 | 27 | Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. 28 | 29 | Internally you can think of this: 30 | 31 | // nums is passed in by reference. (i.e., without making a copy) 32 | int len = removeElement(nums, val); 33 | 34 | // any modification to nums in your function would be known by the caller. 35 | // using the length returned by your function, it prints the first len elements. 36 | for (int i = 0; i < len; i++) { 37 | print(nums[i]); 38 | } 39 | ''' 40 | class Solution: 41 | def removeElement(self, nums: List[int], val: int) -> int: 42 | start, end = 0, len(nums) 43 | while start < end: 44 | if nums[start] == val: 45 | nums[start] = nums[end - 1] 46 | end -= 1 47 | else: 48 | start += 1 49 | return end 50 | -------------------------------------------------------------------------------- /0029-Divide-Two-Integers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. 3 | 4 | Return the quotient after dividing dividend by divisor. 5 | 6 | The integer division should truncate toward zero, which means losing its fractional part. 7 | For example, truncate(8.345) = 8 and truncate(-2.7335) = -2. 8 | 9 | Example 1: 10 | 11 | Input: dividend = 10, divisor = 3 12 | Output: 3 13 | Explanation: 10/3 = truncate(3.33333..) = 3. 14 | Example 2: 15 | 16 | Input: dividend = 7, divisor = -3 17 | Output: -2 18 | Explanation: 7/-3 = truncate(-2.33333..) = -2. 19 | Note: 20 | 21 | Both dividend and divisor will be 32-bit signed integers. 22 | The divisor will never be 0. 23 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. 24 | For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows. 25 | ''' 26 | class Solution: 27 | def divide(self, dividend: int, divisor: int) -> int: 28 | a, b, res = abs(dividend), abs(divisor), 0 29 | 30 | while a >= b: 31 | x = 0 32 | while a - (b << 1 << x) >= 0: 33 | x += 1 34 | res += 1 << x 35 | a -= b << x 36 | 37 | if not (dividend >= 0) is (divisor >= 0): 38 | res = -res 39 | 40 | return min(max(-2 ** 31, res), 2 ** 31 - 1) -------------------------------------------------------------------------------- /0031-Next-Permutation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place and use only constant extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 10 | 1,2,3 → 1,3,2 11 | 3,2,1 → 1,2,3 12 | 1,1,5 → 1,5,1 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 | i = len(nums) - 2 20 | while i >= 0 and nums[i + 1] <= nums[i]: 21 | i -= 1 22 | if i >= 0: 23 | j = len(nums) - 1 24 | while j >= 0 and nums[j] <= nums[i]: 25 | j -= 1 26 | nums[i], nums[j] = nums[j], nums[i] 27 | self.reverse(nums, i + 1, len(nums) - 1) 28 | 29 | def reverse(self, nums, start, end): 30 | while start < end: 31 | nums[start], nums[end] = nums[end], nums[start] 32 | start += 1 33 | end -= 1 34 | -------------------------------------------------------------------------------- /0035-Search-Insert-Position.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/search-insert-position/ 3 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 4 | 5 | You may assume no duplicates in the array. 6 | 7 | Example 1: 8 | 9 | Input: [1,3,5,6], 5 10 | Output: 2 11 | Example 2: 12 | 13 | Input: [1,3,5,6], 2 14 | Output: 1 15 | Example 3: 16 | 17 | Input: [1,3,5,6], 7 18 | Output: 4 19 | Example 4: 20 | 21 | Input: [1,3,5,6], 0 22 | Output: 0 23 | ''' 24 | 25 | # Using Binary Search 26 | 27 | class Solution: 28 | def searchInsert(self, nums: List[int], target: int) -> int: 29 | left, right = 0, len(nums) 30 | while left < right: 31 | mid = (left + right) // 2 32 | if target == nums[mid]: 33 | return mid 34 | if target > nums[mid]: 35 | left = mid + 1 36 | else: 37 | right = mid 38 | return left 39 | -------------------------------------------------------------------------------- /0038-Count-and-Say.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The count-and-say sequence is the sequence of integers with the first five terms as following: 3 | 4 | 1. 1 5 | 2. 11 6 | 3. 21 7 | 4. 1211 8 | 5. 111221 9 | 10 | 1 is read off as "one 1" or 11. 11 | 11 is read off as "two 1s" or 21. 12 | 21 is read off as "one 2, then one 1" or 1211. 13 | 14 | Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. 15 | 16 | Note: Each term of the sequence of integers will be represented as a string. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: 1 23 | Output: "1" 24 | Explanation: This is the base case. 25 | 26 | Example 2: 27 | 28 | Input: 4 29 | Output: "1211" 30 | Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". 31 | ''' 32 | class Solution(object): 33 | def countAndSay(self, n): 34 | if n == 1: 35 | return '1' 36 | s = '1' 37 | for _ in range(n - 1): 38 | cur_val, count, res = s[0], 0, [] 39 | for i in s: 40 | if cur_val == i: 41 | count += 1 42 | else: 43 | res.append(str(count)) 44 | res.append(cur_val) 45 | cur_val = i 46 | count = 1 47 | res.append(str(count)) 48 | res.append(cur_val) 49 | s = ''.join(res) 50 | return s 51 | -------------------------------------------------------------------------------- /0039-Combination-Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of distinct integers candidates and a target integer target, 3 | return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. 4 | The same number may be chosen from candidates an unlimited number of times. 5 | Two combinations are unique if the frequency of at least one of the chosen numbers is different. 6 | It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. 7 | 8 | Example 1: 9 | Input: candidates = [2,3,6,7], target = 7 10 | Output: [[2,2,3],[7]] 11 | 12 | Explanation: 13 | 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 14 | 7 is a candidate, and 7 = 7. 15 | These are the only two combinations. 16 | 17 | Example 2: 18 | Input: candidates = [2,3,5], target = 8 19 | Output: [[2,2,2,2],[2,3,3],[3,5]] 20 | 21 | Example 3: 22 | Input: candidates = [2], target = 1 23 | Output: [] 24 | 25 | Example 4: 26 | Input: candidates = [1], target = 1 27 | Output: [[1]] 28 | 29 | Example 5: 30 | Input: candidates = [1], target = 2 31 | Output: [[1,1]] 32 | 33 | 34 | Constraints: 35 | 1 <= candidates.length <= 30 36 | 1 <= candidates[i] <= 200 37 | All elements of candidates are distinct. 38 | 1 <= target <= 500 39 | ''' 40 | 41 | # Using Backtracking 42 | 43 | class Solution: 44 | 45 | def backtrack(self, candidates, target, res, cur, index, summ): 46 | if summ == target: 47 | res.append(cur[:]) 48 | elif summ < target: 49 | for i in range(index, len(candidates)): 50 | cur.append(candidates[i]) 51 | self.backtrack(candidates, target, res, cur, i, sum(cur)) 52 | cur.pop() 53 | return 54 | 55 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 56 | res = [] 57 | cur = [] 58 | self.backtrack(candidates, target, res, cur, 0, 0) 59 | return res -------------------------------------------------------------------------------- /0046-Permutations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of distinct integers, return all possible permutations. 3 | 4 | Example: 5 | 6 | Input: [1,2,3] 7 | Output: 8 | [ 9 | [1,2,3], 10 | [1,3,2], 11 | [2,1,3], 12 | [2,3,1], 13 | [3,1,2], 14 | [3,2,1] 15 | ] 16 | ''' 17 | 18 | # Using Backtracking 19 | 20 | class Solution: 21 | 22 | def backtrack(self, nums, res, cur): 23 | if not nums: 24 | res.append(cur) 25 | for i in range(len(nums)): 26 | self.backtrack(nums[:i] + nums[i+1:], res, cur + [nums[i]]) 27 | 28 | def permute(self, nums: List[int]) -> List[List[int]]: 29 | cur = [] 30 | res = [] 31 | self.backtrack(nums, res, cur) 32 | return res -------------------------------------------------------------------------------- /0048-Rotate-Image.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 3 | 4 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. 5 | DO NOT allocate another 2D matrix and do the rotation. 6 | 7 | Example 1: 8 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 9 | Output: [[7,4,1],[8,5,2],[9,6,3]] 10 | 11 | Example 2: 12 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 13 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 14 | 15 | Example 3: 16 | Input: matrix = [[1]] 17 | Output: [[1]] 18 | 19 | Example 4: 20 | Input: matrix = [[1,2],[3,4]] 21 | Output: [[3,1],[4,2]] 22 | 23 | 24 | Constraints: 25 | matrix.length == n 26 | matrix[i].length == n 27 | 1 <= n <= 20 28 | -1000 <= matrix[i][j] <= 1000 29 | ''' 30 | class Solution: 31 | def rotate(self, matrix: List[List[int]]) -> None: 32 | """ 33 | Do not return anything, modify matrix in-place instead. 34 | """ 35 | n = len(matrix) 36 | 37 | for i in range(n): 38 | j = i 39 | while j < n: 40 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 41 | j += 1 42 | 43 | for i in range(n): 44 | for j in range(n//2): 45 | matrix[i][j], matrix[i][n - 1 - j] = matrix[i][n - 1 - j], matrix[i][j] -------------------------------------------------------------------------------- /0053-Maximum-Subarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | Example: 5 | 6 | Input: [-2,1,-3,4,-1,2,1,-5,4], 7 | Output: 6 8 | Explanation: [4,-1,2,1] has the largest sum = 6. 9 | Follow up: 10 | 11 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 12 | ''' 13 | 14 | # Using Sliding Window 15 | 16 | class Solution: 17 | def maxSubArray(self, nums: List[int]) -> int: 18 | maxSum = nums[0] 19 | curSum = 0 20 | 21 | for num in nums: 22 | if curSum < 0: 23 | curSum = 0 24 | curSum += num 25 | maxSum = max(curSum, maxSum) 26 | return maxSum 27 | 28 | 29 | # Using Kadane's Algorithm METHOD 1 30 | 31 | class Solution: 32 | def maxSubArray(self, nums: List[int]) -> int: 33 | 34 | cur_sum = max_sum = nums[0] 35 | 36 | for i in range(1, len(nums)): 37 | 38 | cur_sum = max(nums[i] + cur_sum, nums[i]) 39 | max_sum = max(cur_sum, max_sum) 40 | 41 | return max_sum 42 | 43 | # Using Kadane's Algorithm METHOD 2 44 | 45 | class Solution: 46 | def maxSubArray(self, nums: List[int]) -> int: 47 | cur_sum, max_sum = 0, nums[0] 48 | 49 | for num in nums: 50 | cur_sum = max(num, cur_sum + num) 51 | max_sum = max(cur_sum, max_sum) 52 | 53 | return max_sum -------------------------------------------------------------------------------- /0055-Jump-Game.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | Example 1: 9 | 10 | Input: [2,3,1,1,4] 11 | Output: true 12 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 13 | 14 | Example 2: 15 | 16 | Input: [3,2,1,0,4] 17 | Output: false 18 | Explanation: You will always arrive at index 3 no matter what. Its maximum 19 | jump length is 0, which makes it impossible to reach the last index. 20 | ''' 21 | # Time Complexity: O(n) 22 | # Space Complexity: O(1) 23 | class Solution: 24 | def canJump(self, nums: List[int]) -> bool: 25 | last = len(nums) - 1 26 | for i in range(last, -1, -1): 27 | if i + nums[i] >= last: 28 | last = i; 29 | return not last 30 | -------------------------------------------------------------------------------- /0056-Merge-Intervals.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | Example 1: 5 | 6 | Input: [[1,3],[2,6],[8,10],[15,18]] 7 | Output: [[1,6],[8,10],[15,18]] 8 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 9 | 10 | Example 2: 11 | 12 | Input: [[1,4],[4,5]] 13 | Output: [[1,5]] 14 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 15 | ''' 16 | class Solution: 17 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 18 | if len(intervals) <= 1: 19 | return intervals 20 | intervals.sort() 21 | res = [] 22 | cur_interval = intervals[0] 23 | res.append(cur_interval) 24 | 25 | for interval in intervals: 26 | if cur_interval[1] >= interval[0]: 27 | res[-1][1] = max(cur_interval[1], interval[1]) 28 | else: 29 | cur_interval = interval 30 | res.append(cur_interval) 31 | 32 | return res -------------------------------------------------------------------------------- /0066-Plus-One.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 3 | 4 | The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 5 | 6 | You may assume the integer does not contain any leading zero, except the number 0 itself. 7 | 8 | Example 1: 9 | 10 | Input: [1,2,3] 11 | Output: [1,2,4] 12 | Explanation: The array represents the integer 123. 13 | 14 | Example 2: 15 | 16 | Input: [4,3,2,1] 17 | Output: [4,3,2,2] 18 | Explanation: The array represents the integer 4321. 19 | ''' 20 | class Solution: 21 | def plusOne(self, digits: List[int]) -> List[int]: 22 | for i in range(len(digits)-1, -1, -1): 23 | digits[i] += 1 24 | if digits[i] < 10: 25 | return digits 26 | else: 27 | digits[i] = 0 28 | digits.insert(0, 1) 29 | return digits 30 | 31 | -------------------------------------------------------------------------------- /0067-Add-Binary.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | The input strings are both non-empty and contains only characters 1 or 0. 5 | 6 | Example 1: 7 | 8 | Input: a = "11", b = "1" 9 | Output: "100" 10 | Example 2: 11 | 12 | Input: a = "1010", b = "1011" 13 | Output: "10101" 14 | ''' 15 | 16 | # Method 1 17 | 18 | class Solution: 19 | def addBinary(self, a: str, b: str) -> str: 20 | i, j, carry = len(a) - 1, len(b) - 1, '0' 21 | res = [] 22 | while(i >= 0 or j >= 0 or carry != '0'): 23 | 24 | num1 = a[i] if i >= 0 else '0' 25 | num2 = b[j] if j >= 0 else '0' 26 | 27 | if num1 == num2: 28 | res.append(carry) 29 | carry = num1 30 | else: 31 | res.append('1' if carry == '0' else '0') 32 | 33 | i -= 1 34 | j -= 1 35 | 36 | return ''.join(res[::-1]) 37 | 38 | # Method 2 39 | 40 | class Solution: 41 | def addBinary(self, a: str, b: str) -> str: 42 | i, j, carry, result = len(a) - 1, len(b) - 1, 0, [] 43 | while i >= 0 or j >= 0 or carry: 44 | total = carry 45 | if i >= 0: 46 | total += int(a[i]) 47 | i -= 1 48 | if j >= 0: 49 | total += int(b[j]) 50 | j -= 1 51 | result.append(str(total%2)) 52 | carry = total//2 53 | 54 | return ''.join(result[::-1]) 55 | 56 | # Check Custom Input 57 | s = Solution() 58 | answer = s.addBinary('101010', '1111111') 59 | print(answer) -------------------------------------------------------------------------------- /0069-Sqrt(x).py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/sqrtx/ 3 | Implement int sqrt(int x). 4 | 5 | Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 6 | 7 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 8 | 9 | Example 1: 10 | Input: 4 11 | Output: 2 12 | 13 | Example 2: 14 | Input: 8 15 | Output: 2 16 | 17 | Explanation: The square root of 8 is 2.82842..., and since 18 | the decimal part is truncated, 2 is returned. 19 | ''' 20 | class Solution: 21 | def mySqrt(self, x: int) -> int: 22 | lower, upper = 0, x 23 | while(lower<=upper): 24 | mid=(lower+upper)//2 25 | square = mid**2 26 | if(square==x): 27 | return mid 28 | if(square rorse (replace 'h' with 'r') 15 | rorse -> rose (remove 'r') 16 | rose -> ros (remove 'e') 17 | Example 2: 18 | 19 | Input: word1 = "intention", word2 = "execution" 20 | Output: 5 21 | Explanation: 22 | intention -> inention (remove 't') 23 | inention -> enention (replace 'i' with 'e') 24 | enention -> exention (replace 'n' with 'x') 25 | exention -> exection (replace 'n' with 'c') 26 | exection -> execution (insert 'u') 27 | ''' 28 | class Solution: 29 | def minDistance(self, word1: str, word2: str) -> int: 30 | m = len(word1) 31 | n = len(word2) 32 | table = [[0] * (n + 1) for _ in range(m + 1)] 33 | 34 | for i in range(m + 1): 35 | table[i][0] = i 36 | for j in range(n + 1): 37 | table[0][j] = j 38 | 39 | for i in range(1, m + 1): 40 | for j in range(1, n + 1): 41 | if word1[i - 1] == word2[j - 1]: 42 | table[i][j] = table[i - 1][j - 1] 43 | else: 44 | table[i][j] = 1 + min(table[i - 1][j], table[i][j - 1], table[i - 1][j - 1]) 45 | return table[-1][-1] 46 | -------------------------------------------------------------------------------- /0074-Search-a-2D-Matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | Example 1: 7 | 8 | Input: 9 | matrix = [ 10 | [1, 3, 5, 7], 11 | [10, 11, 16, 20], 12 | [23, 30, 34, 50] 13 | ] 14 | target = 3 15 | Output: true 16 | Example 2: 17 | 18 | Input: 19 | matrix = [ 20 | [1, 3, 5, 7], 21 | [10, 11, 16, 20], 22 | [23, 30, 34, 50] 23 | ] 24 | target = 13 25 | Output: false 26 | ''' 27 | class Solution: 28 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 29 | if not matrix: 30 | return False 31 | 32 | rows, cols = len(matrix), len(matrix[0]) 33 | low, high = 0, rows * cols - 1 34 | 35 | while low <= high: 36 | mid = (low + high) // 2 37 | num = matrix[mid // cols][mid % cols] 38 | 39 | if num == target: return True 40 | elif num < target: low = mid + 1 41 | else: high = mid - 1 42 | 43 | return False 44 | -------------------------------------------------------------------------------- /0075-Sort-Colors.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. 3 | 4 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 5 | 6 | Note: You are not suppose to use the library's sort function for this problem. 7 | 8 | Example: 9 | 10 | Input: [2,0,2,1,1,0] 11 | Output: [0,0,1,1,2,2] 12 | Follow up: 13 | 14 | A rather straight forward solution is a two-pass algorithm using counting sort. 15 | First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 16 | Could you come up with a one-pass algorithm using only constant space? 17 | ''' 18 | 19 | # Asked in HashedIn Interview 20 | 21 | class Solution: 22 | def sortColors(self, nums: List[int]) -> None: 23 | index, start, end = 0, 0, len(nums) - 1 24 | while index <= end and start < end: 25 | if nums[index] == 0: 26 | nums[index], nums[start] = nums[start], nums[index] 27 | start += 1 28 | index += 1 29 | elif nums[index] == 2: 30 | nums[index], nums[end] = nums[end], nums[index] 31 | end -= 1 32 | else: 33 | index += 1 -------------------------------------------------------------------------------- /0078-Subsets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums of unique elements, return all possible subsets (the power set). 3 | 4 | The solution set must not contain duplicate subsets. Return the solution in any order. 5 | 6 | Example 1: 7 | Input: nums = [1,2,3] 8 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 9 | 10 | Example 2: 11 | Input: nums = [0] 12 | Output: [[],[0]] 13 | 14 | 15 | Constraints: 16 | 1 <= nums.length <= 10 17 | -10 <= nums[i] <= 10 18 | All the numbers of nums are unique. 19 | ''' 20 | 21 | # Using Backtracking 22 | 23 | class Solution: 24 | 25 | def backtrack(self, nums, res, cur, index): 26 | if index > len(nums): 27 | return 28 | res.append(cur.copy()) 29 | for i in range(index, len(nums)): 30 | if nums[i] not in cur: 31 | cur.append(nums[i]) 32 | self.backtrack(nums, res, cur, i) 33 | cur.pop() 34 | return 35 | 36 | def subsets(self, nums: List[int]) -> List[List[int]]: 37 | cur = [] 38 | res = [] 39 | self.backtrack(nums, res, cur, 0) 40 | return res -------------------------------------------------------------------------------- /0088-Merge-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/merge-sorted-array/ 3 | 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | Note: 7 | 8 | The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 10 | 11 | Example: 12 | 13 | Input: 14 | nums1 = [1,2,3,0,0,0], m = 3 15 | nums2 = [2,5,6], n = 3 16 | 17 | Output: [1,2,2,3,5,6] 18 | 19 | ''' 20 | class Solution: 21 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 22 | """ 23 | Do not return anything, modify nums1 in-place instead. 24 | """ 25 | m -= 1 26 | n -= 1 27 | 28 | index = len(nums1) - 1 29 | 30 | for i in range(index, -1, -1): 31 | 32 | if m >= 0 and n >= 0: 33 | 34 | if nums1[m] > nums2[n]: 35 | 36 | nums1[i] = nums1[m] 37 | m -= 1 38 | 39 | else: 40 | 41 | nums1[i] = nums2[n] 42 | n -= 1 43 | 44 | elif n >= 0: 45 | 46 | nums1[i] = nums2[n] 47 | n -= 1 -------------------------------------------------------------------------------- /0091-Decode-Ways.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 'A' -> 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 9 | 10 | Example 1: 11 | 12 | Input: "12" 13 | Output: 2 14 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 15 | Example 2: 16 | 17 | Input: "226" 18 | Output: 3 19 | Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 20 | ''' 21 | class Solution: 22 | def numDecodings(self, s: str) -> int: 23 | prev_no_of_ways = 0 24 | no_of_ways = int(s > '') 25 | prev_digit = '' 26 | 27 | for digit in s: 28 | copy_prev = prev_no_of_ways 29 | prev_no_of_ways = no_of_ways 30 | 31 | no_of_ways = (digit > '0') * no_of_ways 32 | 33 | no_of_ways += (9 < int(prev_digit + digit) < 27) * copy_prev 34 | 35 | prev_digit = digit 36 | 37 | return no_of_ways 38 | -------------------------------------------------------------------------------- /0094-Binary-Tree-Inorder-Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given the root of a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | Follow up: Recursive solution is trivial, could you do it iteratively? 5 | 6 | Example 1: 7 | 8 | Input: root = [1,null,2,3] 9 | Output: [1,3,2] 10 | 11 | Example 2: 12 | 13 | Input: root = [] 14 | Output: [] 15 | 16 | Example 3: 17 | 18 | Input: root = [1] 19 | Output: [1] 20 | 21 | Example 4: 22 | 23 | Input: root = [1,2] 24 | Output: [2,1] 25 | 26 | Example 5: 27 | 28 | Input: root = [1,null,2] 29 | Output: [1,2] 30 | 31 | 32 | Constraints: 33 | 34 | The number of nodes in the tree is in the range [0, 100]. 35 | -100 <= Node.val <= 100 36 | ''' 37 | 38 | # Definition for a binary tree node. 39 | # class TreeNode: 40 | # def __init__(self, val=0, left=None, right=None): 41 | # self.val = val 42 | # self.left = left 43 | # self.right = right 44 | 45 | # Recursive Solution 46 | 47 | class Solution: 48 | def inorderTraversal(self, root: TreeNode) -> List[int]: 49 | res = [] 50 | self.recursive(root, res) 51 | return res 52 | 53 | def recursive(self, root, res): 54 | if not root: 55 | return 56 | self.recursive(root.left, res) 57 | res.append(root.val) 58 | self.recursive(root.right, res) 59 | 60 | # Iterative Solution 61 | 62 | class Solution: 63 | def inorderTraversal(self, root: TreeNode) -> List[int]: 64 | res = [] 65 | if not root: 66 | return res 67 | stack = [] 68 | node = root 69 | while node or stack: 70 | if node: 71 | stack.append(node) 72 | node = node.left 73 | else: 74 | new_node = stack.pop() 75 | res.append(new_node.val) 76 | node = new_node.right 77 | 78 | return res -------------------------------------------------------------------------------- /0100-Same-Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary trees, write a function to check if they are the same or not. 3 | 4 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 5 | 6 | Example 1: 7 | 8 | Input: 1 1 9 | / \ / \ 10 | 2 3 2 3 11 | 12 | [1,2,3], [1,2,3] 13 | 14 | Output: true 15 | Example 2: 16 | 17 | Input: 1 1 18 | / \ 19 | 2 2 20 | 21 | [1,2], [1,null,2] 22 | 23 | Output: false 24 | Example 3: 25 | 26 | Input: 1 1 27 | / \ / \ 28 | 2 1 1 2 29 | 30 | [1,2,1], [1,1,2] 31 | 32 | Output: false 33 | ''' 34 | # Definition for a binary tree node. 35 | # class TreeNode: 36 | # def __init__(self, val=0, left=None, right=None): 37 | # self.val = val 38 | # self.left = left 39 | # self.right = right 40 | class Solution: 41 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 42 | if not p and not q: 43 | return True 44 | elif not p or not q: 45 | return False 46 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 47 | 48 | def isSameTree_iterative(self, p: TreeNode, q: TreeNode) -> bool: 49 | stack = [(p, q)] 50 | while stack: 51 | node1, node2 = stack.pop() 52 | if not node1 and not node2: 53 | continue 54 | elif not node1 or not node2: 55 | return False 56 | if node1.val != node2.val: 57 | return False 58 | stack.append((node1.right, node2.right)) 59 | stack.append((node1.left, node2.left)) 60 | return True 61 | -------------------------------------------------------------------------------- /0102-Binary-Tree-Level-Order-Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | [ 13 | [3], 14 | [9,20], 15 | [15,7] 16 | ] 17 | ''' 18 | class Solution: 19 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 20 | if not root: 21 | return root 22 | queue, res = [root], [] 23 | while queue: 24 | next_level, value = [], [] 25 | for node in queue: 26 | value.append(node.val) 27 | if node.left: 28 | next_level.append(node.left) 29 | if node.right: 30 | next_level.append(node.right) 31 | queue = next_level 32 | res.append(value) 33 | 34 | return res 35 | 36 | -------------------------------------------------------------------------------- /0107-Binary-Tree-Level-Order-Traversal-II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its bottom-up level order traversal as: 12 | [ 13 | [15,7], 14 | [9,20], 15 | [3] 16 | ] 17 | ''' 18 | # Definition for a binary tree node. 19 | # class TreeNode: 20 | # def __init__(self, val=0, left=None, right=None): 21 | # self.val = val 22 | # self.left = left 23 | # self.right = right 24 | 25 | # Method 1, Iterative Solution 26 | 27 | class Solution: 28 | def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: 29 | if root is None: 30 | return [] 31 | 32 | current, res = [root], [] 33 | 34 | while current: 35 | nex, temp = [], [] 36 | for n in current: 37 | temp.append(n.val) 38 | if n.left: 39 | nex.append(n.left) 40 | if n.right: 41 | nex.append(n.right) 42 | current = nex 43 | res.append(temp) 44 | return res[::-1] 45 | 46 | # Method 2, Recursive Solution 47 | 48 | # Definition for a binary tree node. 49 | # class TreeNode: 50 | # def __init__(self, val=0, left=None, right=None): 51 | # self.val = val 52 | # self.left = left 53 | # self.right = right 54 | class Solution: 55 | def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: 56 | levels = [] 57 | if not root: 58 | return levels 59 | 60 | def helper(node,level): 61 | 62 | if len(levels)==level: 63 | levels.append([]) 64 | 65 | levels[level].append(node.val) 66 | 67 | if node.left: helper(node.left, level+1) 68 | if node.right: helper(node.right, level+1) 69 | 70 | helper(root,0) 71 | 72 | return levels[::-1] 73 | -------------------------------------------------------------------------------- /0118-Pascal-Triangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 3 | 4 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 5 | 6 | Example: 7 | 8 | Input: 5 9 | Output: 10 | [ 11 | [1], 12 | [1,1], 13 | [1,2,1], 14 | [1,3,3,1], 15 | [1,4,6,4,1] 16 | ] 17 | 18 | 19 | ''' 20 | #Method 1 21 | class Solution: 22 | def generate(self, numRows: int) -> List[List[int]]: 23 | res = [] 24 | if numRows == 1: 25 | return [[1]] 26 | for i in range(1, numRows + 1): 27 | row = [1] 28 | for j in range(1,i): 29 | row.append(row[len(row)-1] * (i - j) // j) 30 | res.append(row) 31 | return res 32 | 33 | #Method 2 34 | class Solution: 35 | def generate(self, numRows: int) -> List[List[int]]: 36 | res = [] 37 | if numRows == 1: 38 | return [[1]] 39 | for i in range(1, numRows + 1): 40 | row = [1]*i 41 | for j in range(1, i-1): 42 | row[j] = res[i-2][j-1] + res[i-2][j] 43 | res.append(row) 44 | return res 45 | -------------------------------------------------------------------------------- /0121-Best-Time-To-Buy-and-Sell-Stock.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 5 | 6 | Note that you cannot sell a stock before you buy one. 7 | 8 | Example 1: 9 | 10 | Input: [7,1,5,3,6,4] 11 | Output: 5 12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 13 | Not 7-1 = 6, as selling price needs to be larger than buying price. 14 | Example 2: 15 | 16 | Input: [7,6,4,3,1] 17 | Output: 0 18 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 19 | ''' 20 | class Solution: 21 | def maxProfit(self, prices: List[int]) -> int: 22 | if not prices: return 0 23 | min_price, max_profit = prices[0], 0 24 | for price in prices: 25 | min_price = price if price < min_price else min_price 26 | max_profit = price - min_price if price - min_price > max_profit else max_profit 27 | return max_profit 28 | 29 | # Same Approach, Different Solution 30 | 31 | class Solution: 32 | def maxProfit(self, prices: List[int]) -> int: 33 | buy, sell, max_profit = 0, 1, 0 34 | while sell < len(prices): 35 | if prices[sell] > prices[buy]: 36 | profit = prices[sell] - prices[buy] 37 | max_profit = profit if profit > max_profit else max_profit 38 | else: 39 | buy = sell 40 | sell += 1 41 | return max_profit 42 | 43 | # Kadane's Algorithm 44 | 45 | class Solution: 46 | def maxProfit(self, prices: List[int]) -> int: 47 | profit = max_profit = 0 48 | 49 | for i in range(1, len(prices)): 50 | profit = max(0, profit + prices[i] - prices[i-1]) 51 | max_profit = max(max_profit, profit) 52 | 53 | return max_profit -------------------------------------------------------------------------------- /0122-Best-Time-To-Buy-and-Sell-Stock-II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 5 | 6 | Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 7 | 8 | Example 1: 9 | 10 | Input: [7,1,5,3,6,4] 11 | Output: 7 12 | Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 13 | Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 14 | 15 | Example 2: 16 | 17 | Input: [1,2,3,4,5] 18 | Output: 4 19 | Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 20 | Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 21 | engaging multiple transactions at the same time. You must sell before buying again. 22 | 23 | Example 3: 24 | 25 | Input: [7,6,4,3,1] 26 | Output: 0 27 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 28 | ''' 29 | class Solution: 30 | def maxProfit(self, prices: List[int]) -> int: 31 | max_profit = 0 32 | for i in range(len(prices) - 1): 33 | if prices[i + 1] > prices[i]: 34 | max_profit += prices[i + 1] - prices[i] 35 | return max_profit 36 | -------------------------------------------------------------------------------- /0125-Valid-Palindrome.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | Note: For the purpose of this problem, we define empty string as valid palindrome. 5 | 6 | Example 1: 7 | 8 | Input: "A man, a plan, a canal: Panama" 9 | Output: true 10 | 11 | Example 2: 12 | 13 | Input: "race a car" 14 | Output: false 15 | ''' 16 | # Time Complexity: O(n) 17 | # Space Complexity: O(1) 18 | class Solution: 19 | def isPalindrome(self, s: str) -> bool: 20 | first, last = 0, len(s) - 1 21 | 22 | while first < last: 23 | 24 | if not s[first].isalnum(): 25 | first += 1 26 | continue 27 | 28 | elif not s[last].isalnum(): 29 | last -= 1 30 | continue 31 | 32 | elif s[first].lower() != s[last].lower(): 33 | return False 34 | 35 | first += 1 36 | last -= 1 37 | 38 | return True 39 | -------------------------------------------------------------------------------- /0131-Palindrome-Partitioning.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. 3 | A palindrome string is a string that reads the same backward as forward. 4 | 5 | Example 1: 6 | Input: s = "aab" 7 | Output: [["a","a","b"],["aa","b"]] 8 | 9 | Example 2: 10 | Input: s = "a" 11 | Output: [["a"]] 12 | 13 | Constraints: 14 | 1 <= s.length <= 16 15 | s contains only lowercase English letters. 16 | ''' 17 | 18 | # Using DFS 19 | 20 | class Solution: 21 | 22 | def isPalindrome(self, seg): 23 | start, end = 0, len(seg) - 1 24 | 25 | while start < end: 26 | if seg[start] != seg[end]: 27 | return False 28 | start += 1 29 | end -= 1 30 | return True 31 | 32 | def dfs(self, s, temp, res): 33 | if not s and temp: 34 | res.append(temp[:]) 35 | return 36 | for i in range(1, len(s) + 1): 37 | seg = s[:i] 38 | if self.isPalindrome(seg): 39 | temp.append(seg) 40 | self.dfs(s[i:], temp, res) 41 | temp.pop() 42 | 43 | def partition(self, s: str) -> List[List[str]]: 44 | res = [] 45 | temp = [] 46 | self.dfs(s, temp, res) 47 | return res -------------------------------------------------------------------------------- /0136-Single-Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: 5 | 6 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | 8 | Example 1: 9 | 10 | Input: [2,2,1] 11 | Output: 1 12 | Example 2: 13 | 14 | Input: [4,1,2,1,2] 15 | Output: 4 16 | ''' 17 | 18 | from typing import List 19 | 20 | # Bit Manipulation 21 | 22 | # Time Complexity: O(n) 23 | # Space Complexity: O(1) 24 | 25 | class Solution: 26 | def singleNumber(self, nums: List[int]) -> int: 27 | res = 0 28 | for num in nums: 29 | res ^= num 30 | return res 31 | 32 | # Hash Set 33 | 34 | # Time Complexity: O(n) 35 | # Space Complexity: O(n) 36 | 37 | class Solution: 38 | def singleNumber(self, nums: List[int]) -> int: 39 | unique = set() 40 | for num in nums: 41 | unique.add(num) 42 | return (2 * sum(unique)) - sum(nums) 43 | 44 | # Hash Set One Liner 45 | 46 | class Solution: 47 | def singleNumber(self, nums: List[int]) -> int: 48 | return 2*(sum(set(nums))) - sum(nums) 49 | 50 | # Hash Table 51 | 52 | # Time Complexity: O(n) 53 | # Space Complexity: O(n) 54 | 55 | class Solution: 56 | def singleNumber(self, nums: List[int]) -> int: 57 | unique = {} 58 | for num in nums: 59 | if num in unique: 60 | unique[num] += 1 61 | else: 62 | unique[num] = 1 63 | for key, value in unique.items(): 64 | if value == 1: 65 | return key 66 | 67 | # Check Custom Input 68 | 69 | s = Solution() 70 | answer = s.singleNumber([3, 3, 2, 2, 1]) # 1 71 | print(answer) -------------------------------------------------------------------------------- /0138-Copy-List-with-Random-Pointer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | 4 | Return a deep copy of the list. 5 | 6 | The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: 7 | 8 | val: an integer representing Node.val 9 | random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 16 | Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] 17 | 18 | Example 2: 19 | 20 | Input: head = [[1,1],[2,1]] 21 | Output: [[1,1],[2,1]] 22 | 23 | Example 3: 24 | 25 | Input: head = [[3,null],[3,0],[3,null]] 26 | Output: [[3,null],[3,0],[3,null]] 27 | 28 | Example 4: 29 | 30 | Input: head = [] 31 | Output: [] 32 | Explanation: Given linked list is empty (null pointer), so return null. 33 | 34 | 35 | 36 | Constraints: 37 | 38 | -10000 <= Node.val <= 10000 39 | Node.random is null or pointing to a node in the linked list. 40 | Number of Nodes will not exceed 1000. 41 | ''' 42 | """ 43 | # Definition for a Node. 44 | class Node: 45 | def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): 46 | self.val = int(x) 47 | self.next = next 48 | self.random = random 49 | """ 50 | class Solution: 51 | def copyRandomList(self, head: 'Node') -> 'Node': 52 | if not head: 53 | return None 54 | 55 | copy = {} 56 | cur = head 57 | while cur: 58 | copy[cur] = Node(cur.val, None, None) 59 | cur = cur.next 60 | cur = head 61 | while cur: 62 | if cur.next: 63 | copy[cur].next = copy[cur.next] 64 | if cur.random: 65 | copy[cur].random = copy[cur.random] 66 | cur = cur.next 67 | return copy[head] 68 | -------------------------------------------------------------------------------- /0141-Linked-List-Cycle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, determine if it has a cycle in it. 3 | 4 | To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. 5 | 6 | Example 1: 7 | 8 | Input: head = [3,2,0,-4], pos = 1 9 | Output: true 10 | Explanation: There is a cycle in the linked list, where tail connects to the second node. 11 | 12 | Example 2: 13 | 14 | Input: head = [1,2], pos = 0 15 | Output: true 16 | Explanation: There is a cycle in the linked list, where tail connects to the first node. 17 | 18 | Example 3: 19 | 20 | Input: head = [1], pos = -1 21 | Output: false 22 | Explanation: There is no cycle in the linked list. 23 | 24 | Follow up: 25 | 26 | Can you solve it using O(1) (i.e. constant) memory? 27 | ''' 28 | 29 | # Definition for singly-linked list. 30 | 31 | class ListNode: 32 | def __init__(self, x): 33 | self.val = x 34 | self.next = None 35 | 36 | # Hare Tortoise Algorithm 37 | 38 | class Solution: 39 | def hasCycle(self, head: ListNode) -> bool: 40 | slow = fast = head 41 | while fast and fast.next: 42 | slow = slow.next 43 | fast = fast.next.next 44 | if slow == fast: 45 | return True 46 | return False 47 | 48 | # Custom Input Check 49 | 50 | s = Solution() 51 | 52 | node1 = ListNode(1) 53 | node2 = ListNode(5) 54 | node3 = ListNode(11) 55 | node4 = ListNode(8) 56 | node5 = ListNode(9) 57 | 58 | node1.next = node2 59 | node2.next = node3 60 | node3.next = node4 61 | node4.next = node5 62 | node5.next = node2 63 | 64 | answer = s.hasCycle(node1) 65 | 66 | print(answer) -------------------------------------------------------------------------------- /0143-Reorder-List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, 3 | reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 4 | 5 | You may not modify the values in the list's nodes, only nodes itself may be changed. 6 | 7 | Example 1: 8 | 9 | Given 1->2->3->4, reorder it to 1->4->2->3. 10 | Example 2: 11 | 12 | Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 13 | ''' 14 | # Definition for singly-linked list. 15 | # class ListNode: 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution: 21 | def reorderList(self, head: ListNode) -> None: 22 | """ 23 | Do not return anything, modify head in-place instead. 24 | """ 25 | if not head: 26 | return 27 | 28 | slow = fast = head 29 | while fast and fast.next: 30 | slow = slow.next 31 | fast = fast.next.next 32 | 33 | last = None 34 | while slow: 35 | slow.next, last, slow = last, slow, slow.next 36 | 37 | cur = head 38 | while last.next: 39 | cur_next = cur.next 40 | last_next = last.next 41 | cur.next = last 42 | cur = cur_next 43 | last.next = cur 44 | last = last_next 45 | -------------------------------------------------------------------------------- /0144-Binary-Tree-Preorder-Traversal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the preorder traversal of its nodes' values. 3 | 4 | Example: 5 | 6 | Input: [1,null,2,3] 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | Output: [1,2,3] 14 | Follow up: Recursive solution is trivial, could you do it iteratively? 15 | ''' 16 | # Definition for a binary tree node. 17 | # class TreeNode: 18 | # def __init__(self, val=0, left=None, right=None): 19 | # self.val = val 20 | # self.left = left 21 | # self.right = right 22 | 23 | # Recursive Solution 24 | class Solution: 25 | def preorderTraversal(self, root: TreeNode) -> List[int]: 26 | res = [] 27 | self.recursive(root, res) 28 | return res 29 | 30 | def recursive(self, root, res): 31 | if not root: 32 | return 33 | res.append(root.val) 34 | self.recursive(root.left, res) 35 | self.recursive(root.right, res) 36 | 37 | # Iterative Solution 38 | class Solution: 39 | def preorderTraversal(self, root: TreeNode) -> List[int]: 40 | res = [] 41 | if not root: 42 | return res 43 | stack = [root] 44 | while stack: 45 | node = stack.pop() 46 | res.append(node.val) 47 | if node.right: 48 | stack.append(node.right) 49 | if node.left: 50 | stack.append(node.left) 51 | return res 52 | -------------------------------------------------------------------------------- /0151-Reverse-Words-in-a-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an input string, reverse the string word by word. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: "the sky is blue" 9 | Output: "blue is sky the" 10 | 11 | Example 2: 12 | 13 | Input: " hello world! " 14 | Output: "world! hello" 15 | Explanation: Your reversed string should not contain leading or trailing spaces. 16 | 17 | Example 3: 18 | 19 | Input: "a good example" 20 | Output: "example good a" 21 | Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 22 | 23 | 24 | 25 | Note: 26 | 27 | A word is defined as a sequence of non-space characters. 28 | Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. 29 | You need to reduce multiple spaces between two words to a single space in the reversed string. 30 | 31 | 32 | 33 | Follow up: 34 | 35 | For C programmers, try to solve it in-place in O(1) extra space. 36 | ''' 37 | class Solution: 38 | def reverseWords(self, s: str) -> str: 39 | s = list(s) 40 | self.reverseWord(s, 0, len(s) - 1) 41 | start = i = 0 42 | while i < len(s): 43 | if s[i] != ' ': 44 | if start != 0: 45 | s[start] = ' ' 46 | start += 1 47 | j = i 48 | while j < len(s) and s[j] != ' ': 49 | s[start] = s[j] 50 | j += 1 51 | start += 1 52 | self.reverseWord(s, start - (j - i), start - 1) 53 | i = j 54 | i += 1 55 | return ''.join(s[:start]) 56 | 57 | def reverseWord(self, s, start, end): 58 | while start < end: 59 | s[start], s[end] = s[end], s[start] 60 | start += 1 61 | end -= 1 62 | -------------------------------------------------------------------------------- /0152-Maximum-Product-Subarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | 4 | Example 1: 5 | 6 | Input: [2,3,-2,4] 7 | Output: 6 8 | Explanation: [2,3] has the largest product 6. 9 | 10 | Example 2: 11 | 12 | Input: [-2,0,-1] 13 | Output: 0 14 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 15 | ''' 16 | 17 | # Dynamic Programming 18 | 19 | class Solution: 20 | def maxProduct(self, nums: List[int]) -> int: 21 | res = max(nums) 22 | curMin = curMax = 1 23 | for num in nums: 24 | temp = curMax * num 25 | curMax = max(temp, num * curMin, num) 26 | curMin = min(temp, num * curMin, num) 27 | res = max(res, curMax, curMin) 28 | return res 29 | 30 | # Simlar approach, different steps 31 | 32 | class Solution: 33 | def maxProduct(self, nums: List[int]) -> int: 34 | min_prod = max_prod = res = nums[0] 35 | for i in range(1, len(nums)): 36 | if nums[i] < 0: 37 | min_prod, max_prod = max_prod, min_prod 38 | max_prod = nums[i] * max_prod if nums[i] * max_prod > nums[i] else nums[i] 39 | min_prod = nums[i] * min_prod if nums[i] * min_prod < nums[i] else nums[i] 40 | res = max_prod if max_prod > res else res 41 | return res 42 | -------------------------------------------------------------------------------- /0153-Find-Minimum-in-Rotated-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: 3 | 4 | [4,5,6,7,0,1,2] if it was rotated 4 times. 5 | [0,1,2,4,5,6,7] if it was rotated 7 times. 6 | Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. 7 | 8 | Given the sorted rotated array nums of unique elements, return the minimum element of this array. 9 | 10 | You must write an algorithm that runs in O(log n) time. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums = [3,4,5,1,2] 17 | Output: 1 18 | Explanation: The original array was [1,2,3,4,5] rotated 3 times. 19 | Example 2: 20 | 21 | Input: nums = [4,5,6,7,0,1,2] 22 | Output: 0 23 | Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. 24 | Example 3: 25 | 26 | Input: nums = [11,13,15,17] 27 | Output: 11 28 | Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 29 | 30 | 31 | Constraints: 32 | 33 | n == nums.length 34 | 1 <= n <= 5000 35 | -5000 <= nums[i] <= 5000 36 | All the integers of nums are unique. 37 | nums is sorted and rotated between 1 and n times. 38 | ''' 39 | 40 | # Binary Search 41 | 42 | class Solution: 43 | def findMin(self, nums: List[int]) -> int: 44 | left, right = 0, len(nums) - 1 45 | res = nums[0] 46 | 47 | while right >= left: 48 | if nums[left] < nums[right]: 49 | res = min(res, nums[left]) 50 | break 51 | 52 | mid = (right + left)//2 53 | res = min(res, nums[mid]) 54 | if nums[mid] >= nums[left]: 55 | left = mid + 1 56 | else: 57 | right = mid - 1 58 | return res -------------------------------------------------------------------------------- /0169-Majority-Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | 6 | Example 1: 7 | Input: [3,2,3] 8 | Output: 3 9 | 10 | Example 2: 11 | Input: [2,2,1,1,1,2,2] 12 | Output: 2 13 | ''' 14 | 15 | from typing import List 16 | 17 | # O(1) Space Complexity Solution 1 18 | 19 | class Solution: 20 | def majorityElement(self, nums: List[int]) -> int: 21 | res = count = 0 22 | for num in nums: 23 | if not count: 24 | res = num 25 | count += 1 26 | elif num == res: 27 | count += 1 28 | else: 29 | count -= 1 30 | return res 31 | 32 | # O(1) Space Complexity Solution 2 33 | 34 | class Solution: 35 | def majorityElement(self, nums: List[int]) -> int: 36 | res, count = nums[0], 1 37 | for i in range(1, len(nums)): 38 | count += 1 if nums[i] == res else -1 39 | if not count: 40 | res = nums[i] 41 | count += 1 42 | return res 43 | 44 | # Using Hash Table 45 | 46 | class Solution: 47 | def majorityElement(self, nums: List[int]) -> int: 48 | d = {} 49 | for num in nums: 50 | if num in d: 51 | d[num] += 1 52 | else: 53 | d[num] = 1 54 | return max(d, key = d.get) 55 | 56 | # Custom Input Check 57 | 58 | s = Solution() 59 | answer = s.majorityElement([1, 1, 1, 5]) # 1 60 | print(answer) -------------------------------------------------------------------------------- /0172-Factorial-Trailing-Zeroes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Example 1: 5 | 6 | Input: 3 7 | Output: 0 8 | Explanation: 3! = 6, no trailing zero. 9 | Example 2: 10 | 11 | Input: 5 12 | Output: 1 13 | Explanation: 5! = 120, one trailing zero. 14 | Note: Your solution should be in logarithmic time complexity. 15 | ''' 16 | class Solution: 17 | def trailingZeroes(self, n: int) -> int: 18 | 19 | res = 0 20 | 21 | while n: 22 | 23 | n //= 5 24 | res += n 25 | 26 | return res -------------------------------------------------------------------------------- /0189-Rotate-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array, rotate the array to the right by k steps, where k is non-negative. 3 | 4 | Example 1: 5 | 6 | Input: [1,2,3,4,5,6,7] and k = 3 7 | Output: [5,6,7,1,2,3,4] 8 | Explanation: 9 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 10 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 11 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 12 | 13 | Example 2: 14 | 15 | Input: [-1,-100,3,99] and k = 2 16 | Output: [3,99,-1,-100] 17 | Explanation: 18 | rotate 1 steps to the right: [99,-1,-100,3] 19 | rotate 2 steps to the right: [3,99,-1,-100] 20 | 21 | Note: 22 | 23 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 24 | Could you do it in-place with O(1) extra space? 25 | ''' 26 | class Solution: 27 | def rotate(self, nums: List[int], k: int) -> None: 28 | """ 29 | Do not return anything, modify nums in-place instead. 30 | """ 31 | n = len(nums) 32 | k %= n 33 | 34 | self.reverse(nums, 0, n - 1) 35 | self.reverse(nums, 0, k - 1) 36 | self.reverse(nums, k, n - 1) 37 | 38 | return nums 39 | 40 | def reverse(self, nums, start, end): 41 | 42 | while start < end: 43 | 44 | nums[start], nums[end] = nums[end], nums[start] 45 | 46 | start += 1 47 | end -= 1 48 | -------------------------------------------------------------------------------- /0191-Number-of-1-Bits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). 3 | 4 | Note: 5 | Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. 6 | In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3. 7 | 8 | 9 | Example 1: 10 | Input: n = 00000000000000000000000000001011 11 | Output: 3 12 | Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. 13 | 14 | Example 2: 15 | Input: n = 00000000000000000000000010000000 16 | Output: 1 17 | Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. 18 | 19 | Example 3: 20 | Input: n = 11111111111111111111111111111101 21 | Output: 31 22 | Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits. 23 | 24 | 25 | Constraints: 26 | The input must be a binary string of length 32. 27 | ''' 28 | 29 | # Bit Manipulation 30 | 31 | class Solution: 32 | def hammingWeight(self, n: int) -> int: 33 | res = 0 34 | while n: 35 | n &= n-1 36 | res += 1 37 | return res -------------------------------------------------------------------------------- /0198-House-Robber.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 3 | 4 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. 5 | 6 | Example 1: 7 | 8 | Input: [1,2,3,1] 9 | Output: 4 10 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 11 | Total amount you can rob = 1 + 3 = 4. 12 | 13 | Example 2: 14 | 15 | Input: [2,7,9,3,1] 16 | Output: 12 17 | Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 18 | Total amount you can rob = 2 + 9 + 1 = 12. 19 | ''' 20 | 21 | # Method 1 (Dynamic Programming) 22 | class Solution: 23 | def rob(self, nums: List[int]) -> int: 24 | 25 | if not nums: 26 | 27 | return 0 28 | 29 | dp = [None] * (len(nums) + 1) 30 | 31 | dp[0] = 0 32 | dp[1] = nums[0] 33 | 34 | for i in range(1, len(nums)): 35 | 36 | dp[i + 1] = max(dp[i], dp[i - 1] + nums[i]) 37 | 38 | return dp[-1] 39 | 40 | # Method 2 41 | class Solution: 42 | def rob(self, nums: List[int]) -> int: 43 | 44 | cur_included = max_cur_excluded = 0 45 | 46 | for cur in nums: 47 | 48 | cur_included, max_cur_excluded = cur + max_cur_excluded, max(max_cur_excluded, cur_included) 49 | 50 | return max(cur_included, max_cur_excluded) -------------------------------------------------------------------------------- /0202-Happy-Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an algorithm to determine if a number n is "happy". 3 | 4 | A happy number is a number defined by the following process: 5 | Starting with any positive integer, replace the number by the sum of the squares of its digits, 6 | and repeat the process until the number equals 1 (where it will stay), 7 | or it loops endlessly in a cycle which does not include 1. 8 | Those numbers for which this process ends in 1 are happy numbers. 9 | 10 | Return True if n is a happy number, and False if not. 11 | ''' 12 | class Solution: 13 | def isHappy(self, n: int) -> bool: 14 | 15 | seen = set() 16 | 17 | while n != 1: 18 | 19 | cur = n 20 | summ = 0 21 | 22 | while cur: 23 | 24 | summ += (cur % 10) ** 2 25 | cur //= 10 26 | 27 | if summ in seen: 28 | 29 | return False 30 | 31 | else: 32 | 33 | seen.add(summ) 34 | n = summ 35 | 36 | return True -------------------------------------------------------------------------------- /0203-Remove-Linked-List-Elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Remove all elements from a linked list of integers that have value val. 3 | 4 | Example: 5 | 6 | Input: 1->2->6->3->4->5->6, val = 6 7 | Output: 1->2->3->4->5 8 | ''' 9 | # Definition for singly-linked list. 10 | # class ListNode: 11 | # def __init__(self, x): 12 | # self.val = x 13 | # self.next = None 14 | 15 | #Time Complexity - O(n), Space Complexity - O(1) 16 | class Solution: 17 | def removeElements(self, head: ListNode, val: int) -> ListNode: 18 | zero_node = ListNode(0) 19 | zero_node.next = head 20 | cur_node = zero_node 21 | while cur_node.next: 22 | if cur_node.next.val == val: 23 | cur_node.next = cur_node.next.next 24 | else: 25 | cur_node = cur_node.next 26 | return zero_node.next 27 | -------------------------------------------------------------------------------- /0204-Count-Primes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Count the number of prime numbers less than a non-negative number, n. 3 | 4 | Example: 5 | 6 | Input: 10 7 | Output: 4 8 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 9 | ''' 10 | 11 | import math 12 | 13 | # Sieve of Eratosthenes Algorithm and For Loop 14 | 15 | class Solution: 16 | def countPrimes(self, n: int) -> int: 17 | 18 | if n < 2: 19 | return 0 20 | 21 | primes = [True] * n 22 | primes[0] = primes[1] = False 23 | 24 | for i in range(n): 25 | if primes[i]: 26 | for j in range(i*i, n, i): 27 | if j <= n: 28 | primes[j] = False 29 | 30 | return sum(primes) 31 | 32 | 33 | # Sieve of Eratosthenes Algorithm and While Loop 34 | 35 | class Solution: 36 | def countPrimes(self, n: int) -> int: 37 | if n < 2: 38 | return 0 39 | isPrime = [True for i in range(n)] 40 | isPrime[0] = isPrime[1] = False 41 | i = 2 42 | while n > i*i: 43 | if isPrime[i]: 44 | j = 2 45 | while i * j < n: 46 | isPrime[i*j] = False 47 | j += 1 48 | i += 1 49 | return sum(isPrime) 50 | 51 | # Sieve of Eratosthenes Algorithm For Loop and in-built math functions 52 | 53 | class Solution: 54 | def countPrimes(self, n: int) -> int: 55 | if n < 2: 56 | return 0 57 | isPrime = [True for i in range(n)] 58 | isPrime[0] = isPrime[1] = False 59 | for i in range(2, math.ceil(math.sqrt(n))): 60 | if isPrime[i]: 61 | for multiples in range(i*i, n, i): 62 | isPrime[multiples] = False 63 | return sum(isPrime) 64 | 65 | # Check Custom Input 66 | 67 | s = Solution() 68 | answer = s.countPrimes(12) # (2, 3, 5, 7, 11) => 5 69 | print(answer) -------------------------------------------------------------------------------- /0205-Isomorphic-Strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings s and t, determine if they are isomorphic. 3 | 4 | Two strings are isomorphic if the characters in s can be replaced to get t. 5 | 6 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 7 | 8 | Example 1: 9 | 10 | Input: s = "egg", t = "add" 11 | Output: true 12 | 13 | Example 2: 14 | 15 | Input: s = "foo", t = "bar" 16 | Output: false 17 | 18 | Example 3: 19 | 20 | Input: s = "paper", t = "title" 21 | Output: true 22 | 23 | Note: 24 | You may assume both s and t have the same length. 25 | ''' 26 | class Solution: 27 | def isIsomorphic(self, s: str, t: str) -> bool: 28 | 29 | table_s, table_t = {}, {} 30 | 31 | for i in range(len(s)): 32 | 33 | if (s[i] in table_s and table_s[s[i]] != t[i]) or (t[i] in table_t and table_t[t[i]] != s[i]): 34 | return False 35 | 36 | table_s[s[i]], table_t[t[i]] = t[i], s[i] 37 | 38 | return True -------------------------------------------------------------------------------- /0208-Implement-Trie-(Prefix-Tree).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement a trie with insert, search, and startsWith methods. 3 | 4 | Example: 5 | 6 | Trie trie = new Trie(); 7 | 8 | trie.insert("apple"); 9 | trie.search("apple"); // returns true 10 | trie.search("app"); // returns false 11 | trie.startsWith("app"); // returns true 12 | trie.insert("app"); 13 | trie.search("app"); // returns true 14 | Note: 15 | 16 | You may assume that all inputs are consist of lowercase letters a-z. 17 | All inputs are guaranteed to be non-empty strings. 18 | ''' 19 | class Trie: 20 | 21 | def __init__(self): 22 | """ 23 | Initialize your data structure here. 24 | """ 25 | self.dic = {} 26 | 27 | def insert(self, word): 28 | """ 29 | Inserts a word into the trie. 30 | :type word: str 31 | :rtype: void 32 | """ 33 | cur = self.dic 34 | for c in word: 35 | if c not in cur: 36 | cur[c] = {} 37 | cur = cur[c] 38 | cur['end'] = {} 39 | 40 | def search(self, word): 41 | """ 42 | Returns if the word is in the trie. 43 | :type word: str 44 | :rtype: bool 45 | """ 46 | cur = self.dic 47 | for c in word: 48 | if c in cur: 49 | cur = cur[c] 50 | else: 51 | return False 52 | if 'end' in cur: 53 | return True 54 | return False 55 | 56 | 57 | def startsWith(self, prefix): 58 | """ 59 | Returns if there is any word in the trie that starts with the given prefix. 60 | :type prefix: str 61 | :rtype: bool 62 | """ 63 | cur = self.dic 64 | for c in prefix: 65 | if c in cur: 66 | cur = cur[c] 67 | else: 68 | return False 69 | return True 70 | 71 | # Your Trie object will be instantiated and called as such: 72 | # obj = Trie() 73 | # obj.insert(word) 74 | # param_2 = obj.search(word) 75 | # param_3 = obj.startsWith(prefix) 76 | -------------------------------------------------------------------------------- /0217-Contains-Duplicate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, find if the array contains any duplicates. 3 | 4 | Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 5 | 6 | Example 1: 7 | Input: [1,2,3,1] 8 | Output: true 9 | 10 | Example 2: 11 | Input: [1,2,3,4] 12 | Output: false 13 | 14 | Example 3: 15 | Input: [1,1,1,3,3,4,3,2,4,2] 16 | Output: true 17 | ''' 18 | 19 | from typing import List 20 | 21 | # Using Hash Set 22 | 23 | class Solution: 24 | def containsDuplicate(self, nums: List[int]) -> bool: 25 | s = set() 26 | for num in nums: 27 | if num in s: 28 | return True 29 | s.add(num) 30 | return False 31 | 32 | # Using Hash Map 33 | 34 | class Solution: 35 | def containsDuplicate(self, nums: List[int]) -> bool: 36 | d = {} 37 | for num in nums: 38 | if num in d: 39 | return True 40 | d[num] = 1 41 | return False 42 | 43 | # Check Custom Input 44 | 45 | s = Solution() 46 | answer = s.containsDuplicate([2, 2, 1, 3]) # True 47 | print(answer) -------------------------------------------------------------------------------- /0219-Contains-Duplicate-II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | Example 1: 5 | Input: nums = [1,2,3,1], k = 3 6 | Output: true 7 | 8 | Example 2: 9 | Input: nums = [1,0,1,1], k = 1 10 | Output: true 11 | 12 | Example 3: 13 | Input: nums = [1,2,3,1,2,3], k = 2 14 | Output: false 15 | ''' 16 | class Solution: 17 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 18 | d = {} 19 | for idx, val in enumerate(nums): 20 | if val in d and idx - d[val] <= k: 21 | return True 22 | d[val] = idx 23 | return False 24 | -------------------------------------------------------------------------------- /0226-Invert-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Invert a binary tree. 3 | 4 | Example: 5 | 6 | Input: 7 | 8 | 4 9 | / \ 10 | 2 7 11 | / \ / \ 12 | 1 3 6 9 13 | Output: 14 | 15 | 4 16 | / \ 17 | 7 2 18 | / \ / \ 19 | 9 6 3 1 20 | Trivia: 21 | This problem was inspired by this original tweet by Max Howell: 22 | 23 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. 24 | ''' 25 | # Definition for a binary tree node. 26 | # class TreeNode: 27 | # def __init__(self, val=0, left=None, right=None): 28 | # self.val = val 29 | # self.left = left 30 | # self.right = right 31 | class Solution: 32 | def invertTree(self, root: TreeNode) -> TreeNode: 33 | if not root: 34 | return None 35 | queue = [] 36 | queue.append(root) 37 | while queue: 38 | cur = queue.pop(0) 39 | cur.left, cur.right = cur.right, cur.left 40 | if cur.left: 41 | queue.append(cur.left) 42 | if cur.right: 43 | queue.append(cur.right) 44 | return root 45 | -------------------------------------------------------------------------------- /0227-Basic-Calculator-II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement a basic calculator to evaluate a simple expression string. 3 | 4 | The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. 5 | 6 | Example 1: 7 | 8 | Input: "3+2*2" 9 | Output: 7 10 | Example 2: 11 | 12 | Input: " 3/2 " 13 | Output: 1 14 | Example 3: 15 | 16 | Input: " 3+5 / 2 " 17 | Output: 5 18 | Note: 19 | 20 | You may assume that the given expression is always valid. 21 | Do not use the eval built-in library function. 22 | ''' 23 | class Solution: 24 | def calculate(self, s: str) -> int: 25 | num, stack, sign = 0, [], "+" 26 | 27 | for i in range(len(s)): 28 | if s[i].isdigit(): 29 | num = num * 10 + int(s[i]) 30 | 31 | if s[i] in "+-*/" or i == len(s) - 1: 32 | 33 | if sign == "+": 34 | stack.append(num) 35 | elif sign == "-": 36 | stack.append(-num) 37 | elif sign == "*": 38 | stack.append(stack.pop()*num) 39 | else: 40 | stack.append(int(stack.pop()/num)) 41 | 42 | num = 0 43 | sign = s[i] 44 | 45 | return sum(stack) 46 | -------------------------------------------------------------------------------- /0230-Kth-Smallest-Element-in-a-BST.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: root = [3,1,4,null,2], k = 1 9 | 3 10 | / \ 11 | 1 4 12 | \ 13 | 2 14 | Output: 1 15 | Example 2: 16 | 17 | Input: root = [5,3,6,2,4,null,null,1], k = 3 18 | 5 19 | / \ 20 | 3 6 21 | / \ 22 | 2 4 23 | / 24 | 1 25 | Output: 3 26 | Follow up: 27 | What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 28 | 29 | 30 | 31 | Constraints: 32 | 33 | The number of elements of the BST is between 1 to 10^4. 34 | You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 35 | ''' 36 | # Definition for a binary tree node. 37 | # class TreeNode: 38 | # def __init__(self, val=0, left=None, right=None): 39 | # self.val = val 40 | # self.left = left 41 | # self.right = right 42 | class Solution(object): 43 | def kthSmallest(self, root, k): 44 | stack = [] 45 | while True: 46 | while root: 47 | stack.append(root) 48 | root = root.left 49 | root = stack.pop() 50 | k -= 1 51 | if not k: 52 | return root.val 53 | root = root.right 54 | -------------------------------------------------------------------------------- /0231-Power-of-Two.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer, write a function to determine if it is a power of two. 3 | 4 | Example 1: 5 | 6 | Input: 1 7 | Output: true 8 | Explanation: 20 = 1 9 | Example 2: 10 | 11 | Input: 16 12 | Output: true 13 | Explanation: 24 = 16 14 | Example 3: 15 | 16 | Input: 218 17 | Output: false 18 | ''' 19 | class Solution(object): 20 | def isPowerOfTwo(self, n): 21 | return n > 0 and not(n & n-1) 22 | -------------------------------------------------------------------------------- /0234-Palindrome-Linked-List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list, determine if it is a palindrome. 3 | 4 | Example 1: 5 | 6 | Input: 1->2 7 | Output: false 8 | Example 2: 9 | 10 | Input: 1->2->2->1 11 | Output: true 12 | Follow up: 13 | Could you do it in O(n) time and O(1) space? 14 | ''' 15 | # Definition for singly-linked list. 16 | # class ListNode: 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.next = None 20 | 21 | class Solution: 22 | def isPalindrome(self, head: ListNode) -> bool: 23 | if not head or not head.next: 24 | return True 25 | 26 | slow = fast = prev_slow = head 27 | 28 | mid = self.midNode(slow, fast, prev_slow) 29 | 30 | second_head = self.reverse(mid) 31 | 32 | while head: 33 | if head.val != second_head.val: 34 | return False 35 | head, second_head = head.next, second_head.next 36 | return True 37 | 38 | def midNode(self, slow, fast, prev_slow): 39 | while fast and fast.next: 40 | prev_slow = slow 41 | slow = slow.next 42 | fast = fast.next.next 43 | if fast != None: 44 | slow = slow.next 45 | prev_slow.next = None 46 | return slow 47 | 48 | def reverse(self, head_node): 49 | prev = None 50 | while head_node: 51 | head_node.next, prev, head_node = prev, head_node, head_node.next 52 | return prev 53 | -------------------------------------------------------------------------------- /0237-Delete-Node-in-a-Linked-List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 3 | 4 | Given linked list -- head = [4,5,1,9], which looks like following: 5 | 6 | 4 -> 5 -> 1 -> 9 7 | 8 | Example 1: 9 | 10 | Input: head = [4,5,1,9], node = 5 11 | Output: [4,1,9] 12 | Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. 13 | Example 2: 14 | 15 | Input: head = [4,5,1,9], node = 1 16 | Output: [4,5,9] 17 | Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. 18 | 19 | 20 | Note: 21 | 22 | The linked list will have at least two elements. 23 | All of the nodes' values will be unique. 24 | The given node will not be the tail and it will always be a valid node of the linked list. 25 | Do not return anything from your function. 26 | ''' 27 | 28 | # Solution by modifying in Place 29 | 30 | # Definition for singly-linked list. 31 | # class ListNode: 32 | # def __init__(self, x): 33 | # self.val = x 34 | # self.next = None 35 | 36 | class Solution: 37 | def deleteNode(self, node): 38 | node.val, node.next = node.next.val, node.next.next 39 | -------------------------------------------------------------------------------- /0238-Product-of-Array-Except-Self.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Example: 5 | 6 | Input: [1,2,3,4] 7 | Output: [24,12,8,6] 8 | 9 | Note: Please solve it without division and in O(n). 10 | 11 | Follow up: 12 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 13 | ''' 14 | 15 | # Using Postfix and Prefix Product 16 | 17 | class Solution: 18 | def productExceptSelf(self, nums: List[int]) -> List[int]: 19 | res = [1]*len(nums) 20 | prefix = 1 21 | for i in range(len(nums)): 22 | res[i] = prefix 23 | prefix *= nums[i] 24 | postfix = 1 25 | for i in range(len(nums) - 1, -1, -1): 26 | res[i] *= postfix 27 | postfix *= nums[i] 28 | return res 29 | 30 | # Similar method with small changes 31 | 32 | class Solution: 33 | def productExceptSelf(self, nums: List[int]) -> List[int]: 34 | res = [1] * (len(nums)) 35 | for i in range(1, len(nums)): 36 | res[i] = res[i-1] * nums[i-1] 37 | prod = 1 38 | for i in range(len(nums) - 1, -1 ,-1): 39 | res[i] *= prod 40 | prod *= nums[i] 41 | return res 42 | -------------------------------------------------------------------------------- /0242-Valid-Anagram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings s and t , write a function to determine if t is an anagram of s. 3 | 4 | Example 1: 5 | 6 | Input: s = "anagram", t = "nagaram" 7 | Output: true 8 | 9 | Example 2: 10 | 11 | Input: s = "rat", t = "car" 12 | Output: false 13 | 14 | Note: 15 | You may assume the string contains only lowercase alphabets. 16 | 17 | Follow up: 18 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 19 | ''' 20 | # Time Complexity: O(n) 21 | # Space Complexity: O(1) 22 | class Solution: 23 | def isAnagram(self, s: str, t: str) -> bool: 24 | 25 | if len(s) != len(t): 26 | return False 27 | 28 | check = {} 29 | 30 | for letter in s: 31 | 32 | check[letter] = check.get(letter, 0) + 1 33 | 34 | for letter in t: 35 | 36 | if check.get(letter, 0) <= 0: 37 | return False 38 | check[letter] -= 1 39 | 40 | return True -------------------------------------------------------------------------------- /0258-Add-Digits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | 4 | Example: 5 | 6 | Input: 38 7 | Output: 2 8 | Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 9 | Since 2 has only one digit, return it. 10 | 11 | Follow up: 12 | Could you do it without any loop/recursion in O(1) runtime? 13 | ''' 14 | class Solution: 15 | def addDigits(self, num: int) -> int: 16 | if num < 10: 17 | return num 18 | return num % 9 if num % 9 != 0 else 9 19 | -------------------------------------------------------------------------------- /0268-Missing-Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 3 | 4 | Example 1: 5 | 6 | Input: [3,0,1] 7 | Output: 2 8 | Example 2: 9 | 10 | Input: [9,6,4,2,3,5,7,0,1] 11 | Output: 8 12 | Note: 13 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 14 | ''' 15 | 16 | from typing import List 17 | 18 | # Using Math Formula to find sum 19 | 20 | class Solution: 21 | def missingNumber(self, nums: List[int]) -> int: 22 | n = len(nums) 23 | total = n*(n+1)//2 24 | for n in nums: 25 | total -= n 26 | return total 27 | 28 | # Using Bit Manipulation 29 | 30 | class Solution: 31 | def missingNumber(self, nums: List[int]) -> int: 32 | res = 0 33 | for i in range(len(nums) + 1): 34 | res ^= i 35 | if i < len(nums): 36 | res ^= nums[i] 37 | return res 38 | 39 | # Using Math Formula and in-built sum function 40 | 41 | class Solution: 42 | def missingNumber(self, nums: List[int]) -> int: 43 | current_sum = sum(nums) 44 | intended_sum = len(nums) * (len(nums) + 1) // 2 45 | return intended_sum - current_sum 46 | 47 | # Check Custom Input 48 | 49 | s = Solution() 50 | answer = s.missingNumber([0, 3, 1, 2, 5]) # 4 51 | print(answer) -------------------------------------------------------------------------------- /0278-First-Bad-Version.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 3 | 4 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 5 | 6 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 7 | 8 | Example: 9 | 10 | Given n = 5, and version = 4 is the first bad version. 11 | 12 | call isBadVersion(3) -> false 13 | call isBadVersion(5) -> true 14 | call isBadVersion(4) -> true 15 | 16 | Then 4 is the first bad version. 17 | ''' 18 | 19 | # The isBadVersion API is already defined for you. 20 | # @param version, an integer 21 | # @return an integer 22 | # def isBadVersion(version): 23 | 24 | def isBadVersion(version): 25 | return version >= 3 # First Bad Version 26 | 27 | class Solution: 28 | 29 | def firstBadVersion(self, n): 30 | """ 31 | :type n: int 32 | :rtype: int 33 | """ 34 | low, high = 1, n 35 | while low < high: 36 | mid = (low + high) // 2 37 | if isBadVersion(mid): 38 | high = mid 39 | else: 40 | low = mid + 1 41 | 42 | return high 43 | 44 | s = Solution() 45 | answer = s.firstBadVersion(10) # 3 46 | print(answer) -------------------------------------------------------------------------------- /0283-Move-Zeroes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/move-zeroes/description/ 3 | 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 5 | 6 | Example: 7 | Input: [0,1,0,3,12] 8 | Output: [1,3,12,0,0] 9 | 10 | Note: 11 | You must do this in-place without making a copy of the array. 12 | Minimize the total number of operations. 13 | ''' 14 | 15 | from typing import List 16 | 17 | class Solution: 18 | def moveZeroes(self, nums: List[int]) -> None: 19 | """ 20 | Do not return anything, modify nums in-place instead. 21 | """ 22 | zero = 0 23 | for i in range(len(nums)): 24 | if nums[i]: 25 | nums[i], nums[zero] = nums[zero], nums[i] 26 | zero += 1 27 | print(nums) 28 | 29 | class Solution: 30 | def moveZeroes(self, nums: List[int]) -> None: 31 | non_zero = 0 32 | for i in range(len(nums)): 33 | if nums[i] != 0: 34 | nums[non_zero] = nums[i] 35 | non_zero += 1 36 | for i in range(non_zero, len(nums)): 37 | nums[i] = 0 38 | print(nums) 39 | 40 | # Checking with Custom Input 41 | s = Solution() 42 | s.moveZeroes([0, 2, 0, 1, 4]) # [2, 1, 4, 0, 0] -------------------------------------------------------------------------------- /0287-Find-the-Duplicate-Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 3 | 4 | Example 1: 5 | 6 | Input: [1,3,4,2,2] 7 | Output: 2 8 | 9 | Example 2: 10 | 11 | Input: [3,1,3,4,2] 12 | Output: 3 13 | 14 | Note: 15 | 16 | You must not modify the array (assume the array is read only). 17 | You must use only constant, O(1) extra space. 18 | Your runtime complexity should be less than O(n2). 19 | There is only one duplicate number in the array, but it could be repeated more than once. 20 | ''' 21 | class Solution: 22 | def findDuplicate(self, nums: List[int]) -> int: 23 | tortoise, hare = nums[0], nums[0] 24 | while True: 25 | tortoise, hare = nums[tortoise], nums[nums[hare]] 26 | if tortoise == hare: 27 | break 28 | 29 | ptr1, ptr2 = nums[0], tortoise 30 | while ptr1 != ptr2: 31 | ptr1, ptr2 = nums[ptr1], nums[ptr2] 32 | 33 | return ptr1 34 | -------------------------------------------------------------------------------- /0292-Nim-Game.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/nim-game/ 3 | 4 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 5 | 6 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 7 | 8 | Example: 9 | Input: 4 10 | Output: false 11 | Explanation: If there are 4 stones in the heap, then you will never win the game; 12 | No matter 1, 2, or 3 stones you remove, the last stone will always be 13 | removed by your friend. 14 | ''' 15 | class Solution: 16 | def canWinNim(self, n: int) -> bool: 17 | return n%4!=0 18 | -------------------------------------------------------------------------------- /0322-Coin-Change.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 3 | 4 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 5 | 6 | You may assume that you have an infinite number of each kind of coin. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: coins = [1,2,5], amount = 11 13 | Output: 3 14 | Explanation: 11 = 5 + 5 + 1 15 | Example 2: 16 | 17 | Input: coins = [2], amount = 3 18 | Output: -1 19 | Example 3: 20 | 21 | Input: coins = [1], amount = 0 22 | Output: 0 23 | Example 4: 24 | 25 | Input: coins = [1], amount = 1 26 | Output: 1 27 | Example 5: 28 | 29 | Input: coins = [1], amount = 2 30 | Output: 2 31 | 32 | 33 | Constraints: 34 | 35 | 1 <= coins.length <= 12 36 | 1 <= coins[i] <= 231 - 1 37 | 0 <= amount <= 104 38 | ''' 39 | 40 | # Using Dynamic Programming 41 | 42 | class Solution: 43 | def coinChange(self, coins: List[int], amount: int) -> int: 44 | dp = [amount + 1 for _ in range(amount + 1)] 45 | dp[0] = 0 46 | for i in range(amount + 1): 47 | for j in range(len(coins)): 48 | if coins[j] <= i: 49 | dp[i] = min(dp[i], 1 + dp[i - coins[j]]) 50 | return -1 if dp[amount] > amount else dp[amount] 51 | 52 | # Slightly optimised for average case 53 | 54 | class Solution: 55 | def coinChange(self, coins: List[int], amount: int) -> int: 56 | coins.sort() 57 | dp = [amount + 1 for _ in range(amount + 1)] 58 | dp[0] = 0 59 | for i in range(amount + 1): 60 | for j in range(len(coins)): 61 | if coins[j] <= i: 62 | dp[i] = min(dp[i], 1 + dp[i - coins[j]]) 63 | else: 64 | break 65 | return -1 if dp[amount] > amount else dp[amount] -------------------------------------------------------------------------------- /0328-Odd-Even-Linked-List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 3 | 4 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 5 | 6 | Example 1: 7 | 8 | Input: 1->2->3->4->5->NULL 9 | Output: 1->3->5->2->4->NULL 10 | 11 | Example 2: 12 | 13 | Input: 2->1->3->5->6->4->7->NULL 14 | Output: 2->3->6->7->1->5->4->NULL 15 | 16 | Note: 17 | 18 | The relative order inside both the even and odd groups should remain as it was in the input. 19 | The first node is considered odd, the second node even and so on ... 20 | 21 | ''' 22 | # Definition for singly-linked list. 23 | 24 | class ListNode: 25 | def __init__(self, val=0, next=None): 26 | self.val = val 27 | self.next = next 28 | 29 | class Solution: 30 | def oddEvenList(self, head: ListNode) -> ListNode: 31 | if not head: 32 | return head 33 | 34 | odd = head 35 | even = odd.next 36 | evenList = even 37 | 38 | while even and even.next: 39 | odd.next = even.next 40 | odd = odd.next 41 | 42 | even.next = odd.next 43 | even = even.next 44 | 45 | odd.next = evenList 46 | 47 | return head 48 | 49 | # Custom Input Check 50 | 51 | node1 = ListNode(10) 52 | node2 = ListNode(20) 53 | node3 = ListNode(30) 54 | node4 = ListNode(40) 55 | node5 = ListNode(50) 56 | 57 | node1.next = node2 58 | node2.next = node3 59 | node3.next = node4 60 | node4.next = node5 61 | 62 | s = Solution() 63 | 64 | answer = s.oddEvenList(node1) # 10 => 30 => 50 => 20 => 40 65 | 66 | while answer: 67 | print(answer) 68 | answer = answer.next -------------------------------------------------------------------------------- /0344-Reverse-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that reverses a string. The input string is given as an array of characters char[]. 3 | 4 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | You may assume all the characters consist of printable ascii characters. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: ["h","e","l","l","o"] 13 | Output: ["o","l","l","e","h"] 14 | Example 2: 15 | 16 | Input: ["H","a","n","n","a","h"] 17 | Output: ["h","a","n","n","a","H"] 18 | ''' 19 | 20 | # Without returning anything and modifying in place 21 | 22 | class Solution: 23 | def reverseString(self, s: List[str]) -> None: 24 | start, end = 0, len(s) - 1 25 | while start < end: 26 | s[start], s[end] = s[end], s[start] 27 | start += 1 28 | end -= 1 29 | -------------------------------------------------------------------------------- /0345-Reverse-Vowels-of-a-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that takes a string as input and reverse only the vowels of a string. 3 | 4 | Example 1: 5 | 6 | Input: "hello" 7 | Output: "holle" 8 | 9 | Example 2: 10 | 11 | Input: "leetcode" 12 | Output: "leotcede" 13 | 14 | Note: 15 | The vowels does not include the letter "y". 16 | ''' 17 | class Solution: 18 | def reverseVowels(self, s: str) -> str: 19 | vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} 20 | string = list(s) 21 | start, end = 0, len(s) - 1 22 | while start <= end: 23 | if string[start] in vowels: 24 | if string[end] in vowels: 25 | string[start], string[end] = string[end], string[start] 26 | start += 1 27 | end -= 1 28 | else: 29 | start += 1 30 | return ''.join(string) 31 | -------------------------------------------------------------------------------- /0347-Top-K-Frequent-Elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | Example 1: 5 | 6 | Input: nums = [1,1,1,2,2,3], k = 2 7 | Output: [1,2] 8 | 9 | Example 2: 10 | 11 | Input: nums = [1], k = 1 12 | Output: [1] 13 | 14 | Note: 15 | 16 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 17 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 18 | ''' 19 | class Solution: 20 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 21 | count = {} 22 | for num in nums: 23 | count[num] = count.get(num, 0) + 1 24 | return heapq.nlargest(k, count.keys(), key = count.get) 25 | -------------------------------------------------------------------------------- /0349-Intersection-Of-Two-Arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/intersection-of-two-arrays/ 3 | 4 | Given two arrays, write a function to compute their intersection. 5 | 6 | Example 1: 7 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 8 | Output: [2] 9 | 10 | Example 2: 11 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 12 | Output: [9,4] 13 | 14 | Note: 15 | Each element in the result must be unique. 16 | The result can be in any order. 17 | ''' 18 | class Solution: 19 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 20 | nums = set(nums1) 21 | res = [] 22 | for i in nums2: 23 | if i in nums: 24 | res.append(i) 25 | nums.remove(i) 26 | return res 27 | -------------------------------------------------------------------------------- /0350-Intersection-of-Two-Arrays-II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | Example 1: 5 | 6 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 7 | Output: [2,2] 8 | Example 2: 9 | 10 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 11 | Output: [4,9] 12 | Note: 13 | 14 | Each element in the result should appear as many times as it shows in both arrays. 15 | The result can be in any order. 16 | Follow up: 17 | 18 | What if the given array is already sorted? How would you optimize your algorithm? 19 | What if nums1's size is small compared to nums2's size? Which algorithm is better? 20 | What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? 21 | ''' 22 | class Solution: 23 | def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 24 | d = {} 25 | res = [] 26 | for num in nums1: 27 | d[num] = d.get(num, 0) + 1 28 | 29 | for num in nums2: 30 | if num in d and d[num]: 31 | res.append(num) 32 | d[num] -= 1 33 | 34 | return res 35 | 36 | ''' 37 | Follow up 1: 38 | If both arrays are sorted, use two pointers to iterate. 39 | 40 | Follow up 2: 41 | Make a hashmap from numbers in nums1 and loop through nums2 to find the intersection. 42 | 43 | Follow up 3: 44 | If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections. 45 | If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read 2 elements from each array at a time in memory, record intersections. 46 | ''' 47 | -------------------------------------------------------------------------------- /0367-Valid-Perfect-Square.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 3 | 4 | Note: Do not use any built-in library function such as sqrt. 5 | 6 | Example 1: 7 | 8 | Input: 16 9 | Output: true 10 | Example 2: 11 | 12 | Input: 14 13 | Output: false 14 | ''' 15 | class Solution: 16 | def isPerfectSquare(self, num: int) -> bool: 17 | start, end = 0, num 18 | while start <= end: 19 | mid = (start+end)//2 20 | square = mid*mid 21 | if square == num: 22 | return True 23 | elif square > num: 24 | end = mid - 1 25 | else: 26 | start = mid + 1 27 | return False 28 | -------------------------------------------------------------------------------- /0371-Sum-of-Two-Integers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 3 | 4 | Example 1: 5 | 6 | Input: a = 1, b = 2 7 | Output: 3 8 | Example 2: 9 | 10 | Input: a = -2, b = 3 11 | Output: 1 12 | ''' 13 | class Solution: 14 | def getSum(self, a: int, b: int) -> int: 15 | 16 | mask = 0xffffffff 17 | 18 | while (b & mask) > 0: 19 | 20 | carry = (a & b) << 1 21 | a ^= b 22 | b = carry 23 | 24 | return a & mask if b > 0 else a -------------------------------------------------------------------------------- /0373-Find-K-Pairs-with-Smallest-Sums.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. 3 | 4 | Define a pair (u,v) which consists of one element from the first array and one element from the second array. 5 | 6 | Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums. 7 | 8 | Example 1: 9 | 10 | Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 11 | Output: [[1,2],[1,4],[1,6]] 12 | Explanation: The first 3 pairs are returned from the sequence: 13 | [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] 14 | 15 | Example 2: 16 | 17 | Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 18 | Output: [1,1],[1,1] 19 | Explanation: The first 2 pairs are returned from the sequence: 20 | [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] 21 | 22 | Example 3: 23 | 24 | Input: nums1 = [1,2], nums2 = [3], k = 3 25 | Output: [1,3],[2,3] 26 | Explanation: All possible pairs are returned from the sequence: [1,3],[2,3] 27 | ''' 28 | class Solution: 29 | def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: 30 | res = [] 31 | if nums1 and nums2: 32 | queue = [(nums1[i] + nums2[0], (i, 0)) for i in range(len(nums1))] 33 | while len(res) < k and queue: 34 | summ, (i, j) = heapq.heappop(queue) 35 | res.append([nums1[i], nums2[j]]) 36 | if j + 1 < len(nums2): 37 | heapq.heappush(queue, (nums1[i] + nums2[j + 1], (i, j + 1))) 38 | return res 39 | -------------------------------------------------------------------------------- /0383-Ransom-Note.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 3 | 4 | Each letter in the magazine string can only be used once in your ransom note. 5 | 6 | Note: 7 | You may assume that both strings contain only lowercase letters. 8 | 9 | canConstruct("a", "b") -> false 10 | canConstruct("aa", "ab") -> false 11 | canConstruct("aa", "aab") -> true 12 | ''' 13 | class Solution: 14 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 15 | a = [0]*26 16 | for note in magazine: 17 | a[ord(note) - ord('a')] += 1 18 | 19 | for note in ransomNote: 20 | index = ord(note) - ord('a') 21 | a[index] -= 1 22 | if a[index] < 0: 23 | return False 24 | 25 | return True 26 | -------------------------------------------------------------------------------- /0387-First-Unique-Characcter-in-a-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 3 | 4 | Examples: 5 | 6 | s = "leetcode" 7 | return 0. 8 | 9 | s = "loveleetcode", 10 | return 2. 11 | 12 | Note: You may assume the string contain only lowercase letters. 13 | ''' 14 | class Solution: 15 | def firstUniqChar(self, s: str) -> int: 16 | count = {} 17 | for ch in s: 18 | count[ch] = count.get(ch, 0) + 1 19 | for idx, ch in enumerate(s): 20 | if ch in count and count[ch] == 1: 21 | return idx 22 | return -1 23 | -------------------------------------------------------------------------------- /0392-Is-Subsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s and a string t, check if s is subsequence of t. 3 | 4 | You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). 5 | 6 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not). 7 | 8 | Example 1: 9 | s = "abc", t = "ahbgdc" 10 | 11 | Return true. 12 | 13 | Example 2: 14 | s = "axc", t = "ahbgdc" 15 | 16 | Return false. 17 | 18 | Follow up: 19 | If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? 20 | ''' 21 | class Solution: 22 | def isSubsequence(self, s: str, t: str) -> bool: 23 | s_index = t_index = 0 24 | 25 | while s_index < len(s) and t_index < len(t): 26 | if s[s_index] == t[t_index]: 27 | s_index += 1 28 | t_index += 1 29 | 30 | return s_index == len(s) 31 | -------------------------------------------------------------------------------- /0402-Remove-K-Digits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. 3 | 4 | Note: 5 | The length of num is less than 10002 and will be ≥ k. 6 | The given num does not contain any leading zero. 7 | Example 1: 8 | 9 | Input: num = "1432219", k = 3 10 | Output: "1219" 11 | Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. 12 | Example 2: 13 | 14 | Input: num = "10200", k = 1 15 | Output: "200" 16 | Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. 17 | Example 3: 18 | 19 | Input: num = "10", k = 2 20 | Output: "0" 21 | Explanation: Remove all the digits from the number and it is left with nothing which is 0. 22 | ''' 23 | class Solution: 24 | def removeKdigits(self, num, k): 25 | stack = [] 26 | for i in range(len(num)): 27 | while stack and k: 28 | if num[i] < stack[-1]: 29 | k -= 1 30 | stack.pop() 31 | else: 32 | break 33 | stack.append(num[i]) 34 | 35 | while k: 36 | stack.pop() 37 | k -= 1 38 | 39 | while stack: 40 | if stack[0] == '0': 41 | stack = stack[1:] 42 | else: 43 | break 44 | 45 | return ''.join(stack) or '0' 46 | -------------------------------------------------------------------------------- /0412-Fizz-Buzz.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/fizz-buzz/ 3 | 4 | Write a program that outputs the string representation of numbers from 1 to n. 5 | 6 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 7 | 8 | Example: 9 | 10 | n = 15, 11 | 12 | Return: 13 | [ 14 | "1", 15 | "2", 16 | "Fizz", 17 | "4", 18 | "Buzz", 19 | "Fizz", 20 | "7", 21 | "8", 22 | "Fizz", 23 | "Buzz", 24 | "11", 25 | "Fizz", 26 | "13", 27 | "14", 28 | "FizzBuzz" 29 | ] 30 | ''' 31 | class Solution: 32 | def fizzBuzz(self, n: int) -> List[str]: 33 | arr = [] 34 | for i in range(1,n+1): 35 | if (i%3==0 and i%5==0): 36 | arr.append("FizzBuzz") 37 | elif(i%3==0): 38 | arr.append("Fizz") 39 | elif(i%5==0): 40 | arr.append("Buzz") 41 | else: 42 | arr.append(str(i)) 43 | return arr 44 | -------------------------------------------------------------------------------- /0443-String-Compression.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of characters, compress it in-place. 3 | 4 | The length after compression must always be smaller than or equal to the original array. 5 | 6 | Every element of the array should be a character (not int) of length 1. 7 | 8 | After you are done modifying the input array in-place, return the new length of the array. 9 | 10 | 11 | Follow up: 12 | Could you solve it using only O(1) extra space? 13 | 14 | 15 | Example 1: 16 | 17 | Input: 18 | ["a","a","b","b","c","c","c"] 19 | 20 | Output: 21 | Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] 22 | 23 | Explanation: 24 | "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". 25 | 26 | 27 | 28 | Example 2: 29 | 30 | Input: 31 | ["a"] 32 | 33 | Output: 34 | Return 1, and the first 1 characters of the input array should be: ["a"] 35 | 36 | Explanation: 37 | Nothing is replaced. 38 | 39 | 40 | 41 | Example 3: 42 | 43 | Input: 44 | ["a","b","b","b","b","b","b","b","b","b","b","b","b"] 45 | 46 | Output: 47 | Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. 48 | 49 | Explanation: 50 | Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". 51 | Notice each digit has it's own entry in the array. 52 | 53 | 54 | 55 | Note: 56 | 57 | All characters have an ASCII value in [35, 126]. 58 | 1 <= len(chars) <= 1000. 59 | ''' 60 | # Time Complexity: O(n) 61 | # Space Complexity: O(1) 62 | class Solution: 63 | def compress(self, chars: List[str]) -> int: 64 | index = i = 0 65 | while i < len(chars): 66 | cur, length = chars[i], 1 67 | while (i + 1) < len(chars) and cur == chars[i + 1]: 68 | length, i = length + 1, i + 1 69 | chars[index] = cur 70 | if length > 1: 71 | length = str(length) 72 | for j, v in enumerate(length): 73 | chars[index + j + 1] = v 74 | index += len(length) 75 | index, i = index + 1, i + 1 76 | return index 77 | -------------------------------------------------------------------------------- /0448-Find-All-Numbers-Disappeared-in-an-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements of [1, n] inclusive that do not appear in this array. 5 | 6 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 7 | 8 | Example: 9 | 10 | Input: 11 | [4,3,2,7,8,2,3,1] 12 | 13 | Output: 14 | [5,6] 15 | ''' 16 | class Solution: 17 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 18 | 19 | n = len(nums) 20 | 21 | for idx, val in enumerate(nums): 22 | nums[(val - 1) % n] += n 23 | return [idx + 1 for idx, val in enumerate(nums) if val <= n] -------------------------------------------------------------------------------- /0451-Sort-Characters-By-Frequency.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, sort it in decreasing order based on the frequency of characters. 3 | 4 | Example 1: 5 | 6 | Input: 7 | "tree" 8 | 9 | Output: 10 | "eert" 11 | 12 | Explanation: 13 | 'e' appears twice while 'r' and 't' both appear once. 14 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. 15 | Example 2: 16 | 17 | Input: 18 | "cccaaa" 19 | 20 | Output: 21 | "cccaaa" 22 | 23 | Explanation: 24 | Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. 25 | Note that "cacaca" is incorrect, as the same characters must be together. 26 | Example 3: 27 | 28 | Input: 29 | "Aabb" 30 | 31 | Output: 32 | "bbAa" 33 | 34 | Explanation: 35 | "bbaA" is also a valid answer, but "Aabb" is incorrect. 36 | Note that 'A' and 'a' are treated as two different characters. 37 | ''' 38 | class Solution: 39 | def frequencySort(self, s: str) -> str: 40 | d1, d2 = {}, {} 41 | for c in s: 42 | d1[c] = d1.get(c, 0) + 1 43 | 44 | for k,v in d1.items(): 45 | d2[v] = d2.get(v, '') + k*v 46 | 47 | res = '' 48 | for i in range(len(s), -1, -1): 49 | if i in d2: 50 | res += d2[i] 51 | return res 52 | -------------------------------------------------------------------------------- /0463-Island-Perimeter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. 3 | 4 | Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). 5 | 6 | The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. 7 | 8 | 9 | 10 | Example: 11 | 12 | Input: 13 | [[0,1,0,0], 14 | [1,1,1,0], 15 | [0,1,0,0], 16 | [1,1,0,0]] 17 | 18 | Output: 16 19 | ''' 20 | class Solution: 21 | def islandPerimeter(self, grid: List[List[int]]) -> int: 22 | h, v = len(grid), len(grid[0]) 23 | res = 0 24 | 25 | for i in range(h): 26 | for j in range(v): 27 | if grid[i][j]: 28 | res += 4 29 | if i < h - 1 and grid[i + 1][j]: 30 | res -= 2 31 | if j < v - 1 and grid[i][j + 1]: 32 | res -= 2 33 | 34 | return res 35 | -------------------------------------------------------------------------------- /0476-Number-Complement.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: 5 9 | Output: 2 10 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 11 | 12 | 13 | Example 2: 14 | 15 | Input: 1 16 | Output: 0 17 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 18 | 19 | 20 | Note: 21 | 22 | The given integer is guaranteed to fit within the range of a 32-bit signed integer. 23 | You could assume no leading zero bit in the integer’s binary representation. 24 | This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/ 25 | ''' 26 | class Solution: 27 | def findComplement(self, num: int) -> int: 28 | return num ^ ((1 << len(bin(num)) - 2) - 1) 29 | -------------------------------------------------------------------------------- /0496-Next-Greater-Element-I.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. 3 | 4 | The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. 5 | 6 | Example 1: 7 | 8 | Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. 9 | Output: [-1,3,-1] 10 | Explanation: 11 | For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. 12 | For number 1 in the first array, the next greater number for it in the second array is 3. 13 | For number 2 in the first array, there is no next greater number for it in the second array, so output -1. 14 | 15 | Example 2: 16 | 17 | Input: nums1 = [2,4], nums2 = [1,2,3,4]. 18 | Output: [3,-1] 19 | Explanation: 20 | For number 2 in the first array, the next greater number for it in the second array is 3. 21 | For number 4 in the first array, there is no next greater number for it in the second array, so output -1. 22 | 23 | Note: 24 | 25 | All elements in nums1 and nums2 are unique. 26 | The length of both nums1 and nums2 would not exceed 1000. 27 | ''' 28 | #Time Complexity: O(n) 29 | #Space Complexity: O(n) 30 | class Solution: 31 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 32 | d = {} 33 | stack = [] 34 | for i in range(len(nums2)): 35 | while stack and stack[-1] < nums2[i]: 36 | d[stack.pop()] = nums2[i] 37 | stack.append(nums2[i]) 38 | return [d.get(n, -1) for n in nums1] 39 | -------------------------------------------------------------------------------- /0500-Keyboard-Row.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard. 3 | 4 | Example: 5 | 6 | Input: ["Hello", "Alaska", "Dad", "Peace"] 7 | Output: ["Alaska", "Dad"] 8 | 9 | 10 | 11 | Note: 12 | 13 | You may use one character in the keyboard more than once. 14 | You may assume the input string will only contain letters of alphabet. 15 | ''' 16 | class Solution: 17 | def findWords(self, words: List[str]) -> List[str]: 18 | key_rows = {'q' : 1, 'w' : 1, 'e' : 1, 'r' : 1, 't' : 1, 'y' : 1, 'u' : 1, 'i' : 1, 'p' : 1, 'o' : 1, 'a' : 2, 's' : 2, 'd' : 2, 'f' : 2, 'g' : 2, 'h' : 2, 'j' : 2, 'k' : 2, 'l' : 2, 19 | 'z' : 3, 'x' : 3, 'c' : 3, 'v' : 3, 'b' : 3, 'n' : 3, 'm' : 3} 20 | res = [] 21 | 22 | for word in words: 23 | row, flag = key_rows[word[0].lower()], True 24 | for letter in word: 25 | if key_rows[letter.lower()] != row: 26 | flag = False 27 | break 28 | if flag: 29 | res.append(word) 30 | 31 | return res 32 | -------------------------------------------------------------------------------- /0503-Next-Greater-Element-II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number. 3 | 4 | Example 1: 5 | 6 | Input: [1,2,1] 7 | Output: [2,-1,2] 8 | Explanation: The first 1's next greater number is 2; 9 | The number 2 can't find next greater number; 10 | The second 1's next greater number needs to search circularly, which is also 2. 11 | 12 | Note: The length of given array won't exceed 10000. 13 | ''' 14 | # Time Complexity: O(n) 15 | # Space Complexity: O(n) 16 | class Solution: 17 | def nextGreaterElements(self, nums: List[int]) -> List[int]: 18 | res = [-1] * len(nums) 19 | stack = [nums[n] for n in range(len(nums) - 1, -1, -1)] 20 | for i in range(len(nums) - 1, -1, -1): 21 | while stack and stack[-1] <= nums[i]: 22 | stack.pop() 23 | if stack: 24 | res[i] = stack[-1] 25 | stack.append(nums[i]) 26 | return res 27 | -------------------------------------------------------------------------------- /0525-Contiguous-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 3 | 4 | Example 1: 5 | Input: [0,1] 6 | Output: 2 7 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 8 | Example 2: 9 | Input: [0,1,0] 10 | Output: 2 11 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 12 | ''' 13 | class Solution: 14 | def findMaxLength(self, nums: List[int]) -> int: 15 | d = {0: 0} 16 | max_len = count = 0 17 | for i, num in enumerate(nums, 1): 18 | if not num: 19 | count -= 1 20 | else: 21 | count += 1 22 | if count in d: 23 | max_len = max(max_len, i - d[count]) 24 | else: 25 | d[count] = i 26 | return max_len 27 | -------------------------------------------------------------------------------- /0540-Single-Element-in-a-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. 3 | 4 | Follow up: Your solution should run in O(log n) time and O(1) space. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,1,2,3,3,4,4,8,8] 11 | Output: 2 12 | 13 | Example 2: 14 | 15 | Input: nums = [3,3,7,7,10,11,11] 16 | Output: 10 17 | 18 | 19 | Constraints: 20 | 1 <= nums.length <= 10^5 21 | 0 <= nums[i] <= 10^5 22 | ''' 23 | class Solution: 24 | def singleNonDuplicate(self, nums: List[int]) -> int: 25 | lo, hi = 0, len(nums) - 1 26 | while lo < hi: 27 | mid = (lo + hi) // 2 28 | 29 | if nums[mid] == nums[mid ^ 1]: 30 | lo = mid + 1 31 | else: 32 | hi = mid 33 | return nums[lo] 34 | -------------------------------------------------------------------------------- /0543-Diameter-of-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 3 | 4 | Example: 5 | Given a binary tree 6 | 1 7 | / \ 8 | 2 3 9 | / \ 10 | 4 5 11 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 12 | 13 | Note: The length of path between two nodes is represented by the number of edges between them. 14 | ''' 15 | # Definition for a binary tree node. 16 | # class TreeNode: 17 | # def __init__(self, val=0, left=None, right=None): 18 | # self.val = val 19 | # self.left = left 20 | # self.right = right 21 | class Solution: 22 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 23 | self.diameter = 0 24 | def depth(root): 25 | if not root: 26 | return 0 27 | l = depth(root.left) 28 | r = depth(root.right) 29 | self.diameter = max(self.diameter, l+r) 30 | return max(l,r)+1 31 | depth(root) 32 | return self.diameter 33 | -------------------------------------------------------------------------------- /0557-Reverse-Words-in-a-String-III.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 3 | 4 | Example 1: 5 | Input: "Let's take LeetCode contest" 6 | Output: "s'teL ekat edoCteeL tsetnoc" 7 | Note: In the string, each word is separated by single space and there will not be any extra space in the string. 8 | ''' 9 | 10 | class Solution: 11 | def reverseString(self, sub, start, end): 12 | while start < end: 13 | sub[start], sub[end] = sub[end], sub[start] 14 | start += 1 15 | end -= 1 16 | 17 | def reverseWords(self, s: str) -> str: 18 | s = list(s) 19 | start = 0 20 | for i, char in enumerate(s): 21 | if char == ' ': 22 | self.reverseString(s, start, i - 1) 23 | start = i + 1 24 | if i == len(s) - 1: 25 | self.reverseString(s, start, i) 26 | 27 | return ''.join(s) -------------------------------------------------------------------------------- /0560-Subarray-Sum-Equals-K.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 3 | 4 | Example 1: 5 | Input:nums = [1,1,1], k = 2 6 | Output: 2 7 | Note: 8 | The length of the array is in range [1, 20,000]. 9 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 10 | ''' 11 | class Solution: 12 | def subarraySum(self, nums: List[int], k: int) -> int: 13 | count = summ = 0 14 | d = {0 : 1} 15 | for i in range(len(nums)): 16 | summ += nums[i] 17 | if summ - k in d: 18 | count += d[summ - k] 19 | if summ not in d: 20 | d[summ] = 1 21 | else: 22 | d[summ] += 1 23 | return count 24 | -------------------------------------------------------------------------------- /0605-Can-Place-Flowers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die. 3 | 4 | Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule. 5 | 6 | Example 1: 7 | Input: flowerbed = [1,0,0,0,1], n = 1 8 | Output: True 9 | Example 2: 10 | Input: flowerbed = [1,0,0,0,1], n = 2 11 | Output: False 12 | Note: 13 | The input array won't violate no-adjacent-flowers rule. 14 | The input array size is in the range of [1, 20000]. 15 | n is a non-negative integer which won't exceed the input array size. 16 | ''' 17 | class Solution: 18 | def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: 19 | 20 | count = 0 21 | i = 0 22 | 23 | while i < len(flowerbed): 24 | 25 | if (not flowerbed[i] and (not i or not flowerbed[i - 1]) and (i == len(flowerbed) - 1 or not flowerbed[i + 1])): 26 | flowerbed[i] = 1 27 | i += 1 28 | count += 1 29 | if count >= n: 30 | return True 31 | i += 1 32 | 33 | return False -------------------------------------------------------------------------------- /0617-Merge-Two-Binary-Trees.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. 3 | 4 | You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. 5 | 6 | Example 1: 7 | 8 | Input: 9 | Tree 1 Tree 2 10 | 1 2 11 | / \ / \ 12 | 3 2 1 3 13 | / \ \ 14 | 5 4 7 15 | Output: 16 | Merged tree: 17 | 3 18 | / \ 19 | 4 5 20 | / \ \ 21 | 5 4 7 22 | 23 | 24 | Note: The merging process must start from the root nodes of both trees. 25 | ''' 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, val=0, left=None, right=None): 29 | # self.val = val 30 | # self.left = left 31 | # self.right = right 32 | class Solution: 33 | def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 34 | if not t1 or not t2: 35 | return t1 or t2 36 | t1.val += t2.val 37 | t1.left = self.mergeTrees(t1.left, t2.left) 38 | t1.right = self.mergeTrees(t1.right, t2.right) 39 | return t1 40 | -------------------------------------------------------------------------------- /0657-Robot-Return-to-Origin.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There is a robot starting at position (0, 0), the origin, on a 2D plane. 3 | Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. 4 | The move sequence is represented by a string, and the character moves[i] represents its ith move. 5 | Valid moves are R (right), L (left), U (up), and D (down). 6 | If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. 7 | 8 | Note: The way that the robot is "facing" is irrelevant. 9 | "R" will always make the robot move to the right once, "L" will always make it move left, etc. 10 | Also, assume that the magnitude of the robot's movement is the same for each move. 11 | 12 | 13 | Example 1: 14 | Input: moves = "UD" 15 | Output: true 16 | Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. 17 | 18 | Example 2: 19 | Input: moves = "LL" 20 | Output: false 21 | Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. 22 | 23 | Example 3: 24 | Input: moves = "RRDD" 25 | Output: false 26 | 27 | Example 4: 28 | Input: moves = "LDRRLRUULR" 29 | Output: false 30 | 31 | 32 | Constraints: 33 | 1 <= moves.length <= 2 * 104 34 | moves only contains the characters 'U', 'D', 'L' and 'R'. 35 | ''' 36 | 37 | class Solution: 38 | def judgeCircle(self, moves: str) -> bool: 39 | x = y = 0 40 | for move in moves: 41 | if move == 'R': 42 | x += 1 43 | if move == 'L': 44 | x -= 1 45 | if move == 'U': 46 | y += 1 47 | if move == 'D': 48 | y -= 1 49 | return x == 0 and y == 0 50 | 51 | # Check Custom Input 52 | 53 | s = Solution() 54 | answer = s.judgeCircle('LDRRLRUULRDL') # True 55 | print(answer) -------------------------------------------------------------------------------- /0665-Non-decreasing-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. 3 | 4 | We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [4,2,3] 11 | Output: true 12 | Explanation: You could modify the first 4 to 1 to get a non-decreasing array. 13 | Example 2: 14 | 15 | Input: nums = [4,2,1] 16 | Output: false 17 | Explanation: You can't get a non-decreasing array by modify at most one element. 18 | 19 | 20 | Constraints: 21 | 22 | 1 <= n <= 10 ^ 4 23 | - 10 ^ 5 <= nums[i] <= 10 ^ 5 24 | ''' 25 | class Solution: 26 | def checkPossibility(self, nums: List[int]) -> bool: 27 | 28 | flag = True 29 | 30 | for i in range(len(nums) - 1): 31 | 32 | if nums[i] > nums[i + 1]: 33 | if i: 34 | if nums[i - 1] <= nums[i + 1]: 35 | nums[i] = nums[i - 1] 36 | else: 37 | nums[i + 1] = nums[i] 38 | if flag: 39 | flag = False 40 | else: 41 | return False 42 | return True -------------------------------------------------------------------------------- /0674-Longest-Continuous-Increasing-Subsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). 3 | 4 | Example 1: 5 | Input: [1,3,5,4,7] 6 | Output: 3 7 | Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 8 | Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 9 | Example 2: 10 | Input: [2,2,2,2,2] 11 | Output: 1 12 | Explanation: The longest continuous increasing subsequence is [2], its length is 1. 13 | Note: Length of the array will not exceed 10,000. 14 | ''' 15 | class Solution: 16 | def findLengthOfLCIS(self, nums: List[int]) -> int: 17 | 18 | res = anchor = 0 19 | 20 | for i in range(len(nums)): 21 | 22 | if i and nums[i] <= nums[i - 1]: 23 | anchor = i 24 | res = max(res, i - anchor + 1) 25 | 26 | return res -------------------------------------------------------------------------------- /0678-Valid-Parenthesis-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 3 | 4 | Any left parenthesis '(' must have a corresponding right parenthesis ')'. 5 | Any right parenthesis ')' must have a corresponding left parenthesis '('. 6 | Left parenthesis '(' must go before the corresponding right parenthesis ')'. 7 | '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 8 | An empty string is also valid. 9 | Example 1: 10 | Input: "()" 11 | Output: True 12 | Example 2: 13 | Input: "(*)" 14 | Output: True 15 | Example 3: 16 | Input: "(*))" 17 | Output: True 18 | Note: 19 | The string size will be in the range [1, 100]. 20 | ''' 21 | class Solution: 22 | def checkValidString(self, s: str) -> bool: 23 | low = high = 0 24 | for c in s: 25 | low += 1 if c == '(' else -1 26 | high += 1 if c != ')' else -1 27 | if high < 0: 28 | break 29 | low = max(low, 0) 30 | return not low 31 | -------------------------------------------------------------------------------- /0692-Top-K-Frequent-Words.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty list of words, return the k most frequent elements. 3 | 4 | Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. 5 | 6 | Example 1: 7 | 8 | Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 9 | Output: ["i", "love"] 10 | Explanation: "i" and "love" are the two most frequent words. 11 | Note that "i" comes before "love" due to a lower alphabetical order. 12 | 13 | Example 2: 14 | 15 | Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 16 | Output: ["the", "is", "sunny", "day"] 17 | Explanation: "the", "is", "sunny" and "day" are the four most frequent words, 18 | with the number of occurrence being 4, 3, 2 and 1 respectively. 19 | 20 | Note: 21 | 22 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 23 | Input words contain only lowercase letters. 24 | 25 | Follow up: 26 | 27 | Try to solve it in O(n log k) time and O(n) extra space. 28 | ''' 29 | #Time Complexit: O(n log(k)) 30 | #Spacce Complexity: O(n) 31 | 32 | class Solution: 33 | def topKFrequent(self, words: List[str], k: int) -> List[str]: 34 | count = {} 35 | for word in words: 36 | count[word] = count.get(word, 0) + 1 37 | heap = [] 38 | for word, freq in count.items(): 39 | heap.append((-freq, word)) 40 | heapq.heapify(heap) 41 | res = [] 42 | for _ in range(k): 43 | res.append(heapq.heappop(heap)[1]) 44 | return res 45 | -------------------------------------------------------------------------------- /0700-Search-in-a-Binary-Search-Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 3 | 4 | For example, 5 | 6 | Given the tree: 7 | 4 8 | / \ 9 | 2 7 10 | / \ 11 | 1 3 12 | 13 | And the value to search: 2 14 | You should return this subtree: 15 | 16 | 2 17 | / \ 18 | 1 3 19 | In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL. 20 | 21 | Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null. 22 | ''' 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, val=0, left=None, right=None): 26 | # self.val = val 27 | # self.left = left 28 | # self.right = right 29 | class Solution: 30 | def searchBST(self, root: TreeNode, val: int) -> TreeNode: 31 | if not root: 32 | return None 33 | if root.val == val: 34 | return root 35 | elif root.val > val: 36 | root = root.left 37 | else: 38 | root = root.right 39 | return self.searchBST(root, val) 40 | -------------------------------------------------------------------------------- /0704-Binary-Search.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/binary-search/ 3 | Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. 4 | 5 | 6 | Example 1: 7 | Input: nums = [-1,0,3,5,9,12], target = 9 8 | 9 | Output: 4 10 | Explanation: 9 exists in nums and its index is 4 11 | 12 | Example 2: 13 | Input: nums = [-1,0,3,5,9,12], target = 2 14 | 15 | Output: -1 16 | Explanation: 2 does not exist in nums so return -1 17 | 18 | 19 | Note: 20 | You may assume that all elements in nums are unique. 21 | n will be in the range [1, 10000]. 22 | The value of each element in nums will be in the range [-9999, 9999]. 23 | ''' 24 | class Solution: 25 | def search(self, nums: List[int], target: int) -> int: 26 | lower, upper = 0, len(nums)-1 27 | 28 | while (lower<=upper): 29 | mid = (lower+upper)//2 30 | 31 | if (nums[mid]==target): 32 | return mid 33 | if (nums[mid] str: 25 | return ''.join([chr(ord(c) + 32) if 65 <= ord(c) <= 90 else c for c in str]) 26 | -------------------------------------------------------------------------------- /0724- Find-Pivot-Index.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers nums, calculate the pivot index of this array. 3 | The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. 4 | If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. 5 | Return the leftmost pivot index. If no such index exists, return -1. 6 | 7 | Example 1: 8 | Input: nums = [1,7,3,6,5,6] 9 | Output: 3 10 | Explanation: 11 | The pivot index is 3. 12 | Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 13 | Right sum = nums[4] + nums[5] = 5 + 6 = 11 14 | 15 | Example 2: 16 | Input: nums = [1,2,3] 17 | Output: -1 18 | Explanation: 19 | There is no index that satisfies the conditions in the problem statement. 20 | 21 | Example 3: 22 | Input: nums = [2,1,-1] 23 | Output: 0 24 | Explanation: 25 | The pivot index is 0. 26 | Left sum = 0 (no elements to the left of index 0) 27 | Right sum = nums[1] + nums[2] = 1 + -1 = 0 28 | 29 | Constraints: 30 | 1 <= nums.length <= 104 31 | -1000 <= nums[i] <= 1000 32 | ''' 33 | 34 | # Using Left Sum and Right Sum Method 1 35 | 36 | class Solution: 37 | def pivotIndex(self, nums: List[int]) -> int: 38 | left_sum = 0 39 | right_sum = sum(nums) - nums[0] 40 | 41 | for i, num in enumerate(nums): 42 | if left_sum == right_sum: 43 | return i 44 | 45 | if i != len(nums)- 1: 46 | left_sum += nums[i] 47 | right_sum -= nums[i + 1] 48 | 49 | return -1 50 | 51 | # Using Left Sum and Remaining Sum Method 2 52 | 53 | class Solution: 54 | def pivotIndex(self, nums: List[int]) -> int: 55 | left_sum = 0 56 | summ = sum(nums) 57 | 58 | for i, num in enumerate(nums): 59 | if left_sum == summ - left_sum - num: 60 | return i 61 | 62 | left_sum += nums[i] 63 | 64 | return -1 -------------------------------------------------------------------------------- /0733-Flood-Fill.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). 3 | 4 | Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. 5 | 6 | To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. 7 | 8 | At the end, return the modified image. 9 | 10 | Example 1: 11 | Input: 12 | image = [[1,1,1],[1,1,0],[1,0,1]] 13 | sr = 1, sc = 1, newColor = 2 14 | Output: [[2,2,2],[2,2,0],[2,0,1]] 15 | Explanation: 16 | From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected 17 | by a path of the same color as the starting pixel are colored with the new color. 18 | Note the bottom corner is not colored 2, because it is not 4-directionally connected 19 | to the starting pixel. 20 | Note: 21 | 22 | The length of image and image[0] will be in the range [1, 50]. 23 | The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. 24 | The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. 25 | ''' 26 | class Solution: 27 | def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: 28 | m, n = len(image), len(image[0]) 29 | color = image[sr][sc] 30 | 31 | if color == newColor: 32 | return image 33 | 34 | def dfs(i, j): 35 | if image[i][j] == color: 36 | image[i][j] = newColor 37 | if i >= 1: 38 | dfs(i-1, j) 39 | if j >= 1: 40 | dfs(i, j-1) 41 | if i < m-1: 42 | dfs(i+1, j) 43 | if j < n-1: 44 | dfs(i, j+1) 45 | 46 | dfs(sr, sc) 47 | return image 48 | -------------------------------------------------------------------------------- /0739-Daily-Temperatures.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 3 | 4 | For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 5 | 6 | Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 7 | ''' 8 | # Time Complexity: O(n) 9 | # Space Complexity: O(n) 10 | class Solution: 11 | def dailyTemperatures(self, T: List[int]) -> List[int]: 12 | res = [0] * len(T) 13 | stack = [] 14 | for i in range(len(T) - 1, -1, -1): 15 | while stack and T[i] >= T[stack[-1]]: 16 | stack.pop() 17 | if stack: 18 | res[i] = stack[-1] - i 19 | stack.append(i) 20 | return res 21 | -------------------------------------------------------------------------------- /0771-Jewels-and-Stones.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 3 | 4 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 5 | 6 | Example 1: 7 | 8 | Input: J = "aA", S = "aAAbbbb" 9 | Output: 3 10 | Example 2: 11 | 12 | Input: J = "z", S = "ZZ" 13 | Output: 0 14 | Note: 15 | 16 | S and J will consist of letters and have length at most 50. 17 | The characters in J are distinct. 18 | ''' 19 | class Solution: 20 | def numJewelsInStones(self, J: str, S: str) -> int: 21 | J = set(J) 22 | count = 0 23 | for s in S: 24 | if s in J: count += 1 25 | return count 26 | -------------------------------------------------------------------------------- /0844-Backspace-String-Compare.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. 3 | 4 | Example 1: 5 | 6 | Input: S = "ab#c", T = "ad#c" 7 | Output: true 8 | Explanation: Both S and T become "ac". 9 | 10 | Example 2: 11 | 12 | Input: S = "ab##", T = "c#d#" 13 | Output: true 14 | Explanation: Both S and T become "". 15 | 16 | Example 3: 17 | 18 | Input: S = "a##c", T = "#a#c" 19 | Output: true 20 | Explanation: Both S and T become "c". 21 | 22 | Example 4: 23 | 24 | Input: S = "a#c", T = "b" 25 | Output: false 26 | Explanation: S becomes "c" while T becomes "b". 27 | 28 | Note: 29 | 30 | 1 <= S.length <= 200 31 | 1 <= T.length <= 200 32 | S and T only contain lowercase letters and '#' characters. 33 | 34 | Follow up: 35 | 36 | Can you solve it in O(N) time and O(1) space? 37 | ''' 38 | # Time Complexity: O(n + m) 39 | # Space Complexity: O(1) 40 | class Solution: 41 | def backspaceCompare(self, S: str, T: str) -> bool: 42 | backS, upperS, backT, upperT = 0, len(S) - 1, 0, len(T) - 1 43 | while True: 44 | while upperS >= 0 and (backS or S[upperS] == '#'): 45 | backS += 1 if S[upperS] == '#' else -1 46 | upperS -= 1 47 | while upperT >= 0 and (backT or T[upperT] == '#'): 48 | backT += 1 if T[upperT] == '#' else -1 49 | upperT -= 1 50 | if not (upperS >= 0 and upperT >= 0 and S[upperS] == T[upperT]): 51 | return upperS == upperT == -1 52 | upperS, upperT = upperS - 1, upperT - 1 53 | 54 | -------------------------------------------------------------------------------- /0849-Maximize-Distance-to-Closest-Person.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. 3 | 4 | There is at least one empty seat, and at least one person sitting. 5 | 6 | Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. 7 | 8 | Return that maximum distance to closest person. 9 | 10 | Example 1: 11 | 12 | Input: [1,0,0,0,1,0,1] 13 | Output: 2 14 | Explanation: 15 | If Alex sits in the second open seat (seats[2]), then the closest person has distance 2. 16 | If Alex sits in any other open seat, the closest person has distance 1. 17 | Thus, the maximum distance to the closest person is 2. 18 | 19 | Example 2: 20 | 21 | Input: [1,0,0,0] 22 | Output: 3 23 | Explanation: 24 | If Alex sits in the last seat, the closest person is 3 seats away. 25 | This is the maximum distance possible, so the answer is 3. 26 | 27 | Note: 28 | 29 | 1 <= seats.length <= 20000 30 | seats contains only 0s or 1s, at least one 0, and at least one 1. 31 | ''' 32 | class Solution: 33 | def maxDistToClosest(self, seats: List[int]) -> int: 34 | 35 | last_seen = -1 36 | max_dist = 0 37 | 38 | for i in range(len(seats)): 39 | 40 | if seats[i]: 41 | max_dist = max((i - last_seen) // 2 if last_seen != -1 else i, max_dist) 42 | last_seen = i 43 | 44 | return max(len(seats) - 1 - last_seen if last_seen != -1 else len(seats) - 1, max_dist) -------------------------------------------------------------------------------- /0852-Peak-Index-In-A-Mountain-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/peak-index-in-a-mountain-array/ 3 | 4 | Let's call an array arr a mountain if the following properties hold: 5 | 6 | arr.length >= 3 7 | There exists some i with 0 < i < arr.length - 1 such that: 8 | - arr[0] < arr[1] < ... arr[i-1] < arr[i] 9 | - arr[i] > arr[i+1] > ... > arr[arr.length - 1] 10 | Given an integer array arr that is guaranteed to be a mountain, 11 | return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. 12 | 13 | Example 1: 14 | Input: [0,1,0] 15 | Output: 1 16 | 17 | Example 2: 18 | Input: [0,2,1,0] 19 | Output: 1 20 | 21 | Note: 22 | 3 <= A.length <= 10000 23 | 0 <= A[i] <= 10^6 24 | A is a mountain, as defined above. 25 | ''' 26 | 27 | # Method 1 28 | 29 | class Solution: 30 | def peakIndexInMountainArray(self, arr: List[int]) -> int: 31 | start, end = 0, len(arr) - 1 32 | while start < end: 33 | mid = (start + end) // 2 34 | if arr[mid] > arr[mid + 1]: 35 | end = mid 36 | else: 37 | start = mid + 1 38 | return start 39 | 40 | # Method 2 41 | 42 | class Solution: 43 | def peakIndexInMountainArray(self, arr: List[int]) -> int: 44 | start, end = 0, len(arr) - 1 45 | while start <= end: 46 | mid = (start + end) // 2 47 | if arr[mid - 1] < arr[mid] > arr[mid + 1]: 48 | return mid 49 | elif arr[mid - 1] < arr[mid]: 50 | start = mid 51 | else: 52 | end = mid -------------------------------------------------------------------------------- /0856-Score-of-Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a balanced parentheses string S, compute the score of the string based on the following rule: 3 | 4 | () has score 1 5 | AB has score A + B, where A and B are balanced parentheses strings. 6 | (A) has score 2 * A, where A is a balanced parentheses string. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: "()" 13 | Output: 1 14 | 15 | Example 2: 16 | 17 | Input: "(())" 18 | Output: 2 19 | 20 | Example 3: 21 | 22 | Input: "()()" 23 | Output: 2 24 | 25 | Example 4: 26 | 27 | Input: "(()(()))" 28 | Output: 6 29 | 30 | 31 | 32 | Note: 33 | 34 | S is a balanced parentheses string, containing only ( and ). 35 | 2 <= S.length <= 50 36 | ''' 37 | # Time Complexity: O(n) 38 | # Space Complexity: O(1) 39 | class Solution: 40 | def scoreOfParentheses(self, S: str) -> int: 41 | res = bal = 0 42 | for idx, s in enumerate(S): 43 | if s == '(': 44 | bal += 1 45 | else: 46 | bal -= 1 47 | if S[idx - 1] == '(': 48 | res += 1 << bal 49 | return res 50 | -------------------------------------------------------------------------------- /0872-Leaf-Similar-Trees.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. 3 | 4 | 5 | 6 | For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). 7 | 8 | Two binary trees are considered leaf-similar if their leaf value sequence is the same. 9 | 10 | Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. 11 | 12 | 13 | 14 | Constraints: 15 | 16 | Both of the given trees will have between 1 and 200 nodes. 17 | Both of the given trees will have values between 0 and 200 18 | ''' 19 | # Definition for a binary tree node. 20 | # class TreeNode: 21 | # def __init__(self, val=0, left=None, right=None): 22 | # self.val = val 23 | # self.left = left 24 | # self.right = right 25 | 26 | # Method 1, Object 27 | 28 | class Solution: 29 | def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: 30 | return self.leafInorder(root1) == self.leafInorder(root2) 31 | 32 | def leafInorder(self, root): 33 | if not root: 34 | return [] 35 | if not root.left and not root.right: 36 | return [root.val] 37 | return self.leafInorder(root.left) + self.leafInorder(root.right) 38 | 39 | # Method 2, Iterative 40 | 41 | class Solution: 42 | def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: 43 | return self.getLeaves(root1) == self.getLeaves(root2) 44 | 45 | def getLeaves(self, root): 46 | stack = [root] 47 | leaves = [] 48 | while stack: 49 | node = stack.pop() 50 | if not node.left and not node.right: 51 | leaves.append(node.val) 52 | if node.left: 53 | stack.append(node.left) 54 | if node.right: 55 | stack.append(node.right) 56 | print(leaves) 57 | return leaves 58 | -------------------------------------------------------------------------------- /0876-Middle-of-the-Linked-List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty, singly linked list with head node head, return a middle node of linked list. 3 | 4 | If there are two middle nodes, return the second middle node. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [1,2,3,4,5] 11 | Output: Node 3 from this list (Serialization: [3,4,5]) 12 | The returned node has value 3. (The judge's serialization of this node is [3,4,5]). 13 | Note that we returned a ListNode object ans, such that: 14 | ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. 15 | Example 2: 16 | 17 | Input: [1,2,3,4,5,6] 18 | Output: Node 4 from this list (Serialization: [4,5,6]) 19 | Since the list has two middle nodes with values 3 and 4, we return the second one. 20 | 21 | 22 | Note: 23 | 24 | The number of nodes in the given list will be between 1 and 100. 25 | ''' 26 | # Definition for singly-linked list. 27 | # class ListNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.next = None 31 | 32 | #Time Complexity - O(n), Space Complexity - O(1) 33 | class Solution: 34 | def middleNode(self, head: ListNode) -> ListNode: 35 | mid = end = head 36 | while end and end.next: 37 | mid = mid.next 38 | end = end.next.next 39 | return mid 40 | -------------------------------------------------------------------------------- /0881-Boats-to-Save-People.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. 3 | Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. 4 | Return the minimum number of boats to carry every given person. 5 | 6 | 7 | 8 | Example 1: 9 | Input: people = [1,2], limit = 3 10 | Output: 1 11 | Explanation: 1 boat (1, 2) 12 | 13 | Example 2: 14 | Input: people = [3,2,2,1], limit = 3 15 | Output: 3 16 | Explanation: 3 boats (1, 2), (2) and (3) 17 | 18 | Example 3: 19 | Input: people = [3,5,3,4], limit = 5 20 | Output: 4 21 | Explanation: 4 boats (3), (3), (4), (5) 22 | 23 | Constraints: 24 | 1 <= people.length <= 5 * 104 25 | 1 <= people[i] <= limit <= 3 * 104 26 | ''' 27 | 28 | from typing import List 29 | 30 | # Two Pointers Method 31 | 32 | class Solution: 33 | def numRescueBoats(self, people: List[int], limit: int) -> int: 34 | people.sort() 35 | left, right, boat = 0, len(people) - 1, 0 36 | while left <= right: 37 | if left == right: 38 | boat += 1 39 | break 40 | if people[left] + people[right] <= limit: 41 | left += 1 42 | 43 | boat += 1 44 | right -= 1 45 | 46 | return boat 47 | 48 | # Negligibly Better Solution, same method 49 | 50 | class Solution: 51 | def numRescueBoats(self, people: List[int], limit: int) -> int: 52 | people.sort() 53 | left, right, boat = 0, len(people) - 1, 0 54 | while left <= right: 55 | boat += 1 56 | if left == right: 57 | break 58 | if people[left] + people[right] <= limit: 59 | left += 1 60 | right -= 1 61 | 62 | return boat 63 | 64 | s = Solution() 65 | answer = s.numRescueBoats([2, 1, 3, 4], 4) # 3 66 | print(answer) -------------------------------------------------------------------------------- /0890-Find-and-Replace-Pattern.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have a list of words and a pattern, and you want to know which words in words matches the pattern. 3 | 4 | A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. 5 | 6 | (Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.) 7 | 8 | Return a list of the words in words that match the given pattern. 9 | 10 | You may return the answer in any order. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" 17 | Output: ["mee","aqq"] 18 | Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. 19 | "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, 20 | since a and b map to the same letter. 21 | 22 | 23 | Note: 24 | 25 | 1 <= words.length <= 50 26 | 1 <= pattern.length = words[i].length <= 20 27 | ''' 28 | class Solution: 29 | def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: 30 | 31 | def find_replace(w): 32 | 33 | d = {} 34 | 35 | return [d.setdefault(c, len(d)) for c in w] 36 | 37 | f_pattern = find_replace(pattern) 38 | 39 | return [w for w in words if find_replace(w) == f_pattern] 40 | -------------------------------------------------------------------------------- /0941-Valid-Mountain-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers arr, return true if and only if it is a valid mountain array. 3 | 4 | Recall that arr is a mountain array if and only if: 5 | arr.length >= 3 6 | There exists some i with 0 < i < arr.length - 1 such that: 7 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 8 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 9 | 10 | 11 | Example 1: 12 | Input: arr = [2,1] 13 | Output: false 14 | 15 | Example 2: 16 | Input: arr = [3,5,5] 17 | Output: false 18 | 19 | Example 3: 20 | Input: arr = [0,3,2,1] 21 | Output: true 22 | 23 | Constraints: 24 | 1 <= arr.length <= 104 25 | 0 <= arr[i] <= 104 26 | ''' 27 | 28 | from typing import List 29 | 30 | class Solution: 31 | def validMountainArray(self, arr: List[int]) -> bool: 32 | if len(arr) < 3: 33 | return False 34 | i = 1 35 | while i < len(arr) and arr[i] > arr[i-1]: 36 | i += 1 37 | if i == 1 or i == len(arr): 38 | return False 39 | while i < len(arr) and arr[i] < arr[i-1]: 40 | i += 1 41 | return i == len(arr) 42 | 43 | s = Solution() 44 | answer = s.validMountainArray([1, 2, 3, 2, 1]) # True 45 | print(answer) 46 | answer = s.validMountainArray([1, 2, 2, 4, 1, 5]) # False 47 | print(answer) -------------------------------------------------------------------------------- /0961-N-Repeated-Element-in-Size-2N-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. 3 | 4 | Return the element repeated N times. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [1,2,3,3] 11 | Output: 3 12 | Example 2: 13 | 14 | Input: [2,1,2,5,3,2] 15 | Output: 2 16 | Example 3: 17 | 18 | Input: [5,1,5,2,5,3,5,4] 19 | Output: 5 20 | 21 | 22 | Note: 23 | 24 | 4 <= A.length <= 10000 25 | 0 <= A[i] < 10000 26 | A.length is even 27 | ''' 28 | class Solution: 29 | def repeatedNTimes(self, A: List[int]) -> int: 30 | for i in range(2,len(A)): 31 | if A[i] == A[i-1] or A[i] == A[i-2]: 32 | return A[i] 33 | return A[0] 34 | -------------------------------------------------------------------------------- /0993-Cousins-in-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | n a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. 3 | 4 | Two nodes of a binary tree are cousins if they have the same depth, but have different parents. 5 | 6 | We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. 7 | 8 | Return true if and only if the nodes corresponding to the values x and y are cousins. 9 | 10 | 11 | 12 | Example 1: 13 | Input: root = [1,2,3,4], x = 4, y = 3 14 | Output: false 15 | 16 | Example 2: 17 | Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 18 | Output: true 19 | 20 | Example 3: 21 | Input: root = [1,2,3,null,4], x = 2, y = 3 22 | Output: false 23 | 24 | 25 | Constraints: 26 | 27 | The number of nodes in the tree will be between 2 and 100. 28 | Each node has a unique integer value from 1 to 100. 29 | ''' 30 | class Solution(object): 31 | def isCousins(self, root, x, y): 32 | """ 33 | :type root: TreeNode 34 | :type x: int 35 | :type y: int 36 | :rtype: bool 37 | """ 38 | lookUp = {} 39 | def dfs(root,depth=0,parent=None): 40 | if not root: 41 | return None 42 | if root.val in (x,y): lookUp[root.val] = (depth,parent) 43 | dfs(root.left,depth + 1, root.val) 44 | dfs(root.right,depth + 1, root.val) 45 | dfs(root) 46 | return lookUp[x][0] == lookUp[y][0] and lookUp[x][1] != lookUp[y][1] 47 | -------------------------------------------------------------------------------- /0997-Find-the-Town-Judge.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 3 | 4 | If the town judge exists, then: 5 | 6 | The town judge trusts nobody. 7 | Everybody (except for the town judge) trusts the town judge. 8 | There is exactly one person that satisfies properties 1 and 2. 9 | 10 | You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 11 | 12 | If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 13 | 14 | 15 | 16 | Example 1: 17 | 18 | Input: N = 2, trust = [[1,2]] 19 | Output: 2 20 | 21 | Example 2: 22 | 23 | Input: N = 3, trust = [[1,3],[2,3]] 24 | Output: 3 25 | 26 | Example 3: 27 | 28 | Input: N = 3, trust = [[1,3],[2,3],[3,1]] 29 | Output: -1 30 | 31 | Example 4: 32 | 33 | Input: N = 3, trust = [[1,2],[2,3]] 34 | Output: -1 35 | 36 | Example 5: 37 | 38 | Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] 39 | Output: 3 40 | 41 | 42 | 43 | Note: 44 | 45 | 1 <= N <= 1000 46 | trust.length <= 10000 47 | trust[i] are all different 48 | trust[i][0] != trust[i][1] 49 | 1 <= trust[i][0], trust[i][1] <= N 50 | ''' 51 | class Solution: 52 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 53 | degree = [0] * (N + 1) 54 | for i, j in trust: 55 | degree[i] -= 1 56 | degree[j] += 1 57 | for i in range(1, N + 1): 58 | if degree[i] == N - 1: 59 | return i 60 | return -1 61 | -------------------------------------------------------------------------------- /1014-Best-Sightseeing-Pair.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them. 3 | 4 | The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them. 5 | 6 | Return the maximum score of a pair of sightseeing spots. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: [8,1,5,2,6] 13 | Output: 11 14 | Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 15 | 16 | 17 | 18 | Note: 19 | 20 | 2 <= A.length <= 50000 21 | 1 <= A[i] <= 1000 22 | ''' 23 | class Solution: 24 | def maxScoreSightseeingPair(self, A: List[int]) -> int: 25 | score, max_score = 0, 0 26 | for a in A: 27 | max_score = score + a if score + a > max_score else max_score 28 | score = a if a > score else score 29 | score -= 1 30 | return max_score 31 | -------------------------------------------------------------------------------- /1021-Remove-Outermost-Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. 3 | 4 | A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. 5 | 6 | Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. 7 | 8 | Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: "(()())(())" 15 | Output: "()()()" 16 | Explanation: 17 | The input string is "(()())(())", with primitive decomposition "(()())" + "(())". 18 | After removing outer parentheses of each part, this is "()()" + "()" = "()()()". 19 | 20 | Example 2: 21 | 22 | Input: "(()())(())(()(()))" 23 | Output: "()()()()(())" 24 | Explanation: 25 | The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". 26 | After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". 27 | 28 | Example 3: 29 | 30 | Input: "()()" 31 | Output: "" 32 | Explanation: 33 | The input string is "()()", with primitive decomposition "()" + "()". 34 | After removing outer parentheses of each part, this is "" + "" = "". 35 | 36 | 37 | 38 | Note: 39 | 40 | S.length <= 10000 41 | S[i] is "(" or ")" 42 | S is a valid parentheses string 43 | ''' 44 | class Solution: 45 | def removeOuterParentheses(self, S: str) -> str: 46 | res = [] 47 | count = 0 48 | for i in S: 49 | if count > 0 and i == '(' or count > 1 and i == ')': 50 | res.append(i) 51 | count += 1 if i == '(' else -1 52 | return ''.join(res) 53 | -------------------------------------------------------------------------------- /1029-Two-City-Scheduling.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. 3 | 4 | Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [[10,20],[30,200],[400,50],[30,20]] 11 | Output: 110 12 | Explanation: 13 | The first person goes to city A for a cost of 10. 14 | The second person goes to city A for a cost of 30. 15 | The third person goes to city B for a cost of 50. 16 | The fourth person goes to city B for a cost of 20. 17 | 18 | The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. 19 | 20 | 21 | Note: 22 | 23 | 1 <= costs.length <= 100 24 | It is guaranteed that costs.length is even. 25 | 1 <= costs[i][0], costs[i][1] <= 1000 26 | ''' 27 | class Solution: 28 | def twoCitySchedCost(self, costs: List[List[int]]) -> int: 29 | costs.sort(key = lambda x: x[1]-x[0]) 30 | 31 | res, first_half = 0, len(costs)//2 32 | 33 | for i in range(len(costs)): 34 | res+=costs[i][1] if i < first_half else costs[i][0] 35 | 36 | return res 37 | -------------------------------------------------------------------------------- /1046-Last-Stone-Weight.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We have a collection of stones, each stone has a positive integer weight. 3 | 4 | Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 5 | 6 | If x == y, both stones are totally destroyed; 7 | If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 8 | At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: [2,7,4,1,8,1] 15 | Output: 1 16 | Explanation: 17 | We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 18 | we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 19 | we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 20 | we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. 21 | 22 | 23 | Note: 24 | 25 | 1 <= stones.length <= 30 26 | 1 <= stones[i] <= 1000 27 | ''' 28 | class Solution: 29 | def lastStoneWeight(self, stones: List[int]) -> int: 30 | q = [-stone for stone in stones] 31 | heapq.heapify(q) 32 | 33 | while (len(q)) > 1: 34 | heapq.heappush(q, heapq.heappop(q) - heapq.heappop(q)) 35 | 36 | return -q[0] 37 | -------------------------------------------------------------------------------- /1047-Remove-All-Adjacent-Duplicates-In-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 3 | 4 | Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. 5 | 6 | We repeatedly make duplicate removals on S until we no longer can. 7 | 8 | Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: "abbaca" 15 | Output: "ca" 16 | Explanation: 17 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". 18 | 19 | 20 | 21 | Note: 22 | 23 | 1 <= S.length <= 20000 24 | S consists only of English lowercase letters. 25 | 26 | ''' 27 | class Solution: 28 | def removeDuplicates(self, S: str) -> str: 29 | stack = [] 30 | 31 | for i in S: 32 | if not stack or stack[-1] != i: 33 | stack.append(i) 34 | else: 35 | stack.pop() 36 | 37 | return ''.join(stack) 38 | -------------------------------------------------------------------------------- /1051-Height-Checker.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Students are asked to stand in non-decreasing order of heights for an annual photo. 3 | 4 | Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: heights = [1,1,4,2,1,3] 11 | Output: 3 12 | 13 | 14 | 15 | Constraints: 16 | 17 | 1 <= heights.length <= 100 18 | 1 <= heights[i] <= 100 19 | 20 | 21 | ''' 22 | class Solution: 23 | def heightChecker(self, heights: List[int]) -> int: 24 | arr = sorted(heights) 25 | res = 0 26 | for i in range(len(heights)): 27 | if heights[i] != arr[i]: 28 | res += 1 29 | return res 30 | -------------------------------------------------------------------------------- /1108-Defanging-an-IP-Address.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 3 | 4 | A defanged IP address replaces every period "." with "[.]". 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: address = "1.1.1.1" 11 | Output: "1[.]1[.]1[.]1" 12 | 13 | Example 2: 14 | 15 | Input: address = "255.100.50.0" 16 | Output: "255[.]100[.]50[.]0" 17 | 18 | 19 | 20 | Constraints: 21 | 22 | The given address is a valid IPv4 address. 23 | ''' 24 | # Time Complexity: O(n) 25 | # Space Complexity: O(1) 26 | class Solution: 27 | def defangIPaddr(self, address: str) -> str: 28 | return '[.]'.join(address.split('.')) 29 | -------------------------------------------------------------------------------- /1137-N-th-Tribonacci-Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The Tribonacci sequence Tn is defined as follows: 3 | 4 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 5 | 6 | Given n, return the value of Tn. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: n = 4 13 | Output: 4 14 | Explanation: 15 | T_3 = 0 + 1 + 1 = 2 16 | T_4 = 1 + 1 + 2 = 4 17 | 18 | Example 2: 19 | 20 | Input: n = 25 21 | Output: 1389537 22 | 23 | 24 | 25 | Constraints: 26 | 27 | 0 <= n <= 37 28 | The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. 29 | 30 | ''' 31 | class Solution: 32 | def tribonacci(self, n: int) -> int: 33 | if n == 0: 34 | return 0 35 | elif 1<=n<=2: 36 | return 1 37 | a = 0 38 | b = c = 1 39 | for _ in range(2,n): 40 | sum = a+b+c 41 | a, b, c = b, c, sum 42 | return sum 43 | -------------------------------------------------------------------------------- /1189-Maximum-Number-of-Ballons.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. 3 | 4 | You can use each character in text at most once. Return the maximum number of instances that can be formed. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: text = "nlaebolko" 11 | Output: 1 12 | 13 | Example 2: 14 | 15 | Input: text = "loonbalxballpoon" 16 | Output: 2 17 | 18 | Example 3: 19 | 20 | Input: text = "leetcode" 21 | Output: 0 22 | 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= text.length <= 10^4 28 | text consists of lower case English letters only. 29 | ''' 30 | class Solution: 31 | def maxNumberOfBalloons(self, text: str) -> int: 32 | d = {'b' : 0, 'a' : 0, 'l' : 0, 'o' : 0, 'n' : 0} 33 | for i in text: 34 | if i in d: 35 | d[i] = d.get(i, 0) + 1 36 | d['l'], d['o'] = d.get('l', 0) // 2, d.get('o', 0) // 2 37 | least = d['b'] 38 | for count in d.values(): 39 | least = count if count < least else least 40 | return least 41 | -------------------------------------------------------------------------------- /1207-Unique-Number-of-Occurences.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: arr = [1,2,2,1,1,3] 9 | Output: true 10 | Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. 11 | 12 | Example 2: 13 | 14 | Input: arr = [1,2] 15 | Output: false 16 | 17 | Example 3: 18 | 19 | Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 20 | Output: true 21 | 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= arr.length <= 1000 27 | -1000 <= arr[i] <= 1000 28 | 29 | ''' 30 | class Solution: 31 | def uniqueOccurrences(self, arr: List[int]) -> bool: 32 | d = {} 33 | for i in range(len(arr)): 34 | d[arr[i]] = d.get(arr[i],0) + 1 35 | s = set() 36 | for i,j in d.items(): 37 | if j in s: 38 | return False 39 | s.add(j) 40 | return True 41 | -------------------------------------------------------------------------------- /1281-Subtract-the-Product-and-Sum-of-Digits-of-an-integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer number n, return the difference between the product of its digits and the sum of its digits. 3 | 4 | 5 | Example 1: 6 | 7 | Input: n = 234 8 | Output: 15 9 | Explanation: 10 | Product of digits = 2 * 3 * 4 = 24 11 | Sum of digits = 2 + 3 + 4 = 9 12 | Result = 24 - 9 = 15 13 | Example 2: 14 | 15 | Input: n = 4421 16 | Output: 21 17 | Explanation: 18 | Product of digits = 4 * 4 * 2 * 1 = 32 19 | Sum of digits = 4 + 4 + 2 + 1 = 11 20 | Result = 32 - 11 = 21 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= n <= 10^5 26 | ''' 27 | class Solution: 28 | def subtractProductAndSum(self, n: int) -> int: 29 | digit, s, p = 0, 0, 1 30 | while n > 0: 31 | digit = n%10 32 | n = n//10 33 | p = p * digit 34 | s = s + digit 35 | return p - s 36 | -------------------------------------------------------------------------------- /1317-Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation. 3 | 4 | Return a list of two integers [A, B] where: 5 | 6 | A and B are No-Zero integers. 7 | A + B = n 8 | 9 | It's guarateed that there is at least one valid solution. If there are many valid solutions you can return any of them. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: n = 2 16 | Output: [1,1] 17 | Explanation: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation. 18 | 19 | Example 2: 20 | 21 | Input: n = 11 22 | Output: [2,9] 23 | 24 | Example 3: 25 | 26 | Input: n = 10000 27 | Output: [1,9999] 28 | 29 | Example 4: 30 | 31 | Input: n = 69 32 | Output: [1,68] 33 | 34 | Example 5: 35 | 36 | Input: n = 1010 37 | Output: [11,999] 38 | 39 | 40 | 41 | Constraints: 42 | 43 | 2 <= n <= 10^4 44 | ''' 45 | class Solution: 46 | def getNoZeroIntegers(self, n: int) -> List[int]: 47 | for i in range(1, n): 48 | if self.noZero(i) and self.noZero(n-i): 49 | return [i, n-i] 50 | 51 | def noZero(self, num): 52 | while num > 0: 53 | if not num%10: 54 | return False 55 | num = num//10 56 | return True 57 | -------------------------------------------------------------------------------- /1356-Sort-Integers-by-The-Number-of-1-Bits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | 4 | Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. 5 | 6 | Return the sorted array. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: arr = [0,1,2,3,4,5,6,7,8] 13 | Output: [0,1,2,4,8,3,5,6,7] 14 | Explantion: [0] is the only integer with 0 bits. 15 | [1,2,4,8] all have 1 bit. 16 | [3,5,6] have 2 bits. 17 | [7] has 3 bits. 18 | The sorted array by bits is [0,1,2,4,8,3,5,6,7] 19 | 20 | Example 2: 21 | 22 | Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] 23 | Output: [1,2,4,8,16,32,64,128,256,512,1024] 24 | Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. 25 | 26 | Example 3: 27 | 28 | Input: arr = [10000,10000] 29 | Output: [10000,10000] 30 | 31 | Example 4: 32 | 33 | Input: arr = [2,3,5,7,11,13,17,19] 34 | Output: [2,3,5,17,7,11,13,19] 35 | 36 | Example 5: 37 | 38 | Input: arr = [10,100,1000,10000] 39 | Output: [10,100,10000,1000] 40 | 41 | 42 | 43 | Constraints: 44 | 45 | 1 <= arr.length <= 500 46 | 0 <= arr[i] <= 10^4 47 | ''' 48 | class Solution: 49 | def sortByBits(self, arr: List[int]) -> List[int]: 50 | arr.sort(key = self.count_bits) 51 | return arr 52 | 53 | def count_bits(self, n): 54 | num, count = n, 0 55 | while n: 56 | count += n & 1 57 | n >>= 1 58 | return (count, num) 59 | -------------------------------------------------------------------------------- /1360-Number-of-Days-Between-Two-Days.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program to count the number of days between two dates. 3 | 4 | The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: date1 = "2019-06-29", date2 = "2019-06-30" 11 | Output: 1 12 | Example 2: 13 | 14 | Input: date1 = "2020-01-15", date2 = "2019-12-31" 15 | Output: 15 16 | 17 | 18 | Constraints: 19 | 20 | The given dates are valid dates between the years 1971 and 2100. 21 | ''' 22 | class Solution: 23 | def daysBetweenDates(self, date1: str, date2: str) -> int: 24 | day1, month1, year1 = self.date_format(date1) 25 | day2, month2, year2 = self.date_format(date2) 26 | 27 | days1, days2 = self.count_Days(day1, month1, year1), self.count_Days(day2, month2, year2) 28 | 29 | return days2 - days1 if days2 >= days1 else days1 - days2 30 | 31 | def date_format(self, date): 32 | date = date.split('-') 33 | yyyy, mm, dd = map(int, date) 34 | return dd, mm, yyyy 35 | 36 | def count_Days(self, day, month, year): 37 | months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 38 | count = 0 39 | 40 | for i in range(1970, year): 41 | if (i % 100 and not i % 4) or not i % 400: 42 | count += 366 43 | else: 44 | count += 365 45 | 46 | for i in range(month - 1): 47 | count += months[i] 48 | 49 | if ((year % 100 and not year % 4) or not year % 400) and (month > 2 or (month == 2 and day == 29)): 50 | count += 1 51 | 52 | return count + day 53 | -------------------------------------------------------------------------------- /1362-Closest-Divisors.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. 3 | 4 | Return the two integers in any order. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: num = 8 11 | Output: [3,3] 12 | Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. 13 | 14 | Example 2: 15 | 16 | Input: num = 123 17 | Output: [5,25] 18 | 19 | Example 3: 20 | 21 | Input: num = 999 22 | Output: [40,25] 23 | 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= num <= 10^9 29 | ''' 30 | class Solution: 31 | def closestDivisors(self, num: int) -> List[int]: 32 | for i in range(int((num + 2)**0.5), 0, -1): 33 | if not (num + 1) % i: 34 | return [i, (num + 1) // i] 35 | if not (num + 2) % i: 36 | return [i, (num + 2) // i] 37 | -------------------------------------------------------------------------------- /1374-Generate-a-String-With-Characters-That-Have-Odd-Counts.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. 3 | 4 | The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: n = 4 11 | Output: "pppz" 12 | Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". 13 | 14 | Example 2: 15 | 16 | Input: n = 2 17 | Output: "xy" 18 | Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". 19 | 20 | Example 3: 21 | 22 | Input: n = 7 23 | Output: "holasss" 24 | 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= n <= 500 30 | ''' 31 | class Solution: 32 | def generateTheString(self, n: int) -> str: 33 | if n % 2: 34 | return 'a' * n 35 | return 'a' * (n - 1) + 'b' 36 | -------------------------------------------------------------------------------- /1380-Lucky-Numbers-in-a-Matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order. 3 | 4 | A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] 11 | Output: [15] 12 | Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column 13 | 14 | Example 2: 15 | 16 | Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] 17 | Output: [12] 18 | Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column. 19 | 20 | Example 3: 21 | 22 | Input: matrix = [[7,8],[1,2]] 23 | Output: [7] 24 | 25 | 26 | 27 | Constraints: 28 | 29 | m == mat.length 30 | n == mat[i].length 31 | 1 <= n, m <= 50 32 | 1 <= matrix[i][j] <= 10^5. 33 | All elements in the matrix are distinct. 34 | ''' 35 | class Solution: 36 | def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: 37 | m, n = len(matrix), len(matrix[0]) 38 | row_mins = [10**5 + 1] * m 39 | col_maxs = [0] * n 40 | 41 | for i in range(m): 42 | for j in range(n): 43 | row_mins[i] = row_mins[i] if row_mins[i] < matrix[i][j] else matrix[i][j] 44 | col_maxs[j] = col_maxs[j] if col_maxs[j] > matrix[i][j] else matrix[i][j] 45 | 46 | res = [] 47 | for i in row_mins: 48 | if i in col_maxs: 49 | res.append(i) 50 | 51 | return res 52 | -------------------------------------------------------------------------------- /1399-Count-Largest-Group.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n. Each number from 1 to n is grouped according to the sum of its digits. 3 | 4 | Return how many groups have the largest size. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: n = 13 11 | Output: 4 12 | Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: 13 | [1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size. 14 | Example 2: 15 | 16 | Input: n = 2 17 | Output: 2 18 | Explanation: There are 2 groups [1], [2] of size 1. 19 | Example 3: 20 | 21 | Input: n = 15 22 | Output: 6 23 | Example 4: 24 | 25 | Input: n = 24 26 | Output: 5 27 | 28 | 29 | Constraints: 30 | 31 | 1 <= n <= 10^4 32 | ''' 33 | class Solution: 34 | def countLargestGroup(self, n: int) -> int: 35 | d = {} 36 | max_value = count = 0 37 | for number in range(1,n+1): 38 | num_sum = self.number_sum(number) 39 | d[num_sum] = d.get(num_sum, 0) + 1 40 | 41 | if d[num_sum] > max_value: 42 | count = 0 43 | max_value = d[num_sum] 44 | 45 | if d[num_sum] == max_value: 46 | count += 1 47 | return count 48 | 49 | 50 | def number_sum(self, n): 51 | num_sum = 0 52 | while n: 53 | num_sum += n % 10 54 | n //= 10 55 | return num_sum 56 | -------------------------------------------------------------------------------- /1400-Construct-K-Palindrome-Strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s. 3 | 4 | Return True if you can use all the characters in s to construct k palindrome strings or False otherwise. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: s = "annabelle", k = 2 11 | Output: true 12 | Explanation: You can construct two palindromes using all characters in s. 13 | Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b" 14 | Example 2: 15 | 16 | Input: s = "leetcode", k = 3 17 | Output: false 18 | Explanation: It is impossible to construct 3 palindromes using all the characters of s. 19 | Example 3: 20 | 21 | Input: s = "true", k = 4 22 | Output: true 23 | Explanation: The only possible solution is to put each character in a separate string. 24 | Example 4: 25 | 26 | Input: s = "yzyzyzyzyzyzyzy", k = 2 27 | Output: true 28 | Explanation: Simply you can put all z's in one string and all y's in the other string. Both strings will be palindrome. 29 | Example 5: 30 | 31 | Input: s = "cr", k = 7 32 | Output: false 33 | Explanation: We don't have enough characters in s to construct 7 palindromes. 34 | 35 | 36 | Constraints: 37 | 38 | 1 <= s.length <= 10^5 39 | All characters in s are lower-case English letters. 40 | 1 <= k <= 10^5 41 | ''' 42 | class Solution: 43 | def canConstruct(self, s: str, k: int) -> bool: 44 | if len(s) <= k: 45 | return len(s) == k 46 | 47 | alphabets = {} 48 | 49 | for c in s: 50 | alphabets[c] = alphabets.get(c, 0) + 1 51 | 52 | count = sum(value % 2 for value in alphabets.values()) 53 | 54 | return count <= k 55 | -------------------------------------------------------------------------------- /1401-Circle-and-Rectangle-Overlapping.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a circle represented as (radius, x_center, y_center) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. 3 | 4 | Return True if the circle and rectangle are overlapped otherwise return False. 5 | 6 | In other words, check if there are any point (xi, yi) such that belongs to the circle and the rectangle at the same time. 7 | 8 | 9 | 10 | Example 1: 11 | Input: radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 12 | Output: true 13 | Explanation: Circle and rectangle share the point (1,0) 14 | 15 | Example 2: 16 | Input: radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 17 | Output: true 18 | 19 | Example 3: 20 | Input: radius = 1, x_center = 1, y_center = 1, x1 = -3, y1 = -3, x2 = 3, y2 = 3 21 | Output: true 22 | 23 | Example 4: 24 | Input: radius = 1, x_center = 1, y_center = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 25 | Output: false 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= radius <= 2000 31 | -10^4 <= x_center, y_center, x1, y1, x2, y2 <= 10^4 32 | x1 < x2 33 | y1 < y2 34 | ''' 35 | class Solution: 36 | def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool: 37 | corners = [(x1,y1), (x2,y1), (x2,y2), (x1, y2)] 38 | for (x, y) in corners: 39 | if (x_center - x)**2 + (y_center - y)**2 <= radius**2: 40 | return True 41 | 42 | for x in [x1, x2]: 43 | if x_center-radius <= x <= x_center+radius and y1<=y_center<=y2: 44 | return True 45 | for y in [y1, y2]: 46 | if y_center-radius <= y <= y_center+radius and x1<=x_center<=x2: 47 | return True 48 | 49 | if x1<=x_center<=x2 and y1<=y_center<=y2: 50 | return True 51 | return False 52 | -------------------------------------------------------------------------------- /1426-Counting-Elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array arr, count element x such that x + 1 is also in arr. 3 | 4 | If there're duplicates in arr, count them seperately. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: arr = [1,2,3] 11 | Output: 2 12 | Explanation: 1 and 2 are counted cause 2 and 3 are in arr. 13 | Example 2: 14 | 15 | Input: arr = [1,1,3,3,5,5,7,7] 16 | Output: 0 17 | Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr. 18 | Example 3: 19 | 20 | Input: arr = [1,3,2,3,5,0] 21 | Output: 3 22 | Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr. 23 | Example 4: 24 | 25 | Input: arr = [1,1,2,2] 26 | Output: 2 27 | Explanation: Two 1s are counted cause 2 is in arr. 28 | 29 | 30 | Constraints: 31 | 32 | 1 <= arr.length <= 1000 33 | 0 <= arr[i] <= 1000 34 | ''' 35 | class Solution: 36 | def countElements(self, arr: List[int]) -> int: 37 | arr_set = set(arr) 38 | count = 0 39 | for x in arr: 40 | if x + 1 in arr_set: 41 | count += 1 42 | return count 43 | -------------------------------------------------------------------------------- /1431-Kids-With-the-Greatest-Number-of-Candies.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. 3 | 4 | For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: candies = [2,3,5,1,3], extraCandies = 3 11 | Output: [true,true,true,false,true] 12 | Explanation: 13 | Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. 14 | Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 15 | Kid 3 has 5 candies and this is already the greatest number of candies among the kids. 16 | Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. 17 | Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 18 | Example 2: 19 | 20 | Input: candies = [4,2,1,1,2], extraCandies = 1 21 | Output: [true,false,false,false,false] 22 | Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy. 23 | Example 3: 24 | 25 | Input: candies = [12,1,12], extraCandies = 10 26 | Output: [true,false,true] 27 | 28 | 29 | Constraints: 30 | 31 | 2 <= candies.length <= 100 32 | 1 <= candies[i] <= 100 33 | 1 <= extraCandies <= 50 34 | ''' 35 | class Solution: 36 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: 37 | max_candies = max(candies) 38 | res = [] 39 | for i in candies: 40 | res.append(i + extraCandies >= max_candies) 41 | return res 42 | -------------------------------------------------------------------------------- /1432-Max-Difference-You-Can-Get-From-Changing-an-Integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an integer num. You will apply the following steps exactly two times: 3 | 4 | Pick a digit x (0 <= x <= 9). 5 | Pick another digit y (0 <= y <= 9). The digit y can be equal to x. 6 | Replace all the occurrences of x in the decimal representation of num by y. 7 | The new integer cannot have any leading zeros, also the new integer cannot be 0. 8 | Let a and b be the results of applying the operations to num the first and second times, respectively. 9 | 10 | Return the max difference between a and b. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: num = 555 17 | Output: 888 18 | Explanation: The first time pick x = 5 and y = 9 and store the new integer in a. 19 | The second time pick x = 5 and y = 1 and store the new integer in b. 20 | We have now a = 999 and b = 111 and max difference = 888 21 | Example 2: 22 | 23 | Input: num = 9 24 | Output: 8 25 | Explanation: The first time pick x = 9 and y = 9 and store the new integer in a. 26 | The second time pick x = 9 and y = 1 and store the new integer in b. 27 | We have now a = 9 and b = 1 and max difference = 8 28 | Example 3: 29 | 30 | Input: num = 123456 31 | Output: 820000 32 | Example 4: 33 | 34 | Input: num = 10000 35 | Output: 80000 36 | Example 5: 37 | 38 | Input: num = 9288 39 | Output: 8700 40 | 41 | 42 | Constraints: 43 | 44 | 1 <= num <= 10^8 45 | ''' 46 | class Solution: 47 | def maxDiff(self, num: int) -> int: 48 | a, b = ([d for d in str(num)] for _ in range(2)) 49 | x, y = a[0], ' ' 50 | for i, ch in enumerate(a): 51 | if ch == x: 52 | a[i] = '9' 53 | b[i] = '1' 54 | else: 55 | if x == '1' and ord(ch) > ord('0') or x == '9' and ord(ch) < ord('9'): 56 | if y == ' ': 57 | y = ch 58 | if y == ch: 59 | if x == '1': 60 | b[i] = '0' 61 | else: 62 | a[i] = '9' 63 | return int(''.join(a)) - int(''.join(b)) 64 | -------------------------------------------------------------------------------- /1433-Check-If-a-String-Can-Break-Another-String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa (in other words s2 can break s1). 3 | 4 | A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: s1 = "abc", s2 = "xya" 11 | Output: true 12 | Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc". 13 | Example 2: 14 | 15 | Input: s1 = "abe", s2 = "acd" 16 | Output: false 17 | Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa. 18 | Example 3: 19 | 20 | Input: s1 = "leetcodee", s2 = "interview" 21 | Output: true 22 | 23 | 24 | Constraints: 25 | 26 | s1.length == n 27 | s2.length == n 28 | 1 <= n <= 10^5 29 | All strings consist of lowercase English letters. 30 | ''' 31 | class Solution: 32 | def checkIfCanBreak(self, s1: str, s2: str) -> bool: 33 | s1 = sorted(s1) 34 | s2 = sorted(s2) 35 | flag1 = flag2 = True 36 | for i in range(len(s1)): 37 | if s1[i] < s2[i]: 38 | flag1 = False 39 | elif s1[i] > s2[i]: 40 | flag2 = False 41 | if not flag1 and not flag2: 42 | return False 43 | return True 44 | -------------------------------------------------------------------------------- /1480-Running-Sum-of-1d-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 3 | Return the running sum of nums. 4 | 5 | Example 1: 6 | Input: nums = [1,2,3,4] 7 | Output: [1,3,6,10] 8 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 9 | 10 | Example 2: 11 | Input: nums = [1,1,1,1,1] 12 | Output: [1,2,3,4,5] 13 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 14 | 15 | Example 3: 16 | Input: nums = [3,1,2,10,1] 17 | Output: [3,4,6,16,17] 18 | 19 | Constraints: 20 | 1 <= nums.length <= 1000 21 | -10^6 <= nums[i] <= 10^6 22 | ''' 23 | 24 | # Normal Iteration and Addition 25 | 26 | class Solution: 27 | def runningSum(self, nums: List[int]) -> List[int]: 28 | res = [nums[0]] 29 | for num in nums[1:]: 30 | res.append(res[-1] + num) 31 | return res 32 | 33 | # Normal Iteration and Addition in the Input Array 34 | 35 | class Solution: 36 | def runningSum(self, nums: List[int]) -> List[int]: 37 | for i, num in enumerate(nums[1:]): 38 | nums[i+1] = nums[i]+num 39 | return nums 40 | 41 | # Normal Iteration and Addition in the Input Array II 42 | 43 | class Solution: 44 | def runningSum(self, nums: List[int]) -> List[int]: 45 | for i in range(1, len(nums)): 46 | nums[i] += nums[i-1] 47 | return nums -------------------------------------------------------------------------------- /1991-Find-the-Middle-Index-in-Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). 3 | A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. 4 | If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. 5 | Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. 6 | 7 | Example 1: 8 | Input: nums = [2,3,-1,8,4] 9 | Output: 3 10 | Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 11 | The sum of the numbers after index 3 is: 4 = 4 12 | 13 | Example 2: 14 | Input: nums = [1,-1,4] 15 | Output: 2 16 | Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0 17 | The sum of the numbers after index 2 is: 0 18 | 19 | Example 3: 20 | Input: nums = [2,5] 21 | Output: -1 22 | Explanation: There is no valid middleIndex. 23 | 24 | Constraints: 25 | 1 <= nums.length <= 100 26 | -1000 <= nums[i] <= 1000 27 | ''' 28 | 29 | class Solution: 30 | def findMiddleIndex(self, nums: List[int]) -> int: 31 | left_sum = 0 32 | right_sum = sum(nums) 33 | 34 | for i, num in enumerate(nums): 35 | if left_sum == right_sum - num: 36 | return i 37 | 38 | left_sum += num 39 | right_sum -= num 40 | 41 | return -1 --------------------------------------------------------------------------------