├── 00_note.py ├── Remove_Element_027_explanation.py ├── Valid_Palindrome_125.py ├── test_Remove_Duplicates_from_Sorted_Array_II_080.py ├── Contains_Duplicate_217.py ├── Power_of_Two_231.py ├── Pascals_Triangle_118.py ├── test_Move_Zeroes_283.py ├── Length_of_Last_Word_058.py ├── Power_of_Three_326.py ├── Reverse_Linked_List_206.py ├── Add_Binary_067.py ├── Majority_Element_169.py ├── Single_Number_136.py ├── Isomorphic_Strings_205.py ├── test_Happy_Number_202.py ├── Missing_Number_268.py ├── Factorial_Trailing_Zeroes_172.py ├── Word_Pattern_290.py ├── Happy_Number_202.py ├── Number_of_1_Bits_191.py ├── test_Majority_Element_169.py ├── test_Pascals_Triangle_118.py ├── Merge_Two_Sorted_Lists_021_explanation.py ├── Add_Digits_258.py ├── Delete_Node_in_a_Linked_List_237.py ├── Excel_Sheet_Column_Number_171.py ├── test_Valid_Palindrome_125.py ├── Maximum_Subarray_053.py ├── Remove_Duplicates_from_Sorted_Array_026_explanation.py ├── test_Add_Binary_067.py ├── Excel_Sheet_Column_Title_168.py ├── Permutations_046.py ├── Nim_Game_292.py ├── test_Single_Number_II_137.py ├── logic_tutorial.py ├── Merge_Intervals_056.py ├── Reverse_Words_in_a_String_151.py ├── test_Power_of_Two_231.py ├── Remove_Duplicates_from_Sorted_Array_II_080.py ├── Single_Number_II_137.py ├── test_Merge_Sorted_Array_088.py ├── Count_and_Say_038.py ├── Plus_One_066.py ├── Ugly_Number_263.py ├── test_Single_Number_136.py ├── test_Contains_Duplicate_217.py ├── test_Power_of_Three_326.py ├── test_Length_of_Last_Word_058.py ├── Implement_strStr_028.py ├── Container_With_Most_Water_011.py ├── test_Add_Digits_258.py ├── test_Valid_Anagram_242.py ├── test_Implement_strStr_028.py ├── test_Missing_Number_268.py ├── Remove_Element_027.py ├── Move_Zeroes_283.py ├── Sqrtx_069.py ├── Reverse_Integer_007.py ├── Rotate_Array_189.py ├── test_Climbing_Stairs_070.py ├── test_Contains_Duplicate_II_219.py ├── test_Remove_Duplicates_from_Sorted_Array_026.py ├── Climbing_Stairs_070.py ├── Reverse_Bits_190.py ├── test_3Sum_015.py ├── test_Container_With_Most_Water_011.py ├── test_Two_Sum_001.py ├── test_Isomorphic_Strings_205.py ├── test_Sqrtx_069.py ├── test_Reverse_Integer_007.py ├── test_Excel_Sheet_Column_Title_168.py ├── test_Remove_Element_027.py ├── test_Excel_Sheet_Column_Number_171.py ├── Remove_Duplicates_from_Sorted_Array_026.py ├── test_Nim_Game_292.py ├── test_Palindrome_Number_009.py ├── .gitignore ├── test_Ugly_Number_263.py ├── Valid_Anagram_242.py ├── LRU_Cache_146.py ├── Longest_Common_Prefix_014.py ├── test_Longest_Increasing_Subsequence_300.py ├── test_Factorial_Trailing_Zeroes_172.py ├── Roman_to_Integer_013.py ├── test_Permutations_046.py ├── Bulls_and_Cows_299.py ├── test_Word_Pattern_290.py ├── test_Plus_One_066.py ├── Merge_Two_Sorted_Lists_021.py ├── test_Merge_Intervals_056.py ├── P3Sum_015.py ├── test_Search_Insert_Position_035.py ├── test_Maximum_Subarray_053.py ├── test_Merge_Two_Sorted_Lists_021.py ├── Valid_Parentheses_020.py ├── test_Reverse_Words_in_a_String_151.py ├── Palindrome_Number_009.py ├── Merge_Sorted_Array_088.py ├── test_Roman_to_Integer_013.py ├── test_Number_of_1_Bits_191.py ├── test_Valid_Parentheses_020.py ├── test_Reverse_Bits_190.py ├── Contains_Duplicate_II_219.py ├── Two_Sum_001.py ├── test_Longest_Common_Prefix_014.py ├── test_Bulls_and_Cows_299.py ├── test_Count_and_Say_038.py ├── Search_Insert_Position_035.py ├── test_Rotate_Array_189.py ├── Longest_Increasing_Subsequence_300.py └── README.md /00_note.py: -------------------------------------------------------------------------------- 1 | Reverse_Linked_List_206 2 | 3 | important 4 | 5 | Longest_Increasing_Subsequence_300 6 | 7 | LRU_Cache_146.py 8 | -------------------------------------------------------------------------------- /Remove_Element_027_explanation.py: -------------------------------------------------------------------------------- 1 | # Confused why the returned value is an integer but your answer is an array? 2 | # why list.remove() work ? 3 | 4 | # Note that the input array is passed in by reference, 5 | # which means modification to the input array will be known to the caller as well. 6 | a = b = [1, 1, 2, 4] 7 | b.remove(1) 8 | print('a', a) 9 | print('b', b) 10 | -------------------------------------------------------------------------------- /Valid_Palindrome_125.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Example 1: 4 | 5 | Input: "A man, a plan, a canal: Panama" 6 | Output: true 7 | 8 | Example 2: 9 | 10 | Input: "race a car" 11 | Output: false 12 | ''' 13 | 14 | import re 15 | 16 | class Solution(object): 17 | def isPalindrome(self, s): 18 | """ 19 | :type s: str 20 | :rtype: bool 21 | """ 22 | s = re.sub('[^a-zA-Z0-9]','',s).lower() 23 | return s == s[::-1] 24 | 25 | -------------------------------------------------------------------------------- /test_Remove_Duplicates_from_Sorted_Array_II_080.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Remove_Duplicates_from_Sorted_Array_II_080 import * 3 | 4 | class Test_Case(unittest.TestCase): 5 | 6 | def test_answer_01(self): 7 | nums = [1,1,1,2,2,3] 8 | result = 5 9 | self.assertEqual(Solution().removeDuplicates(nums), result) 10 | 11 | def test_answer_02(self): 12 | nums = [0,0,1,1,1,1,2,3,3] 13 | result = 7 14 | self.assertEqual(Solution().removeDuplicates(nums), result) 15 | -------------------------------------------------------------------------------- /Contains_Duplicate_217.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, 3 | find if the array contains any duplicates. 4 | 5 | Example 1: 6 | 7 | Input: [1,2,3,1] 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: [1,2,3,4] 13 | Output: false 14 | 15 | Example 3: 16 | 17 | Input: [1,1,1,3,3,4,3,2,4,2] 18 | Output: true 19 | ''' 20 | 21 | class Solution(object): 22 | def containsDuplicate(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: bool 26 | """ 27 | return len(nums) != len(set(nums)) 28 | -------------------------------------------------------------------------------- /Power_of_Two_231.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: n = 1 7 | Output: true 8 | 9 | Example 2: 10 | 11 | Input: n = 16 12 | Output: true 13 | 14 | Example 3: 15 | 16 | Input: n = 3 17 | Output: false 18 | 19 | """ 20 | 21 | 22 | class Solution: 23 | def isPowerOfTwo(self, n: int) -> bool: 24 | 25 | two_power = 2 ** 31 26 | if n <= 0: 27 | return False 28 | else: 29 | return True if two_power % n == 0 else False 30 | -------------------------------------------------------------------------------- /Pascals_Triangle_118.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Input: 5 4 | Output: 5 | [ 6 | [1], 7 | [1,1], 8 | [1,2,1], 9 | [1,3,3,1], 10 | [1,4,6,4,1] 11 | ] 12 | 13 | ''' 14 | 15 | class Solution: 16 | def generate(self, numRows): 17 | if numRows == 0: 18 | return [] 19 | 20 | stack = [1] 21 | result = [stack] 22 | 23 | for i in range(1, numRows): 24 | temp = [stack[s-1] + stack[s] for s in range(1, i)] 25 | stack = [1] + temp + [1] 26 | result.append(stack) 27 | 28 | return result 29 | -------------------------------------------------------------------------------- /test_Move_Zeroes_283.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Move_Zeroes_283 import * 3 | 4 | ''' 5 | Given an array nums, write a function to move all 0's 6 | to the end of it while maintaining the relative order 7 | of the non-zero elements. 8 | 9 | Example: 10 | 11 | Input: [0,1,0,3,12] 12 | Output: [1,3,12,0,0] 13 | ''' 14 | 15 | class Test_Case(unittest.TestCase): 16 | 17 | def test_answer_01(self): 18 | nums = [0,1,0,3,12] 19 | result = [1,3,12,0,0] 20 | 21 | self.assertEqual(Solution().moveZeroes(nums), result) 22 | 23 | if __name__ == '__main__': 24 | unittest.main() 25 | -------------------------------------------------------------------------------- /Length_of_Last_Word_058.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | Example: 9 | 10 | Input: "Hello World" 11 | Output: 5 12 | ''' 13 | 14 | 15 | class Solution: 16 | def lengthOfLastWord(self, s): 17 | """ 18 | :type s: str 19 | :rtype: int 20 | """ 21 | s = s.split() 22 | return len(s[-1]) if s else 0 23 | 24 | -------------------------------------------------------------------------------- /Power_of_Three_326.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer, write a function to determine if it is a power of three. 3 | 4 | Follow up: 5 | Could you do it without using any loop / recursion? 6 | 7 | Example 1: 8 | 9 | Input: n = 27 10 | Output: true 11 | 12 | Example 2: 13 | 14 | Input: n = 0 15 | Output: false 16 | 17 | Example 3: 18 | 19 | Input: n = 9 20 | Output: true 21 | 22 | """ 23 | 24 | 25 | class Solution: 26 | def isPowerOfThree(self, n: int) -> bool: 27 | 28 | threepower = 3 ** 100 29 | if n <= 0: 30 | return False 31 | else: 32 | return threepower % n == 0 -------------------------------------------------------------------------------- /Reverse_Linked_List_206.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | ''' 3 | Reverse a singly linked list. 4 | 5 | Input: 1->2->3->4->5->NULL 6 | Output: 5->4->3->2->1->NULL 7 | ''' 8 | 9 | # class ListNode: 10 | # def __init__(self, val=0, next=None): 11 | # self.val = val 12 | # self.next = next 13 | 14 | # 可參考 https://www.youtube.com/watch?v=mQJOr-_pR_4 15 | 16 | class Solution: 17 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 18 | prev = None 19 | while head: 20 | next = head.next 21 | head.next = prev 22 | prev = head 23 | head = next 24 | return prev 25 | -------------------------------------------------------------------------------- /Add_Binary_067.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 | 17 | class Solution: 18 | def addBinary(self, a, b): 19 | """ 20 | :type a: str 21 | :type b: str 22 | :rtype: str 23 | """ 24 | # return bin(int(a, 2) + int(b, 2))[2:] 25 | # return "{:b}".format(int(a, 2) + int(b, 2)) 26 | return format(int(a, 2) + int(b, 2), "b") 27 | -------------------------------------------------------------------------------- /Majority_Element_169.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of size n, find the majority element. 3 | 4 | The majority element is the element that appears more than ⌊ n/2 ⌋ times. 5 | Example 1: 6 | 7 | Input: [3,2,3] 8 | Output: 3 9 | 10 | Example 2: 11 | 12 | Input: [2,2,1,1,1,2,2] 13 | Output: 2 14 | 15 | ''' 16 | class Solution(object): 17 | def majorityElement(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | d = dict() 23 | for n in nums: 24 | if n in d: 25 | d[n] += 1 26 | else: 27 | d[n] = 1 28 | return max(d, key=d.get) 29 | 30 | 31 | -------------------------------------------------------------------------------- /Single_Number_136.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | """ 4 | Given an array of integers, every element appears twice except for one. 5 | Find that single one. 6 | 7 | Example 1: 8 | 9 | Input: nums = [2,2,1] 10 | Output: 1 11 | 12 | Example 2: 13 | 14 | Input: nums = [4,1,2,1,2] 15 | Output: 4 16 | 17 | Example 3: 18 | 19 | Input: nums = [1] 20 | Output: 1 21 | 22 | """ 23 | 24 | 25 | class Solution: 26 | def singleNumber(self, nums: List[int]) -> int: 27 | """ 28 | ^ -> XOR 29 | a=0 b=0 0 30 | a=0 b=1 1 31 | a=1 b=0 1 32 | a=1 b=1 0 33 | """ 34 | res = 0 35 | for i in nums: 36 | res = res ^ i 37 | return res 38 | -------------------------------------------------------------------------------- /Isomorphic_Strings_205.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: s = "egg", t = "add" 5 | Output: true 6 | 7 | Example 2: 8 | 9 | Input: s = "foo", t = "bar" 10 | Output: false 11 | 12 | Example 3: 13 | 14 | Input: s = "paper", t = "title" 15 | Output: true 16 | ''' 17 | 18 | class Solution(object): 19 | def isIsomorphic(self, s, t): 20 | """ 21 | :type s: str 22 | :type t: str 23 | :rtype: bool 24 | """ 25 | c1,c2 = [0] * 200, [0] * 200 26 | 27 | for i in range(len(s)): 28 | ord1, ord2 = ord(s[i]), ord(t[i]) 29 | if c1[ord1] != c2[ord2]: 30 | return False 31 | c1[ord1] = i + 1 32 | c2[ord2] = i + 1 33 | return True 34 | 35 | -------------------------------------------------------------------------------- /test_Happy_Number_202.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Happy_Number_202 import Solution 3 | 4 | ''' 5 | Happy Number 6 | Example 1: 7 | Input: n = 19 8 | Output: true 9 | Explanation: 10 | 12 + 92 = 82 11 | 82 + 22 = 68 12 | 62 + 82 = 100 13 | 12 + 02 + 02 = 1 14 | 15 | Example 2: 16 | 17 | Input: n = 2 18 | Output: false 19 | 20 | ''' 21 | 22 | class Test_Case(unittest.TestCase): 23 | 24 | def test_answer_01(self): 25 | n = 19 26 | result = True 27 | self.assertEqual(Solution().isHappy(n), result) 28 | 29 | def test_answer_02(self): 30 | n = 2 31 | result = False 32 | self.assertEqual(Solution().isHappy(n), result) 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /Missing_Number_268.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: nums = [3,0,1] 5 | Output: 2 6 | 7 | Example 2: 8 | 9 | Input: nums = [0,1] 10 | Output: 2 11 | 12 | Example 3: 13 | 14 | Input: nums = [9,6,4,2,3,5,7,0,1] 15 | Output: 8 16 | 17 | Example 4: 18 | 19 | Input: nums = [0] 20 | Output: 1 21 | 22 | ''' 23 | 24 | class Solution(object): 25 | def missingNumber(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | return sum(range(len(nums)+1)) - sum(nums) 31 | 32 | 33 | class Solution(object): 34 | def missingNumber(self, nums): 35 | """ 36 | :type nums: List[int] 37 | :rtype: int 38 | """ 39 | n = len(nums) 40 | return n*(n+1)/2 - sum(nums) 41 | 42 | -------------------------------------------------------------------------------- /Factorial_Trailing_Zeroes_172.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Note: Your solution should be in logarithmic time complexity. 5 | 6 | Example 1: 7 | 8 | Input: n = 3 9 | Output: 0 10 | Explanation: 3! = 6, no trailing zero. 11 | 12 | Example 2: 13 | 14 | Input: n = 5 15 | Output: 1 16 | Explanation: 5! = 120, one trailing zero. 17 | 18 | Example 3: 19 | 20 | Input: n = 0 21 | Output: 0 22 | 23 | ''' 24 | 25 | class Solution(object): 26 | def trailingZeroes(self, n): 27 | """ 28 | :type n: int 29 | :rtype: int 30 | """ 31 | count = 0 32 | check = 5 33 | 34 | while n >= check: 35 | count += n/check 36 | check *= 5 37 | return count 38 | 39 | -------------------------------------------------------------------------------- /Word_Pattern_290.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: pattern = "abba", s = "dog cat cat dog" 5 | Output: true 6 | 7 | Example 2: 8 | 9 | Input: pattern = "abba", s = "dog cat cat fish" 10 | Output: false 11 | 12 | Example 3: 13 | 14 | Input: pattern = "aaaa", s = "dog cat cat dog" 15 | Output: false 16 | 17 | Example 4: 18 | 19 | Input: pattern = "abba", s = "dog dog dog dog" 20 | Output: false 21 | 22 | ''' 23 | 24 | class Solution(object): 25 | def wordPattern(self, pattern, s): 26 | """ 27 | :type pattern: str 28 | :type str: s 29 | :rtype: bool 30 | """ 31 | 32 | s = s.split() 33 | 34 | if len(pattern) != len(s): 35 | return False 36 | 37 | return list(map(pattern.find, pattern)) == list(map(s.index, s)) -------------------------------------------------------------------------------- /Happy_Number_202.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Happy Number 3 | Example 1: 4 | Input: n = 19 5 | Output: true 6 | Explanation: 7 | 12 + 92 = 82 8 | 82 + 22 = 68 9 | 62 + 82 = 100 10 | 12 + 02 + 02 = 1 11 | 12 | Example 2: 13 | 14 | Input: n = 2 15 | Output: false 16 | 17 | ''' 18 | 19 | class Solution(object): 20 | def isHappy(self, n): 21 | """ 22 | :type n: int 23 | :rtype: bool 24 | """ 25 | duplicate = [] 26 | while 1: 27 | sum = 0 28 | for i in str(n): 29 | sum += int(i) ** 2 30 | n = sum 31 | 32 | if n in duplicate: 33 | break 34 | 35 | duplicate.append(n) 36 | 37 | if n == 1: 38 | return True 39 | return False 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Number_of_1_Bits_191.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 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 5 | 6 | ''' 7 | class Solution: 8 | def hammingWeight(self, n: int) -> int: 9 | str_bits = '{:032b}'.format(n) 10 | count = 0 11 | for s in str_bits: 12 | if s == '1': 13 | count += 1 14 | return count 15 | 16 | 17 | class SolutionBitOperations: 18 | def hammingWeight(self, n: int) -> int: 19 | count = 0 20 | while n > 0: 21 | if n & 1: 22 | count += 1 23 | n = n >> 1 24 | return count 25 | -------------------------------------------------------------------------------- /test_Majority_Element_169.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Majority_Element_169 import * 3 | 4 | ''' 5 | Given an array of size n, find the majority element. 6 | 7 | The majority element is the element that appears more than ⌊ n/2 ⌋ times. 8 | Example 1: 9 | 10 | Input: [3,2,3] 11 | Output: 3 12 | 13 | Example 2: 14 | 15 | Input: [2,2,1,1,1,2,2] 16 | Output: 2 17 | ''' 18 | 19 | class Test_Case(unittest.TestCase): 20 | 21 | def test_answer_01(self): 22 | nums = [3,2,3] 23 | result = 3 24 | self.assertEqual(Solution().majorityElement(nums), result) 25 | 26 | def test_answer_02(self): 27 | nums = [2,2,1,1,1,2,2] 28 | result = 2 29 | self.assertEqual(Solution().majorityElement(nums), result) 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /test_Pascals_Triangle_118.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Pascals_Triangle_118 import Solution 3 | 4 | ''' 5 | Input: 5 6 | Output: 7 | [ 8 | [1], 9 | [1,1], 10 | [1,2,1], 11 | [1,3,3,1], 12 | [1,4,6,4,1] 13 | ] 14 | 15 | ''' 16 | 17 | 18 | class Test_Case(unittest.TestCase): 19 | 20 | def test_answer_01(self): 21 | numRows = 5 22 | result = [ 23 | [1], 24 | [1,1], 25 | [1,2,1], 26 | [1,3,3,1], 27 | [1,4,6,4,1] 28 | ] 29 | self.assertEqual(Solution().generate(numRows), result) 30 | 31 | def test_answer_02(self): 32 | numRows = 0 33 | result = [] 34 | self.assertEqual(Solution().generate(numRows), result) 35 | 36 | if __name__ == '__main__': 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /Merge_Two_Sorted_Lists_021_explanation.py: -------------------------------------------------------------------------------- 1 | from Merge_Two_Sorted_Lists_021 import ListNode 2 | 3 | if __name__ == "__main__": 4 | a = b = 3 5 | c = 3 6 | print('a', id(a)) 7 | print('b', id(b)) 8 | print('c', id(c)) 9 | b = 4 10 | print('a', id(a)) 11 | print('b', id(b)) 12 | print('a', a) 13 | print('b', b) 14 | 15 | L1 = L2 = ListNode(0) 16 | L3 = ListNode(0) 17 | print('L1', id(L1)) 18 | print('L2', id(L2)) 19 | print('L3', id(L3)) 20 | print('L1 == L2', L1 == L2) 21 | print('L1 is L2', L1 is L2) 22 | print('L1 == L3', L1 == L3) 23 | print('L1 is L3', L1 is L3) 24 | L2.next = ListNode(1) 25 | print("see L1 and L2 var") 26 | L2 = L2.next 27 | print("see L1 and L2 var") 28 | L2.next = ListNode(2) 29 | print("see L1 and L2 var") 30 | 31 | -------------------------------------------------------------------------------- /Add_Digits_258.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | 4 | For example: 5 | 6 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 7 | 8 | Follow up: 9 | Could you do it without any loop/recursion in O(1) runtime? 10 | 11 | Example 1: 12 | 13 | Input: num = 38 14 | Output: 2 15 | Explanation: The process is 16 | 38 --> 3 + 8 --> 11 17 | 11 --> 1 + 1 --> 2 18 | Since 2 has only one digit, return it. 19 | 20 | Example 2: 21 | 22 | Input: num = 0 23 | Output: 0 24 | 25 | """ 26 | 27 | 28 | class Solution: 29 | def addDigits(self, num: int) -> int: 30 | if num < 10: 31 | return num 32 | elif num % 9 == 0: 33 | return 9 34 | else: 35 | return num % 9 36 | -------------------------------------------------------------------------------- /Delete_Node_in_a_Linked_List_237.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to delete a node in a singly-linked list. 3 | You will not be given access to the head of the list, 4 | instead you will be given access to the node to be deleted directly. 5 | 6 | It is guaranteed that the node to be deleted is not a tail node in the list. 7 | 8 | Input: head = [4,5,1,9], node = 5 9 | Output: [4,1,9] 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | class ListNode(object): 14 | def __init__(self, val): 15 | self.val = val 16 | self.next = None 17 | 18 | class Solution(object): 19 | def deleteNode(self, node): 20 | """ 21 | :type node: ListNode 22 | :rtype: void Do not return anything, modify node in-place instead. 23 | """ 24 | node.val = node.next.val 25 | node.next = node.next.next 26 | -------------------------------------------------------------------------------- /Excel_Sheet_Column_Number_171.py: -------------------------------------------------------------------------------- 1 | """ 2 | Related to question Excel Sheet Column Title 3 | 4 | Given a column title as appear in an Excel sheet, return its corresponding column number. 5 | 6 | For example: 7 | 8 | A -> 1 9 | B -> 2 10 | C -> 3 11 | ... 12 | Z -> 26 13 | AA -> 27 14 | AB -> 28 15 | 16 | Example 1: 17 | 18 | Input: columnTitle = "A" 19 | Output: 1 20 | 21 | Example 2: 22 | 23 | Input: columnTitle = "AB" 24 | Output: 28 25 | 26 | Example 3: 27 | 28 | Input: columnTitle = "ZY" 29 | Output: 701 30 | 31 | """ 32 | 33 | 34 | class Solution: 35 | def titleToNumber(self, columnTitle: str) -> int: 36 | 37 | total = 0 38 | count = 0 39 | 40 | for i in columnTitle[::-1]: 41 | total += (ord(i) - 64) * (26 ** count) 42 | count += 1 43 | return total 44 | -------------------------------------------------------------------------------- /test_Valid_Palindrome_125.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Valid_Palindrome_125 import * 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: "A man, a plan, a canal: Panama" 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: "race a car" 13 | Output: false 14 | ''' 15 | 16 | 17 | class Test_Case(unittest.TestCase): 18 | 19 | def test_answer_01(self): 20 | s = "A man, a plan, a canal: Panama" 21 | result = True 22 | self.assertEqual(Solution().isPalindrome(s), result) 23 | 24 | def test_answer_02(self): 25 | s = "race a car" 26 | result = False 27 | self.assertEqual(Solution().isPalindrome(s), result) 28 | 29 | def test_answer_03(self): 30 | s = "0P" 31 | result = False 32 | self.assertEqual(Solution().isPalindrome(s), result) 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /Maximum_Subarray_053.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 5 | Output: 6 6 | Explanation: [4,-1,2,1] has the largest sum = 6. 7 | 8 | Example 2: 9 | 10 | Input: nums = [1] 11 | Output: 1 12 | 13 | Example 3: 14 | 15 | Input: nums = [0] 16 | Output: 0 17 | 18 | Example 4: 19 | 20 | Input: nums = [-1] 21 | Output: -1 22 | 23 | Example 5: 24 | 25 | Input: nums = [-2147483647] 26 | Output: -2147483647 27 | 28 | ''' 29 | 30 | class Solution: 31 | def maxSubArray(self, nums): 32 | """ 33 | :type nums: List[int] 34 | :rtype: int 35 | """ 36 | if not nums: 37 | return 0 38 | 39 | cur_sum = max_sum = nums[0] 40 | for num in nums[1:]: 41 | cur_sum = max(num, cur_sum + num) 42 | max_sum = max(max_sum, cur_sum) 43 | 44 | return max_sum 45 | -------------------------------------------------------------------------------- /Remove_Duplicates_from_Sorted_Array_026_explanation.py: -------------------------------------------------------------------------------- 1 | # This method of use is not very good 2 | 3 | nums = [1, 2, 3, 4] 4 | 5 | for i in range(len(nums) - 1, 0, -1): 6 | print('i', i) 7 | del nums[i] 8 | print('nums', nums) 9 | 10 | # Confused why the returned value is an integer but your answer is an array? 11 | # nums=[1,1,2] , return len(set(nums)) , output [1,1] ? 12 | 13 | # because will check nums too see if it's content is correct, 14 | # but will check only the first n (the number that you returned) elements. 15 | 16 | # Note that the input array is passed in by reference, 17 | # which means modification to the input array will be known to the caller as well. 18 | 19 | # why del work ? 20 | a = b = [1, 1, 2, 4] 21 | del b[2] 22 | print('a', a) 23 | print('b', b) 24 | 25 | a1 = b1 = [1, 1, 2, 4] 26 | print('a1', a1) 27 | print('set(b1)', set(b1)) 28 | -------------------------------------------------------------------------------- /test_Add_Binary_067.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Add_Binary_067 import Solution 3 | 4 | ''' 5 | Given two binary strings, return their sum (also a binary string). 6 | 7 | The input strings are both non-empty and contains only characters 1 or 0. 8 | 9 | Example 1: 10 | 11 | Input: a = "11", b = "1" 12 | Output: "100" 13 | Example 2: 14 | 15 | Input: a = "1010", b = "1011" 16 | Output: "10101" 17 | ''' 18 | 19 | 20 | class Test_Case(unittest.TestCase): 21 | 22 | def test_answer_01(self): 23 | a = '11' 24 | b = '1' 25 | result = '100' 26 | self.assertEqual(Solution().addBinary(a, b), result) 27 | 28 | def test_answer_02(self): 29 | a = '1010' 30 | b = '1011' 31 | result = '10101' 32 | self.assertEqual(Solution().addBinary(a, b), result) 33 | 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | -------------------------------------------------------------------------------- /Excel_Sheet_Column_Title_168.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 3 | 4 | For example: 5 | 6 | 1 -> A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB 13 | 14 | 15 | Example 1: 16 | 17 | Input: columnNumber = 1 18 | Output: "A" 19 | 20 | Example 2: 21 | 22 | Input: columnNumber = 28 23 | Output: "AB" 24 | 25 | Example 3: 26 | 27 | Input: columnNumber = 701 28 | Output: "ZY" 29 | 30 | """ 31 | 32 | class Solution: 33 | def convertToTitle(self, columnNumber: int) -> str: 34 | res = "" 35 | while columnNumber: 36 | columnNumber, y = columnNumber // 26, columnNumber % 26 37 | if y == 0: 38 | columnNumber -= 1 39 | y = 26 40 | res += chr(y + 64) 41 | 42 | return res[::-1] 43 | -------------------------------------------------------------------------------- /Permutations_046.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: nums = [1,2,3] 5 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 6 | 7 | Example 2: 8 | 9 | Input: nums = [0,1] 10 | Output: [[0,1],[1,0]] 11 | 12 | Example 3: 13 | 14 | Input: nums = [1] 15 | Output: [[1]] 16 | ''' 17 | 18 | import itertools 19 | 20 | class Solution2(object): 21 | def permute(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: List[List[int]] 25 | """ 26 | return itertools.permutations(nums, len(nums)) 27 | 28 | 29 | class Solution(object): 30 | def permute(self, nums): 31 | res = [] 32 | self.dfs(nums, [], res) 33 | return res 34 | 35 | def dfs(self, nums, one_ans, res): 36 | if not nums: 37 | res.append(one_ans) 38 | for i in range(len(nums)): 39 | self.dfs(nums[:i]+nums[i+1:], one_ans+[nums[i]], res) -------------------------------------------------------------------------------- /Nim_Game_292.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | 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. 5 | 6 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 7 | 8 | Example 1: 9 | 10 | Input: n = 4 11 | Output: false 12 | 13 | Example 2: 14 | 15 | Input: n = 1 16 | Output: true 17 | 18 | Example 3: 19 | 20 | Input: n = 2 21 | Output: true 22 | ''' 23 | 24 | class Solution(object): 25 | def canWinNim(self, n: int) -> bool: 26 | return n %4 >0 27 | -------------------------------------------------------------------------------- /test_Single_Number_II_137.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Single_Number_II_137 import Solution 3 | 4 | """ 5 | Given an array of integers, every element appears three times except for one. Find that single one. 6 | 7 | Note: 8 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | 10 | Example 1: 11 | 12 | Input: nums = [2,2,3,2] 13 | Output: 3 14 | 15 | Example 2: 16 | 17 | Input: nums = [0,1,0,1,0,1,99] 18 | Output: 99 19 | 20 | """ 21 | 22 | 23 | class Test_Case(unittest.TestCase): 24 | def test_answer_01(self): 25 | nums = [2,2,3,2] 26 | result = 3 27 | self.assertEqual(Solution().singleNumber(nums), result) 28 | 29 | def test_answer_02(self): 30 | nums = [0,1,0,1,0,1,99] 31 | result = 99 32 | self.assertEqual(Solution().singleNumber(nums), result) 33 | 34 | 35 | if __name__ == "__main__": 36 | unittest.main() 37 | -------------------------------------------------------------------------------- /logic_tutorial.py: -------------------------------------------------------------------------------- 1 | 2 | def trunk_1(arr_1, size_1): 3 | result_1 = [] 4 | while arr: 5 | pop_data = [arr_1.pop(0) for _ in range(size_1)] 6 | result_1.append(pop_data) 7 | return result_1 8 | 9 | 10 | def trunk_2(arr_2, size_2): 11 | arrs = [] 12 | while len(arr_2) > size_2: 13 | pice = arr_2[:size_2] 14 | arrs.append(pice) 15 | arr_2 = arr_2[size:] 16 | arrs.append(arr_2) 17 | return arrs 18 | 19 | 20 | def trunk_3(arr, size): 21 | result = [] 22 | 23 | count = 0 24 | while count < len(arr): 25 | result.append(arr[count:count+size]) 26 | count += size 27 | return result 28 | 29 | 30 | if __name__ == "__main__": 31 | ''' 32 | arr = [1, 2, 3, 4, 5, 6] 33 | size = 2 34 | result = [[1, 2], [3, 4], [5, 6]] 35 | ''' 36 | arr = [1, 2, 3, 4, 5, 6] 37 | size = 2 38 | result = trunk_1(arr, size) 39 | print(result) 40 | -------------------------------------------------------------------------------- /Merge_Intervals_056.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Example 1: 4 | 5 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 6 | Output: [[1,6],[8,10],[15,18]] 7 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 8 | 9 | Example 2: 10 | 11 | Input: intervals = [[1,4],[4,5]] 12 | Output: [[1,5]] 13 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 14 | 15 | ''' 16 | 17 | class Solution(object): 18 | def merge(self, intervals): 19 | """ 20 | :type intervals: List[List[int]] 21 | :rtype: List[List[int]] 22 | """ 23 | 24 | result = [] 25 | intervals.sort() 26 | 27 | for i in range(len(intervals)): 28 | if result and result[-1][1] >= intervals[i][0]: 29 | if result[-1][1] < intervals[i][1]: 30 | result[-1][1] = intervals[i][1] 31 | continue 32 | result.append(intervals[i]) 33 | return result -------------------------------------------------------------------------------- /Reverse_Words_in_a_String_151.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: s = "the sky is blue" 5 | Output: "blue is sky the" 6 | 7 | Example 2: 8 | 9 | Input: s = " hello world " 10 | Output: "world hello" 11 | Explanation: Your reversed string should not contain leading or trailing spaces. 12 | 13 | Example 3: 14 | 15 | Input: s = "a good example" 16 | Output: "example good a" 17 | Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 18 | 19 | Example 4: 20 | 21 | Input: s = " Bob Loves Alice " 22 | Output: "Alice Loves Bob" 23 | 24 | Example 5: 25 | 26 | Input: s = "Alice does not even like bob" 27 | Output: "bob like even not does Alice" 28 | 29 | ''' 30 | 31 | class Solution(object): 32 | def reverseWords(self, s): 33 | """ 34 | :type s: str 35 | :rtype: str 36 | """ 37 | temp = s.split() 38 | return ' '.join(temp[::-1]) 39 | 40 | -------------------------------------------------------------------------------- /test_Power_of_Two_231.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Power_of_Two_231 import Solution 3 | 4 | ''' 5 | Given an integer, write a function to determine if it is a power of two. 6 | 7 | Example 1: 8 | 9 | Input: n = 1 10 | Output: true 11 | 12 | Example 2: 13 | 14 | Input: n = 16 15 | Output: true 16 | 17 | Example 3: 18 | 19 | Input: n = 3 20 | Output: false 21 | 22 | ''' 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | n = 1 28 | result = True 29 | 30 | self.assertEqual(Solution().isPowerOfTwo(n), result) 31 | 32 | def test_answer_02(self): 33 | n = 16 34 | result = True 35 | 36 | self.assertEqual(Solution().isPowerOfTwo(n), result) 37 | 38 | def test_answer_03(self): 39 | n = 3 40 | result = False 41 | 42 | self.assertEqual(Solution().isPowerOfTwo(n), result) 43 | 44 | if __name__ == '__main__': 45 | unittest.main() 46 | -------------------------------------------------------------------------------- /Remove_Duplicates_from_Sorted_Array_II_080.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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 | Input: nums = [1,1,1,2,2,3] 8 | Output: 5, nums = [1,1,2,2,3] 9 | 10 | Example 2: 11 | Input: nums = [0,0,1,1,1,1,2,3,3] 12 | Output: 7, nums = [0,0,1,1,2,3,3] 13 | ''' 14 | 15 | class Solution: 16 | def removeDuplicates(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: int 20 | """ 21 | count = 0 22 | for i in range(len(nums)-1, 0, -1): 23 | if nums[i] == nums[i-1]: 24 | count += 1 25 | if count >1: 26 | del nums[i] 27 | else: 28 | count = 0 29 | return len(nums) 30 | -------------------------------------------------------------------------------- /Single_Number_II_137.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | ''' 4 | Given an array of integers, every element appears three times except for one. Find that single one. 5 | 6 | Note: 7 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 8 | 9 | Example 1: 10 | 11 | Input: nums = [2,2,3,2] 12 | Output: 3 13 | 14 | Example 2: 15 | 16 | Input: nums = [0,1,0,1,0,1,99] 17 | Output: 99 18 | 19 | ''' 20 | class Solution: 21 | def singleNumber(self, nums: List[int]) -> int: 22 | """ 23 | ^ -> XOR 24 | a=0 b=0 0 25 | a=0 b=1 1 26 | a=1 b=0 1 27 | a=1 b=1 0 28 | 29 | 1 & 1 1 30 | 1 & ~1 0 31 | 32 | 33 | one 紀錄出現一次的數字 34 | two 紀錄出現兩次的數字 35 | """ 36 | one = two = 0 37 | for num in nums: 38 | one = (one ^ num) & ~two 39 | two = (two ^ num) & ~one 40 | 41 | return one 42 | 43 | -------------------------------------------------------------------------------- /test_Merge_Sorted_Array_088.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Merge_Sorted_Array_088 import Solution 3 | 4 | ''' 5 | Given two sorted integer arrays nums1 and nums2, 6 | merge nums2 into nums1 as one sorted array. 7 | 8 | Input: 9 | nums1 = [1,2,3,0,0,0], m = 3 10 | nums2 = [2,5,6], n = 3 11 | 12 | Output: [1,2,2,3,5,6] 13 | ''' 14 | 15 | 16 | class Test_Case(unittest.TestCase): 17 | 18 | def test_answer_01(self): 19 | 20 | nums1 = [1,2,3,0,0,0] 21 | m = 3 22 | nums2 = [2,5,6] 23 | n = 3 24 | 25 | result = [1,2,2,3,5,6] 26 | 27 | self.assertEqual(Solution().merge(nums1, m, nums2, n), result) 28 | 29 | 30 | def test_answer_02(self): 31 | 32 | nums1 = [2,0] 33 | m = 1 34 | nums2 = [1] 35 | n = 1 36 | 37 | result = [1,2] 38 | 39 | self.assertEqual(Solution().merge(nums1, m, nums2, n), result) 40 | 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /Count_and_Say_038.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | ''' 4 | The count-and-say sequence is the sequence of integers with the first five terms as following: 5 | 6 | 1. 1 7 | 2. 11 8 | 3. 21 9 | 4. 1211 10 | 5. 111221 11 | 1 is read off as "one 1" or 11. 12 | 11 is read off as "two 1s" or 21. 13 | 21 is read off as "one 2, then one 1" or 1211. 14 | 15 | The following are the terms from n=1 to n=10 of the count-and-say sequence: 16 | 1. 1 17 | 2. 11 18 | 3. 21 19 | 4. 1211 20 | 5. 111221 21 | 6. 312211 22 | 7. 13112221 23 | 8. 1113213211 24 | 9. 31131211131221 25 | 10. 13211311123113112211 26 | ''' 27 | 28 | 29 | class Solution: 30 | def countAndSay(self, n): 31 | """ 32 | :type n: int 33 | :rtype: str 34 | """ 35 | s = '1' 36 | for _ in range(n - 1): 37 | s = ''.join(str(len(list(group))) + key 38 | for key, group in itertools.groupby(s)) 39 | return s 40 | -------------------------------------------------------------------------------- /Plus_One_066.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 | Example 2: 14 | 15 | Input: [4,3,2,1] 16 | Output: [4,3,2,2] 17 | Explanation: The array represents the integer 4321. 18 | ''' 19 | 20 | class Solution: 21 | def plusOne(self, digits): 22 | """ 23 | :type digits: List[int] 24 | :rtype: List[int] 25 | """ 26 | if digits and (digits[-1] + 1) < 10: 27 | digits[-1] = digits[-1] + 1 28 | return digits 29 | num = int("".join(str(d) for d in digits)) + 1 30 | return [int(s) for s in str(num)] 31 | 32 | -------------------------------------------------------------------------------- /Ugly_Number_263.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program to check whether a given number is an ugly number. 3 | 4 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 5 | 6 | Note that 1 is typically treated as an ugly number. 7 | 8 | 9 | Example 1: 10 | 11 | Input: n = 6 12 | Output: true 13 | Explanation: 6 = 2 × 3 14 | 15 | Example 2: 16 | 17 | Input: n = 1 18 | Output: true 19 | Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 20 | 21 | Example 3: 22 | 23 | Input: n = 14 24 | Output: false 25 | Explanation: 14 is not ugly since it includes the prime factor 7. 26 | 27 | """ 28 | 29 | 30 | class Solution: 31 | def isUgly(self, n: int) -> bool: 32 | only = [2, 3, 5] 33 | if n == 0: 34 | return False 35 | for i in only: 36 | while n % i == 0: 37 | n = n / i 38 | return n == 1 39 | -------------------------------------------------------------------------------- /test_Single_Number_136.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Single_Number_136 import Solution 3 | 4 | """ 5 | Given an array of integers, every element appears twice except for one. 6 | Find that single one. 7 | 8 | Example 1: 9 | 10 | Input: nums = [2,2,1] 11 | Output: 1 12 | 13 | Example 2: 14 | 15 | Input: nums = [4,1,2,1,2] 16 | Output: 4 17 | 18 | Example 3: 19 | 20 | Input: nums = [1] 21 | Output: 1 22 | 23 | """ 24 | 25 | 26 | class Test_Case(unittest.TestCase): 27 | def test_answer_01(self): 28 | nums = [2, 2, 1] 29 | result = 1 30 | self.assertEqual(Solution().singleNumber(nums), result) 31 | 32 | def test_answer_02(self): 33 | nums = [4, 1, 2, 1, 2] 34 | result = 4 35 | self.assertEqual(Solution().singleNumber(nums), result) 36 | 37 | def test_answer_03(self): 38 | nums = [1] 39 | result = 1 40 | self.assertEqual(Solution().singleNumber(nums), result) 41 | 42 | 43 | if __name__ == "__main__": 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /test_Contains_Duplicate_217.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Contains_Duplicate_217 import * 3 | 4 | ''' 5 | Given an array of integers, 6 | find if the array contains any duplicates. 7 | 8 | Example 1: 9 | 10 | Input: [1,2,3,1] 11 | Output: true 12 | 13 | Example 2: 14 | 15 | Input: [1,2,3,4] 16 | Output: false 17 | 18 | Example 3: 19 | 20 | Input: [1,1,1,3,3,4,3,2,4,2] 21 | Output: true 22 | ''' 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | nums = [1,2,3,1] 28 | result = True 29 | self.assertEqual(Solution().containsDuplicate(nums), result) 30 | 31 | def test_answer_02(self): 32 | nums = [1,2,3,4] 33 | result = False 34 | self.assertEqual(Solution().containsDuplicate(nums), result) 35 | 36 | def test_answer_03(self): 37 | nums = [1,1,1,3,3,4,3,2,4,2] 38 | result = True 39 | self.assertEqual(Solution().containsDuplicate(nums), result) 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /test_Power_of_Three_326.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Power_of_Three_326 import Solution 3 | 4 | ''' 5 | Given an integer, write a function to determine if it is a power of three. 6 | 7 | Follow up: 8 | Could you do it without using any loop / recursion? 9 | 10 | Example 1: 11 | 12 | Input: n = 27 13 | Output: true 14 | 15 | Example 2: 16 | 17 | Input: n = 0 18 | Output: false 19 | 20 | Example 3: 21 | 22 | Input: n = 9 23 | Output: true 24 | 25 | ''' 26 | 27 | 28 | class Test_Case(unittest.TestCase): 29 | 30 | def test_answer_01(self): 31 | n = 27 32 | result = True 33 | 34 | self.assertEqual(Solution().isPowerOfThree(n), result) 35 | 36 | def test_answer_02(self): 37 | n = 0 38 | result = False 39 | 40 | self.assertEqual(Solution().isPowerOfThree(n), result) 41 | 42 | def test_answer_03(self): 43 | n = 9 44 | result = True 45 | 46 | self.assertEqual(Solution().isPowerOfThree(n), result) 47 | 48 | if __name__ == '__main__': 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /test_Length_of_Last_Word_058.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Length_of_Last_Word_058 import * 3 | 4 | ''' 5 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 6 | 7 | If the last word does not exist, return 0. 8 | 9 | Note: A word is defined as a character sequence consists of non-space characters only. 10 | 11 | Example: 12 | 13 | Input: "Hello World" 14 | Output: 5 15 | ''' 16 | 17 | 18 | class Test_Case(unittest.TestCase): 19 | 20 | def test_answer_01(self): 21 | s = "Hello World" 22 | result = 5 23 | self.assertEqual(Solution().lengthOfLastWord(s), result) 24 | 25 | def test_answer_02(self): 26 | s = "a " 27 | result = 1 28 | self.assertEqual(Solution().lengthOfLastWord(s), result) 29 | 30 | def test_answer_03(self): 31 | s = " " 32 | result = 0 33 | self.assertEqual(Solution().lengthOfLastWord(s), result) 34 | 35 | 36 | if __name__ == '__main__': 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /Implement_strStr_028.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement strStr(). 3 | 4 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | 6 | Example 1: 7 | Input: haystack = "hello", needle = "ll" 8 | Output: 2 9 | 10 | Example 2: 11 | Input: haystack = "aaaaa", needle = "bba" 12 | Output: -1 13 | 14 | What should we return when needle is an empty string? This is a great question to ask during an interview. 15 | ''' 16 | 17 | class Solution: 18 | def strStr(self, haystack, needle): 19 | """ 20 | :type haystack: str 21 | :type needle: str 22 | :rtype: int 23 | """ 24 | return haystack.find(needle) 25 | 26 | 27 | class Solution_Logic: 28 | def strStr(self, haystack, needle): 29 | """ 30 | :type haystack: str 31 | :type needle: str 32 | :rtype: int 33 | """ 34 | for i in range(len(haystack) - len(needle) + 1): 35 | if haystack[i:i + len(needle)] == needle: 36 | return i 37 | return -1 38 | -------------------------------------------------------------------------------- /Container_With_Most_Water_011.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Input: height = [1,8,6,2,5,4,8,3,7] 3 | Output: 49 4 | Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 5 | 6 | Example 2: 7 | 8 | Input: height = [1,1] 9 | Output: 1 10 | 11 | Example 3: 12 | 13 | Input: height = [4,3,2,1,4] 14 | Output: 16 15 | 16 | Example 4: 17 | 18 | Input: height = [1,2,1] 19 | Output: 2 20 | 21 | ''' 22 | 23 | class Solution(object): 24 | def maxArea(self, height): 25 | """ 26 | :type height: List[int] 27 | :rtype: int 28 | """ 29 | left = 0 30 | right = len(height) - 1 31 | area = 0 32 | 33 | while left < right: 34 | area = max( 35 | min(height[left], height[right]) * (right - left), 36 | area 37 | ) 38 | 39 | if height[left]> height[right]: 40 | right -= 1 41 | else: 42 | left += 1 43 | 44 | return area 45 | 46 | -------------------------------------------------------------------------------- /test_Add_Digits_258.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Add_Digits_258 import Solution 3 | 4 | """ 5 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 6 | 7 | For example: 8 | 9 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. 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 | Example 1: 15 | 16 | Input: num = 38 17 | Output: 2 18 | Explanation: The process is 19 | 38 --> 3 + 8 --> 11 20 | 11 --> 1 + 1 --> 2 21 | Since 2 has only one digit, return it. 22 | 23 | Example 2: 24 | 25 | Input: num = 0 26 | Output: 0 27 | 28 | """ 29 | 30 | 31 | class Test_Case(unittest.TestCase): 32 | def test_answer_01(self): 33 | num = 38 34 | result = 2 35 | self.assertEqual(Solution().addDigits(num), result) 36 | 37 | def test_answer_02(self): 38 | num = 0 39 | result = 0 40 | self.assertEqual(Solution().addDigits(num), result) 41 | 42 | if __name__ == "__main__": 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /test_Valid_Anagram_242.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Valid_Anagram_242 import * 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: s = "anagram", t = "nagaram" 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: s = "rat", t = "car" 13 | Output: false 14 | 15 | ''' 16 | 17 | class Test_Case(unittest.TestCase): 18 | 19 | def test_answer_01(self): 20 | s = "anagram" 21 | t = "nagaram" 22 | result = True 23 | self.assertEqual(Solution().isAnagram(s, t), result) 24 | 25 | def test_answer_02(self): 26 | s = "rat" 27 | t = "car" 28 | result = False 29 | self.assertEqual(Solution().isAnagram(s, t), result) 30 | 31 | def test_answer_03(self): 32 | s = "a" 33 | t = "ab" 34 | result = False 35 | self.assertEqual(Solution().isAnagram(s, t), result) 36 | 37 | def test_answer_04(self): 38 | s = "ac" 39 | t = "bb" 40 | result = False 41 | self.assertEqual(Solution().isAnagram(s, t), result) 42 | 43 | if __name__ == '__main__': 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /test_Implement_strStr_028.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Implement_strStr_028 import * 3 | 4 | ''' 5 | Implement strStr(). 6 | 7 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 8 | 9 | Example 1: 10 | Input: haystack = "hello", needle = "ll" 11 | Output: 2 12 | 13 | Example 2: 14 | Input: haystack = "aaaaa", needle = "bba" 15 | Output: -1 16 | ''' 17 | 18 | 19 | class Test_Case(unittest.TestCase): 20 | 21 | def test_answer_01(self): 22 | haystack = "hello" 23 | needle = "ll" 24 | result = 2 25 | self.assertEqual(Solution().strStr(haystack, needle), result) 26 | 27 | def test_answer_02(self): 28 | haystack = "aaaaa" 29 | needle = "bba" 30 | result = -1 31 | self.assertEqual(Solution().strStr(haystack, needle), result) 32 | 33 | def test_answer_03(self): 34 | haystack = "" 35 | needle = "" 36 | result = 0 37 | self.assertEqual(Solution().strStr(haystack, needle), result) 38 | 39 | 40 | if __name__ == '__main__': 41 | unittest.main() 42 | -------------------------------------------------------------------------------- /test_Missing_Number_268.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Missing_Number_268 import Solution 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: nums = [3,0,1] 8 | Output: 2 9 | 10 | Example 2: 11 | 12 | Input: nums = [0,1] 13 | Output: 2 14 | 15 | Example 3: 16 | 17 | Input: nums = [9,6,4,2,3,5,7,0,1] 18 | Output: 8 19 | 20 | Example 4: 21 | 22 | Input: nums = [0] 23 | Output: 1 24 | ''' 25 | 26 | class Test_Case(unittest.TestCase): 27 | 28 | def test_answer_01(self): 29 | nums = [3,0,1] 30 | result = 2 31 | self.assertEqual(Solution().missingNumber(nums), result) 32 | 33 | def test_answer_02(self): 34 | nums = [0,1] 35 | result = 2 36 | self.assertEqual(Solution().missingNumber(nums), result) 37 | 38 | def test_answer_03(self): 39 | nums = [9,6,4,2,3,5,7,0,1] 40 | result = 8 41 | self.assertEqual(Solution().missingNumber(nums), result) 42 | 43 | def test_answer_04(self): 44 | nums = [0] 45 | result = 1 46 | self.assertEqual(Solution().missingNumber(nums), result) 47 | 48 | if __name__ == '__main__': 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /Remove_Element_027.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 | Output: 2, nums = [2,2] 11 | 12 | 13 | Example 2: 14 | Given nums = [0,1,2,2,3,0,4,2], val = 2, 15 | Output: 5, nums = [0,1,4,0,3] 16 | 17 | ''' 18 | 19 | class Solution: 20 | def removeElement(self, nums, val): 21 | """ 22 | :type nums: List[int] 23 | :type val: int 24 | :rtype: int 25 | """ 26 | while val in nums: 27 | nums.remove(val) 28 | return len(nums) 29 | 30 | class Solution2: 31 | def removeElement(self, nums, val): 32 | """ 33 | :type nums: List[int] 34 | :type val: int 35 | :rtype: int 36 | """ 37 | nums[:] = [num for num in nums if num != val] 38 | return len(nums) 39 | -------------------------------------------------------------------------------- /Move_Zeroes_283.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums, write a function to move all 0's 3 | to the end of it while maintaining the relative order 4 | of the non-zero elements. 5 | 6 | Example: 7 | 8 | Input: [0,1,0,3,12] 9 | Output: [1,3,12,0,0] 10 | 11 | ''' 12 | class Solution(object): 13 | def moveZeroes(self, nums): 14 | """ 15 | :type nums: List[int] 16 | :rtype: void Do not return anything, modify nums in-place instead. 17 | """ 18 | count = 0 19 | while 0 in nums: 20 | nums.remove(0) 21 | count += 1 22 | nums[:] = nums[:] + [0] * count 23 | return nums 24 | 25 | class Solution2(object): 26 | def moveZeroes(self, nums): 27 | """ 28 | :type nums: List[int] 29 | :rtype: void Do not return anything, modify nums in-place instead. 30 | """ 31 | for i in range(len(nums)): 32 | if nums[i] != 0: 33 | nums[count] = nums[i] 34 | count += 1 35 | 36 | while count < len(nums): 37 | nums[count] = 0 38 | count += 1 39 | 40 | return nums 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Sqrtx_069.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer x, compute and return the square root of x. 3 | 4 | Since the return type is an integer, the decimal digits are truncated, 5 | 6 | and only the integer part of the result is returned 7 | 8 | Example 1: 9 | 10 | Input: 4 11 | Output: 2 12 | Example 2: 13 | 14 | Input: 8 15 | Output: 2 16 | Explanation: The square root of 8 is 2.82842..., and since 17 | the decimal part is truncated, 2 is returned. 18 | ''' 19 | 20 | import math 21 | 22 | class SolutionLibrary: 23 | def mySqrt(self, x): 24 | return int(math.sqrt(x)) 25 | 26 | class Solution: 27 | # Binary Search 28 | def mySqrt(self, x): 29 | """ 30 | :type x: int 31 | :rtype: int 32 | """ 33 | if x == 0: 34 | return 0 35 | 36 | left = 1 37 | right = x // 2 + 1 38 | 39 | while left <= right: 40 | mid = (right + left) // 2 41 | if mid ** 2 <= x < (mid+1) ** 2: 42 | return mid 43 | 44 | if mid ** 2 > x: 45 | right = mid - 1 46 | else: 47 | left = mid + 1 48 | -------------------------------------------------------------------------------- /Reverse_Integer_007.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | Input: 123 4 | Output: 321 5 | 6 | Example 2: 7 | Input: -123 8 | Output: -321 9 | 10 | Example 3: 11 | Input: 120 12 | Output: 21 13 | 14 | Note: 15 | Assume we are dealing with an environment which could only store integers within the 16 | 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, 17 | assume that your function returns 0 when the reversed integer overflows. 18 | ''' 19 | 20 | 21 | class Solution_Brute_Force: 22 | def reverse(self, x: int) -> int: 23 | reversed_int = int(str(abs(x))[::-1]) 24 | if reversed_int >= 2 ** 31 - 1 or x == 0: 25 | return 0 26 | 27 | return reversed_int * -1 if x < 0 else reversed_int 28 | 29 | 30 | class Solution: 31 | def reverse(self, x: int) -> int: 32 | # without converting the integer to a string 33 | flag = -1 if x < 0 else 1 34 | x = abs(x) 35 | result = 0 36 | while x: 37 | result = result * 10 + x % 10 38 | x = x // 10 39 | 40 | if result >= 2 ** 31 - 1: 41 | return 0 42 | 43 | return result * flag 44 | -------------------------------------------------------------------------------- /Rotate_Array_189.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Given an array, rotate the array 4 | 5 | to the right by k steps, where k is non-negative. 6 | 7 | Follow up: 8 | 9 | Try to come up as many solutions as you can, 10 | there are at least 3 different ways to solve this problem. 11 | Could you do it in-place with O(1) extra space? 12 | 13 | 14 | Input: nums = [1,2,3,4,5,6,7], k = 3 15 | Output: [5,6,7,1,2,3,4] 16 | Explanation: 17 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 18 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 19 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 20 | 21 | 22 | Input: nums = [-1,-100,3,99], k = 2 23 | Output: [3,99,-1,-100] 24 | Explanation: 25 | rotate 1 steps to the right: [99,-1,-100,3] 26 | rotate 2 steps to the right: [3,99,-1,-100] 27 | ''' 28 | 29 | class Solution(object): 30 | def rotate(self, nums, k): 31 | """ 32 | :type nums: List[int] 33 | :type k: int 34 | :rtype: None Do not return anything, modify nums in-place instead. 35 | """ 36 | 37 | if k > len(nums): 38 | index = k % len(nums) 39 | return nums[-index:] + nums[:-index] 40 | 41 | return nums[-k:]+nums[:-k] 42 | -------------------------------------------------------------------------------- /test_Climbing_Stairs_070.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Climbing_Stairs_070 import Solution 3 | 4 | ''' 5 | You are climbing a stair case. It takes n steps to reach to the top. 6 | 7 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | 9 | Note: Given n will be a positive integer. 10 | 11 | Example 1: 12 | 13 | Input: 2 14 | Output: 2 15 | Explanation: There are two ways to climb to the top. 16 | 1. 1 step + 1 step 17 | 2. 2 steps 18 | Example 2: 19 | 20 | Input: 3 21 | Output: 3 22 | Explanation: There are three ways to climb to the top. 23 | 1. 1 step + 1 step + 1 step 24 | 2. 1 step + 2 steps 25 | 3. 2 steps + 1 step 26 | ''' 27 | 28 | 29 | class Test_Case(unittest.TestCase): 30 | 31 | def test_answer_01(self): 32 | n = 2 33 | result = 2 34 | self.assertEqual(Solution().climbStairs(n), result) 35 | 36 | def test_answer_02(self): 37 | n = 3 38 | result = 3 39 | self.assertEqual(Solution().climbStairs(n), result) 40 | 41 | def test_answer_03(self): 42 | n = 4 43 | result = 5 44 | self.assertEqual(Solution().climbStairs(n), result) 45 | 46 | if __name__ == '__main__': 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /test_Contains_Duplicate_II_219.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Contains_Duplicate_II_219 import * 3 | 4 | ''' 5 | Given an array of integers and an integer k, 6 | find out whether there are two distinct indices i and j 7 | in the array such that nums[i] = nums[j] 8 | and the absolute difference between i and j is at most k. 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,2,3,1], k = 3 13 | Output: true 14 | 15 | Example 2: 16 | 17 | Input: nums = [1,0,1,1], k = 1 18 | Output: true 19 | 20 | Example 3: 21 | 22 | Input: nums = [1,2,3,1,2,3], k = 2 23 | Output: false 24 | ''' 25 | 26 | class Test_Case(unittest.TestCase): 27 | 28 | def test_answer_01(self): 29 | nums = [1,2,3,1] 30 | k = 3 31 | result = True 32 | self.assertEqual(Solution().containsNearbyDuplicate(nums, k), result) 33 | 34 | def test_answer_02(self): 35 | nums = [1,0,1,1] 36 | k = 1 37 | result = True 38 | self.assertEqual(Solution().containsNearbyDuplicate(nums, k), result) 39 | 40 | def test_answer_03(self): 41 | nums = [1,2,3,1,2,3] 42 | k = 2 43 | result = False 44 | self.assertEqual(Solution().containsNearbyDuplicate(nums, k), result) 45 | 46 | if __name__ == '__main__': 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /test_Remove_Duplicates_from_Sorted_Array_026.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Remove_Duplicates_from_Sorted_Array_026 import * 3 | 4 | ''' 5 | Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | Example 1: 10 | Given nums = [1,1,2], 11 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 12 | It doesn't matter what you leave beyond the returned length. 13 | 14 | Example 2: 15 | Given nums = [0,0,1,1,1,2,2,3,3,4], 16 | Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. 17 | It doesn't matter what values are set beyond the returned length. 18 | ''' 19 | 20 | 21 | class Test_Case(unittest.TestCase): 22 | 23 | def test_answer_01(self): 24 | nums = [1, 1, 2] 25 | result = 2 26 | self.assertEqual(Solution().removeDuplicates(nums), result) 27 | 28 | def test_answer_02(self): 29 | nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] 30 | result = 5 31 | self.assertEqual(Solution().removeDuplicates(nums), result) 32 | -------------------------------------------------------------------------------- /Climbing_Stairs_070.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | 6 | Note: Given n will be a positive integer. 7 | 8 | Example 1: 9 | 10 | Input: 2 11 | Output: 2 12 | Explanation: There are two ways to climb to the top. 13 | 1. 1 step + 1 step 14 | 2. 2 steps 15 | Example 2: 16 | 17 | Input: 3 18 | Output: 3 19 | Explanation: There are three ways to climb to the top. 20 | 1. 1 step + 1 step + 1 step 21 | 2. 1 step + 2 steps 22 | 3. 2 steps + 1 step 23 | ''' 24 | 25 | 26 | class Solution2: 27 | def climbStairs(self, n): 28 | """ 29 | :type n: int 30 | :rtype: int 31 | """ 32 | # fibonacci 33 | # 1 -> 2 -> 3 -> 5 -> 8 34 | a = 1 35 | b = 1 36 | for _ in range(n): 37 | a, b = b, a + b 38 | return a 39 | 40 | # Time Limit Exceeded 41 | class SolutionBruteForce: 42 | def climbStairs(self, n): 43 | """ 44 | :type n: int 45 | :rtype: int 46 | """ 47 | if n == 1: 48 | return 1 49 | 50 | if n == 2: 51 | return 2 52 | 53 | return self.climbStairs(n-1) + self.climbStairs(n-2) 54 | -------------------------------------------------------------------------------- /Reverse_Bits_190.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse bits of a given 32 bits unsigned integer. 3 | 4 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 5 | 6 | Follow up: 7 | If this function is called many times, how would you optimize it? 8 | 9 | Related problem: Reverse Integer 10 | ''' 11 | 12 | # 可參考 https://www.youtube.com/watch?v=K0EHvvbUdEg 13 | 14 | 15 | class Solution: 16 | # Base2 17 | # without converting the integer to a string 18 | def reverseBits(self, n: int) -> int: 19 | ans = 0 20 | for _ in range(32): 21 | ans = ans * 2 + n % 2 22 | n = n // 2 23 | return ans 24 | 25 | class Solution2: 26 | # Base2 27 | def reverseBits(self, n: int) -> int: 28 | if n == 0: 29 | return 0 30 | 31 | str_tmp = '' 32 | for _ in range(32): 33 | str_tmp += str(n % 2) 34 | n = n // 2 35 | 36 | return int(str_tmp, 2) # 轉換為整數 37 | 38 | class SolutionBitOperations: 39 | def reverseBits(self, n: int) -> int: 40 | ans = 0 41 | for _ in range(32): 42 | ans = (ans << 1) | (n & 1) 43 | n = n >> 1 44 | return ans 45 | -------------------------------------------------------------------------------- /test_3Sum_015.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from P3Sum_015 import * 3 | 4 | ''' 5 | Given an array nums of n integers, are there elements 6 | a, b, c in nums such that a + b + c = 0? 7 | Find all unique triplets in the array which gives the sum of zero. 8 | 9 | Notice that the solution set must not contain duplicate triplets. 10 | 11 | Example 1: 12 | Input: nums = [-1,0,1,2,-1,-4] 13 | Output: [[-1,-1,2],[-1,0,1]] 14 | 15 | Example 2: 16 | Input: nums = [] 17 | Output: [] 18 | 19 | Example 3: 20 | Input: nums = [0] 21 | Output: [] 22 | ''' 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | nums = [-1,0,1,2,-1,-4] 28 | result = [[-1,-1,2],[-1,0,1]] 29 | self.assertEqual(Solution().threeSum(nums), result) 30 | 31 | def test_answer_02(self): 32 | nums = [] 33 | result = [] 34 | self.assertEqual(Solution().threeSum(nums), result) 35 | 36 | def test_answer_03(self): 37 | nums = [0] 38 | result = [] 39 | self.assertEqual(Solution().threeSum(nums), result) 40 | 41 | def test_answer_04(self): 42 | nums = [0, 0, 0, 0] 43 | result = [[0, 0, 0]] 44 | self.assertEqual(Solution().threeSum(nums), result) 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /test_Container_With_Most_Water_011.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Container_With_Most_Water_011 import * 3 | 4 | ''' 5 | Input: height = [1,8,6,2,5,4,8,3,7] 6 | Output: 49 7 | Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 8 | 9 | Example 2: 10 | 11 | Input: height = [1,1] 12 | Output: 1 13 | 14 | Example 3: 15 | 16 | Input: height = [4,3,2,1,4] 17 | Output: 16 18 | 19 | Example 4: 20 | 21 | Input: height = [1,2,1] 22 | Output: 2 23 | ''' 24 | 25 | class Test_Case(unittest.TestCase): 26 | 27 | def test_answer_01(self): 28 | height = [1,8,6,2,5,4,8,3,7] 29 | result = 49 30 | self.assertEqual(Solution().maxArea(height), result) 31 | 32 | def test_answer_02(self): 33 | height = [1,1] 34 | result = 1 35 | self.assertEqual(Solution().maxArea(height), result) 36 | 37 | def test_answer_03(self): 38 | height = [4,3,2,1,4] 39 | result = 16 40 | self.assertEqual(Solution().maxArea(height), result) 41 | 42 | def test_answer_04(self): 43 | height = [1,2,1] 44 | result = 2 45 | self.assertEqual(Solution().maxArea(height), result) 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /test_Two_Sum_001.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Two_Sum_001 import * 3 | 4 | ''' 5 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 6 | 7 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 8 | 9 | Example: 10 | 11 | Given nums = [2, 7, 11, 15], target = 9, 12 | 13 | Because nums[0] + nums[1] = 2 + 7 = 9, 14 | return [0, 1]. 15 | ''' 16 | 17 | 18 | class Test_Case(unittest.TestCase): 19 | 20 | def test_answer_01(self): 21 | nums = [2, 7, 11, 15] 22 | target = 9 23 | self.assertEqual(Solution_better().twoSum(nums, target), [0, 1]) 24 | 25 | def test_answer_02(self): 26 | nums = [2, 7, 11, 15] 27 | target = 9 28 | self.assertEqual(Solution_better().twoSum(nums, target), [0, 1]) 29 | 30 | def test_answer_03(self): 31 | # If there is a repetition in nums , will FAILED 32 | nums = [2, 3, 3, 11] 33 | target = 6 34 | self.assertEqual(Solution_better().twoSum(nums, target), [1, 2]) 35 | 36 | def test_answer_04(self): 37 | nums = [2, 3, 4] 38 | target = 6 39 | self.assertEqual(Solution_better().twoSum(nums, target), [0, 2]) 40 | 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /test_Isomorphic_Strings_205.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Isomorphic_Strings_205 import Solution 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: s = "egg", t = "add" 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: s = "foo", t = "bar" 13 | Output: false 14 | 15 | Example 3: 16 | 17 | Input: s = "paper", t = "title" 18 | Output: true 19 | 20 | ''' 21 | 22 | class Test_Case(unittest.TestCase): 23 | 24 | def test_answer_01(self): 25 | s = "egg" 26 | t = "add" 27 | result = True 28 | self.assertEqual(Solution().isIsomorphic(s, t), result) 29 | 30 | def test_answer_02(self): 31 | s = "foo" 32 | t = "bar" 33 | result = False 34 | self.assertEqual(Solution().isIsomorphic(s, t), result) 35 | 36 | def test_answer_03(self): 37 | s = "paper" 38 | t = "title" 39 | result = True 40 | self.assertEqual(Solution().isIsomorphic(s, t), result) 41 | 42 | def test_answer_04(self): 43 | s = "" 44 | t = "" 45 | result = True 46 | self.assertEqual(Solution().isIsomorphic(s, t), result) 47 | 48 | def test_answer_05(self): 49 | s = "ads" 50 | t = "bce" 51 | result = True 52 | self.assertEqual(Solution().isIsomorphic(s, t), result) 53 | 54 | if __name__ == '__main__': 55 | unittest.main() 56 | 57 | -------------------------------------------------------------------------------- /test_Sqrtx_069.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Sqrtx_069 import Solution 3 | 4 | ''' 5 | Given a non-negative integer x, compute and return the square root of x. 6 | 7 | Since the return type is an integer, the decimal digits are truncated, 8 | 9 | and only the integer part of the result is returned 10 | 11 | Example 1: 12 | 13 | Input: 4 14 | Output: 2 15 | Example 2: 16 | 17 | Input: 8 18 | Output: 2 19 | Explanation: The square root of 8 is 2.82842..., and since 20 | the decimal part is truncated, 2 is returned. 21 | ''' 22 | 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | x = 4 28 | result = 2 29 | self.assertEqual(Solution().mySqrt(x), result) 30 | 31 | def test_answer_02(self): 32 | x = 8 33 | result = 2 34 | self.assertEqual(Solution().mySqrt(x), result) 35 | 36 | def test_answer_03(self): 37 | x = 0 38 | result = 0 39 | self.assertEqual(Solution().mySqrt(x), result) 40 | 41 | def test_answer_04(self): 42 | x = 100 43 | result = 10 44 | self.assertEqual(Solution().mySqrt(x), result) 45 | 46 | def test_answer_05(self): 47 | x = 1 48 | result = 1 49 | self.assertEqual(Solution().mySqrt(x), result) 50 | 51 | if __name__ == '__main__': 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /test_Reverse_Integer_007.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Reverse_Integer_007 import * 3 | 4 | ''' 5 | Example 1: 6 | Input: 123 7 | Output: 321 8 | 9 | Example 2: 10 | Input: -123 11 | Output: -321 12 | 13 | Example 3: 14 | Input: 120 15 | Output: 21 16 | 17 | Note: 18 | Assume we are dealing with an environment which could only store integers within the 19 | 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, 20 | assume that your function returns 0 when the reversed integer overflows. 21 | ''' 22 | 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | x = 1534236469 28 | result = 0 29 | self.assertEqual(Solution().reverse(x), result) 30 | 31 | def test_answer_02(self): 32 | x = 123 33 | result = 321 34 | self.assertEqual(Solution().reverse(x), result) 35 | 36 | def test_answer_03(self): 37 | x = -123 38 | result = -321 39 | self.assertEqual(Solution().reverse(x), result) 40 | 41 | def test_answer_04(self): 42 | x = 120 43 | result = 21 44 | self.assertEqual(Solution().reverse(x), result) 45 | 46 | def test_answer_04(self): 47 | x = 0 48 | result = 0 49 | self.assertEqual(Solution().reverse(x), result) 50 | 51 | 52 | if __name__ == '__main__': 53 | unittest.main() 54 | -------------------------------------------------------------------------------- /test_Excel_Sheet_Column_Title_168.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Excel_Sheet_Column_Title_168 import Solution 3 | 4 | """ 5 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 6 | 7 | For example: 8 | 9 | 1 -> A 10 | 2 -> B 11 | 3 -> C 12 | ... 13 | 26 -> Z 14 | 27 -> AA 15 | 28 -> AB 16 | 17 | 18 | Example 1: 19 | 20 | Input: columnNumber = 1 21 | Output: "A" 22 | 23 | Example 2: 24 | 25 | Input: columnNumber = 28 26 | Output: "AB" 27 | 28 | Example 3: 29 | 30 | Input: columnNumber = 701 31 | Output: "ZY" 32 | 33 | """ 34 | 35 | 36 | class Test_Case(unittest.TestCase): 37 | def test_answer_01(self): 38 | columnNumber = 1 39 | result = "A" 40 | self.assertEqual(Solution().convertToTitle(columnNumber), result) 41 | 42 | def test_answer_02(self): 43 | columnNumber = 28 44 | result = "AB" 45 | self.assertEqual(Solution().convertToTitle(columnNumber), result) 46 | 47 | def test_answer_03(self): 48 | columnNumber = 701 49 | result = "ZY" 50 | self.assertEqual(Solution().convertToTitle(columnNumber), result) 51 | 52 | def test_answer_04(self): 53 | columnNumber = 1457 54 | result = "BDA" 55 | self.assertEqual(Solution().convertToTitle(columnNumber), result) 56 | 57 | if __name__ == "__main__": 58 | unittest.main() 59 | -------------------------------------------------------------------------------- /test_Remove_Element_027.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Remove_Element_027 import * 3 | 4 | ''' 5 | Given an array nums and a value val, remove all instances of that value in-place and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | 11 | Example 1: 12 | Given nums = [3,2,2,3], val = 3, 13 | Your function should return length = 2, with the first two elements of nums being 2. 14 | 15 | 16 | Example 2: 17 | Given nums = [0,1,2,2,3,0,4,2], val = 2, 18 | Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. 19 | ''' 20 | 21 | 22 | class Test_Case(unittest.TestCase): 23 | 24 | def test_answer_01(self): 25 | nums = [3, 2, 2, 3] 26 | val = 3 27 | result = 2 28 | self.assertEqual(Solution().removeElement(nums, val), result) 29 | 30 | def test_answer_02(self): 31 | nums = [0, 1, 2, 2, 3, 0, 4, 2] 32 | val = 2 33 | result = 5 34 | self.assertEqual(Solution().removeElement(nums, val), result) 35 | 36 | def test_answer_03(self): 37 | nums = [3, 3, 3] 38 | val = 3 39 | result = 0 40 | self.assertEqual(Solution().removeElement(nums, val), result) 41 | -------------------------------------------------------------------------------- /test_Excel_Sheet_Column_Number_171.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Excel_Sheet_Column_Number_171 import Solution 3 | 4 | """ 5 | Related to question Excel Sheet Column Title 6 | 7 | Given a column title as appear in an Excel sheet, return its corresponding column number. 8 | 9 | For example: 10 | 11 | A -> 1 12 | B -> 2 13 | C -> 3 14 | ... 15 | Z -> 26 16 | AA -> 27 17 | AB -> 28 18 | 19 | Example 1: 20 | 21 | Input: columnTitle = "A" 22 | Output: 1 23 | 24 | Example 2: 25 | 26 | Input: columnTitle = "AB" 27 | Output: 28 28 | 29 | Example 3: 30 | 31 | Input: columnTitle = "ZY" 32 | Output: 701 33 | 34 | """ 35 | 36 | 37 | class Test_Case(unittest.TestCase): 38 | def test_answer_01(self): 39 | columnTitle = "A" 40 | result = 1 41 | self.assertEqual(Solution().titleToNumber(columnTitle), result) 42 | 43 | def test_answer_02(self): 44 | columnTitle = "AB" 45 | result = 28 46 | self.assertEqual(Solution().titleToNumber(columnTitle), result) 47 | 48 | def test_answer_03(self): 49 | columnTitle = "ZY" 50 | result = 701 51 | self.assertEqual(Solution().titleToNumber(columnTitle), result) 52 | 53 | def test_answer_04(self): 54 | columnTitle = "BDA" 55 | result = 1457 56 | self.assertEqual(Solution().titleToNumber(columnTitle), result) 57 | 58 | if __name__ == "__main__": 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /Remove_Duplicates_from_Sorted_Array_026.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 | Given nums = [1,1,2], 8 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 9 | It doesn't matter what you leave beyond the returned length. 10 | 11 | Example 2: 12 | Given nums = [0,0,1,1,1,2,2,3,3,4], 13 | Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. 14 | It doesn't matter what values are set beyond the returned length. 15 | ''' 16 | 17 | class Solution2: 18 | def removeDuplicates(self, nums: List[int]) -> int: 19 | nums[:] = set(nums) 20 | 21 | # nums = set(nums) # it doesn't accept 22 | # Without "[:]", you're creating a new list object 23 | # https://stackoverflow.com/a/10623352/4440387 24 | 25 | return len(nums) 26 | 27 | class Solution: 28 | def removeDuplicates(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: int 32 | """ 33 | for i in range(len(nums) - 1, 0, -1): 34 | if nums[i] == nums[i - 1]: 35 | del nums[i] 36 | return len(nums) 37 | -------------------------------------------------------------------------------- /test_Nim_Game_292.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Nim_Game_292 import Solution 3 | 4 | """ 5 | 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. 6 | 7 | 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. 8 | 9 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 10 | 11 | Example 1: 12 | 13 | Input: n = 4 14 | Output: false 15 | 16 | Example 2: 17 | 18 | Input: n = 1 19 | Output: true 20 | 21 | Example 3: 22 | 23 | Input: n = 2 24 | Output: true 25 | """ 26 | 27 | 28 | class Test_Case(unittest.TestCase): 29 | def test_answer_01(self): 30 | n = 4 31 | result = False 32 | self.assertEqual(Solution().canWinNim(n), result) 33 | 34 | def test_answer_02(self): 35 | n = 1 36 | result = True 37 | self.assertEqual(Solution().canWinNim(n), result) 38 | 39 | def test_answer_03(self): 40 | n = 2 41 | result = True 42 | self.assertEqual(Solution().canWinNim(n), result) 43 | 44 | 45 | if __name__ == "__main__": 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /test_Palindrome_Number_009.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Palindrome_Number_009 import * 3 | 4 | ''' 5 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 6 | 7 | Example 1: 8 | Input: 121 9 | Output: true 10 | 11 | Example 2: 12 | Input: -121 13 | Output: false 14 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 15 | 16 | Example 3: 17 | Input: 10 18 | Output: false 19 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 20 | ''' 21 | 22 | 23 | class Test_Case(unittest.TestCase): 24 | 25 | def test_answer_01(self): 26 | x = 121 27 | result = True 28 | self.assertEqual(Solution().isPalindrome(x), result) 29 | 30 | def test_answer_02(self): 31 | x = -121 32 | result = False 33 | self.assertEqual(Solution().isPalindrome(x), result) 34 | 35 | def test_answer_03(self): 36 | x = -123 37 | result = False 38 | self.assertEqual(Solution().isPalindrome(x), result) 39 | 40 | def test_answer_04(self): 41 | x = 10 42 | result = False 43 | self.assertEqual(Solution().isPalindrome(x), result) 44 | 45 | def test_answer_05(self): 46 | x = -101 47 | result = False 48 | self.assertEqual(Solution().isPalindrome(x), result) 49 | 50 | if __name__ == '__main__': 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | migrations/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # IPython Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # dotenv 80 | .env 81 | 82 | # virtualenv 83 | venv/ 84 | ENV/ 85 | 86 | # Spyder project settings 87 | .spyderproject 88 | 89 | # Rope project settings 90 | .ropeproject 91 | .idea/ -------------------------------------------------------------------------------- /test_Ugly_Number_263.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Ugly_Number_263 import Solution 3 | 4 | """ 5 | Write a program to check whether a given number is an ugly number. 6 | 7 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 8 | 9 | Note that 1 is typically treated as an ugly number. 10 | 11 | 12 | Example 1: 13 | 14 | Input: n = 6 15 | Output: true 16 | Explanation: 6 = 2 × 3 17 | 18 | Example 2: 19 | 20 | Input: n = 1 21 | Output: true 22 | Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 23 | 24 | Example 3: 25 | 26 | Input: n = 14 27 | Output: false 28 | Explanation: 14 is not ugly since it includes the prime factor 7. 29 | """ 30 | 31 | 32 | class Test_Case(unittest.TestCase): 33 | def test_answer_01(self): 34 | n = 6 35 | result = True 36 | self.assertEqual(Solution().isUgly(n), result) 37 | 38 | def test_answer_02(self): 39 | n = 1 40 | result = True 41 | self.assertEqual(Solution().isUgly(n), result) 42 | 43 | def test_answer_03(self): 44 | n = 14 45 | result = False 46 | self.assertEqual(Solution().isUgly(n), result) 47 | 48 | def test_answer_03(self): 49 | n = 0 50 | result = False 51 | self.assertEqual(Solution().isUgly(n), result) 52 | 53 | if __name__ == "__main__": 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /Valid_Anagram_242.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: s = "anagram", t = "nagaram" 5 | Output: true 6 | 7 | Example 2: 8 | 9 | Input: s = "rat", t = "car" 10 | Output: false 11 | 12 | ''' 13 | 14 | class Solution(object): 15 | def isAnagram(self, s, t): 16 | """ 17 | :type s: str 18 | :type t: str 19 | :rtype: bool 20 | """ 21 | if len(s) != len(t): 22 | return False 23 | count = [0] * 123 24 | 25 | for ch in s: 26 | count[ord(ch)] += 1 27 | for ch in t: 28 | if count[ord(ch)] == 0: 29 | return False 30 | # count[ord(ch)] -= 1 31 | return True 32 | 33 | 34 | class Solution_worse(object): 35 | def isAnagram(self, s, t): 36 | """ 37 | :type s: str 38 | :type t: str 39 | :rtype: bool 40 | """ 41 | if len(s) != len(t): 42 | return False 43 | 44 | return sorted(s) == sorted(t) 45 | 46 | 47 | class Solution_Brute_Force(object): 48 | def isAnagram(self, s, t): 49 | """ 50 | :type s: str 51 | :type t: str 52 | :rtype: bool 53 | """ 54 | if len(s) != len(t): 55 | return False 56 | 57 | s = [i for i in s] 58 | t = [i for i in t] 59 | for data in s: 60 | try: 61 | t.remove(data) 62 | except : 63 | return False 64 | 65 | return True -------------------------------------------------------------------------------- /LRU_Cache_146.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU 3 | 4 | Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. 5 | 6 | Implement the LRUCache class: 7 | 8 | LRUCache(int capacity) Initialize the LRU cache with positive size capacity. 9 | int get(int key) Return the value of the key if the key exists, otherwise return -1. 10 | void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. 11 | 12 | ''' 13 | 14 | import collections 15 | 16 | class LRUCache(collections.OrderedDict): 17 | 18 | def __init__(self, capacity: int): 19 | super().__init__() 20 | self.capacity = capacity 21 | 22 | 23 | def get(self, key: int) -> int: 24 | # 假如key存在, 移動到最後(當作是使用過)並回傳, 如果不存在回傳 -1 25 | if key in self: 26 | self.move_to_end(key) 27 | return self[key] 28 | return -1 29 | 30 | 31 | def put(self, key: int, value: int) -> None: 32 | # 如果 key 存在, 改變 value(並且移到最後), 33 | # 不存在則加入 34 | if key in self: 35 | self.move_to_end(key) 36 | self[key] = value 37 | if len(self) > self.capacity: 38 | self.popitem(last=False) 39 | 40 | c = LRUCache(2) 41 | c.put(1,1) 42 | c.put(2,2) 43 | c.get(1) 44 | c.put(3,3) 45 | print(c) 46 | c.put(4,4) 47 | print(c) -------------------------------------------------------------------------------- /Longest_Common_Prefix_014.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 | Example 1: 7 | Input: ["flower","flow","flight"] 8 | Output: "fl" 9 | 10 | Example 2: 11 | Input: ["dog","racecar","car"] 12 | Output: "" 13 | Explanation: There is no common prefix among the input strings. 14 | 15 | Note: 16 | 17 | All given inputs are in lowercase letters a-z. 18 | ''' 19 | 20 | class Solution: 21 | def longestCommonPrefix(self, strs): 22 | """ 23 | :type strs: List[str] 24 | :rtype: str 25 | """ 26 | if not strs: 27 | return '' 28 | 29 | m_str = min(strs, key=len) 30 | 31 | for i, v in enumerate(m_str): 32 | for s in strs: 33 | if s == m_str: 34 | continue 35 | if s[i] != v: 36 | return m_str[:i] 37 | return m_str 38 | 39 | class Solution_better: 40 | def longestCommonPrefix(self, strs): 41 | """ 42 | :type strs: List[str] 43 | :rtype: str 44 | """ 45 | if not strs: 46 | return '' 47 | 48 | # retrieved min(strs) max(strs) by alphabetical order 49 | 50 | s1 = min(strs) 51 | s2 = max(strs) 52 | 53 | for index, value in enumerate(s1): 54 | if value != s2[index]: 55 | return s2[:index] 56 | return s1 57 | 58 | -------------------------------------------------------------------------------- /test_Longest_Increasing_Subsequence_300.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Longest_Increasing_Subsequence_300 import ( 3 | Solution_DP, 4 | Solution_BinarySearch, 5 | Solution_bisect, 6 | ) 7 | 8 | """ 9 | Input: nums = [10,9,2,5,3,7,101,18] 10 | [2,3,7,101] 11 | Output: 4 12 | 13 | Input: nums = [0,1,0,3,2,3] 14 | Output: 4 15 | 16 | Input: nums = [7,7,7,7,7,7,7] 17 | Output: 1 18 | """ 19 | 20 | 21 | class Test_Case(unittest.TestCase): 22 | def test_answer_01(self): 23 | nums = [10, 9, 2, 5, 3, 7, 101, 18] 24 | result = 4 25 | 26 | self.assertEqual(Solution_bisect().lengthOfLIS(nums), result) 27 | # self.assertEqual(Solution_BinarySearch().lengthOfLIS(nums), result) 28 | # self.assertEqual(Solution_DP().lengthOfLIS(nums), result) 29 | 30 | def test_answer_02(self): 31 | nums = [0, 1, 0, 3, 2, 3] 32 | result = 4 33 | self.assertEqual(Solution_bisect().lengthOfLIS(nums), result) 34 | # self.assertEqual(Solution_BinarySearch().lengthOfLIS(nums), result) 35 | # self.assertEqual(Solution_DP().lengthOfLIS(nums), result) 36 | 37 | def test_answer_03(self): 38 | nums = [7, 7, 7, 7, 7, 7, 7] 39 | result = 1 40 | self.assertEqual(Solution_bisect().lengthOfLIS(nums), result) 41 | # self.assertEqual(Solution_BinarySearch().lengthOfLIS(nums), result) 42 | # self.assertEqual(Solution_DP().lengthOfLIS(nums), result) 43 | 44 | 45 | if __name__ == "__main__": 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /test_Factorial_Trailing_Zeroes_172.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Factorial_Trailing_Zeroes_172 import * 3 | 4 | ''' 5 | Given an integer n, return the number of trailing zeroes in n!. 6 | 7 | Note: Your solution should be in logarithmic time complexity. 8 | 9 | Example 1: 10 | 11 | Input: n = 3 12 | Output: 0 13 | Explanation: 3! = 6, no trailing zero. 14 | 15 | Example 2: 16 | 17 | Input: n = 5 18 | Output: 1 19 | Explanation: 5! = 120, one trailing zero. 20 | 21 | Example 3: 22 | 23 | Input: n = 0 24 | Output: 0 25 | ''' 26 | 27 | class Test_Case(unittest.TestCase): 28 | 29 | def test_answer_01(self): 30 | n = 3 31 | result = 0 32 | self.assertEqual(Solution().trailingZeroes(n), result) 33 | 34 | def test_answer_02(self): 35 | n = 5 36 | result = 1 37 | self.assertEqual(Solution().trailingZeroes(n), result) 38 | 39 | def test_answer_03(self): 40 | n = 0 41 | result = 0 42 | self.assertEqual(Solution().trailingZeroes(n), result) 43 | 44 | def test_answer_04(self): 45 | n = 10 46 | result = 2 47 | self.assertEqual(Solution().trailingZeroes(n), result) 48 | 49 | def test_answer_05(self): 50 | n = 25 51 | result = 6 52 | self.assertEqual(Solution().trailingZeroes(n), result) 53 | 54 | def test_answer_05(self): 55 | n = 125 56 | result = 31 57 | self.assertEqual(Solution().trailingZeroes(n), result) 58 | 59 | if __name__ == '__main__': 60 | unittest.main() 61 | -------------------------------------------------------------------------------- /Roman_to_Integer_013.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Symbol Value 3 | I 1 4 | V 5 5 | X 10 6 | L 50 7 | C 100 8 | D 500 9 | M 1000 10 | 11 | I can be placed before V (5) and X (10) to make 4 and 9. 12 | X can be placed before L (50) and C (100) to make 40 and 90. 13 | C can be placed before D (500) and M (1000) to make 400 and 900. 14 | 15 | Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 16 | 17 | Example 1: 18 | Input: "III" 19 | Output: 3 20 | 21 | Example 2: 22 | Input: "IV" 23 | Output: 4 24 | 25 | Example 3: 26 | Input: "IX" 27 | Output: 9 28 | 29 | Example 4: 30 | Input: "LVIII" 31 | Output: 58 32 | Explanation: L = 50, V= 5, III = 3. 33 | 34 | Example 5: 35 | Input: "MCMXCIV" 36 | Output: 1994 37 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 38 | ''' 39 | 40 | class Solution: 41 | def romanToInt(self, s): 42 | """ 43 | :type s: str 44 | :rtype: int 45 | """ 46 | mapping = { 47 | 'I': 1, 48 | 'V': 5, 49 | 'X': 10, 50 | 'L': 50, 51 | 'C': 100, 52 | 'D': 500, 53 | 'M': 1000 54 | } 55 | 56 | sum = 0 57 | for index in range(len(s)-1): 58 | if mapping[s[index]] >= mapping[s[index+1]]: 59 | sum += mapping[s[index]] 60 | else: 61 | sum -= mapping[s[index]] 62 | return sum + mapping[s[-1]] 63 | -------------------------------------------------------------------------------- /test_Permutations_046.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Permutations_046 import Solution 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: nums = [1,2,3] 8 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 9 | 10 | Example 2: 11 | 12 | Input: nums = [0,1] 13 | Output: [[0,1],[1,0]] 14 | 15 | Example 3: 16 | 17 | Input: nums = [1] 18 | Output: [[1]] 19 | ''' 20 | 21 | class Test_Case(unittest.TestCase): 22 | 23 | def test_answer_01(self): 24 | nums = [1,2,3] 25 | result_temp = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 26 | ans = Solution().permute(nums) 27 | ans = map(list, ans) 28 | result = True 29 | for data in ans: 30 | if data not in result_temp: 31 | result = False 32 | self.assertTrue(result) 33 | 34 | def test_answer_02(self): 35 | nums = [0,1] 36 | result_temp = [[0,1],[1,0]] 37 | ans = Solution().permute(nums) 38 | ans = map(list, ans) 39 | result = True 40 | for data in ans: 41 | if data not in result_temp: 42 | result = False 43 | self.assertTrue(result) 44 | 45 | def test_answer_03(self): 46 | nums = [1] 47 | result_temp = [[1]] 48 | ans = Solution().permute(nums) 49 | ans = map(list, ans) 50 | result = True 51 | for data in ans: 52 | if data not in result_temp: 53 | result = False 54 | self.assertTrue(result) 55 | 56 | if __name__ == '__main__': 57 | unittest.main() 58 | -------------------------------------------------------------------------------- /Bulls_and_Cows_299.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: 3 | 4 | Input: secret = "1807", guess = "7810" 5 | Output: "1A3B" 6 | Explanation: Bulls are connected with a '|' and cows are underlined: 7 | "1807" 8 | | 9 | "7810" 10 | 11 | Example 2: 12 | 13 | Input: secret = "1123", guess = "0111" 14 | Output: "1A1B" 15 | Explanation: Bulls are connected with a '|' and cows are underlined: 16 | "1123" "1123" 17 | | or | 18 | "0111" "0111" 19 | Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. 20 | 21 | Example 3: 22 | 23 | Input: secret = "1", guess = "0" 24 | Output: "0A0B" 25 | 26 | Example 4: 27 | 28 | Input: secret = "1", guess = "1" 29 | Output: "1A0B" 30 | 31 | ''' 32 | class Solution(object): 33 | def getHint(self, secret, guess): 34 | """ 35 | :type secret: str 36 | :type guess: str 37 | :rtype: str 38 | """ 39 | 40 | result_A = 0 41 | result_B = 0 42 | A = [] 43 | B = [] 44 | 45 | for i in range(len(secret)): 46 | if secret[i] == guess[i]: 47 | result_A += 1 48 | else: 49 | A.append(secret[i]) 50 | B.append(guess[i]) 51 | 52 | if result_A == 0 : 53 | A = [i for i in secret] 54 | B = [i for i in guess] 55 | 56 | for i in range(len(A)): 57 | if A[i] in B: 58 | result_B += 1 59 | B.remove(A[i]) 60 | 61 | return '{}A{}B'.format(result_A, result_B) 62 | 63 | 64 | -------------------------------------------------------------------------------- /test_Word_Pattern_290.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Word_Pattern_290 import Solution 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: pattern = "abba", s = "dog cat cat dog" 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: pattern = "abba", s = "dog cat cat fish" 13 | Output: false 14 | 15 | Example 3: 16 | 17 | Input: pattern = "aaaa", s = "dog cat cat dog" 18 | Output: false 19 | 20 | Example 4: 21 | 22 | Input: pattern = "abba", s = "dog dog dog dog" 23 | Output: false 24 | ''' 25 | 26 | class Test_Case(unittest.TestCase): 27 | 28 | def test_answer_01(self): 29 | pattern = "abba" 30 | s = "dog cat cat dog" 31 | result = True 32 | self.assertEqual(Solution().wordPattern(pattern, s), result) 33 | 34 | def test_answer_02(self): 35 | pattern = "abba" 36 | s = "dog cat cat fish" 37 | result = False 38 | self.assertEqual(Solution().wordPattern(pattern, s), result) 39 | 40 | def test_answer_03(self): 41 | pattern = "aaaa" 42 | s = "dog cat cat dog" 43 | result = False 44 | self.assertEqual(Solution().wordPattern(pattern, s), result) 45 | 46 | def test_answer_04(self): 47 | pattern = "abba" 48 | s = "dog dog dog dog" 49 | result = False 50 | self.assertEqual(Solution().wordPattern(pattern, s), result) 51 | 52 | def test_answer_05(self): 53 | pattern = "abc" 54 | s = "b c a" 55 | result = True 56 | self.assertEqual(Solution().wordPattern(pattern, s), result) 57 | 58 | if __name__ == '__main__': 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /test_Plus_One_066.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Plus_One_066 import * 3 | 4 | ''' 5 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 6 | 7 | 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. 8 | 9 | You may assume the integer does not contain any leading zero, except the number 0 itself. 10 | 11 | Example 1: 12 | 13 | Input: [1,2,3] 14 | Output: [1,2,4] 15 | Explanation: The array represents the integer 123. 16 | Example 2: 17 | 18 | Input: [4,3,2,1] 19 | Output: [4,3,2,2] 20 | Explanation: The array represents the integer 4321. 21 | ''' 22 | 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | digits = [1, 2, 3] 28 | result = [1, 2, 4] 29 | self.assertEqual(Solution().plusOne(digits), result) 30 | 31 | def test_answer_02(self): 32 | digits = [4, 3, 2, 1] 33 | result = [4, 3, 2, 2] 34 | self.assertEqual(Solution().plusOne(digits), result) 35 | 36 | def test_answer_03(self): 37 | digits = [9] 38 | result = [1, 0] 39 | self.assertEqual(Solution().plusOne(digits), result) 40 | 41 | def test_answer_04(self): 42 | digits = [9, 9] 43 | result = [1, 0, 0] 44 | self.assertEqual(Solution().plusOne(digits), result) 45 | 46 | def test_answer_05(self): 47 | digits = [0, 0] 48 | result = [0, 1] 49 | self.assertEqual(Solution().plusOne(digits), result) 50 | 51 | if __name__ == '__main__': 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /Merge_Two_Sorted_Lists_021.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Merge two sorted linked lists and return it as a new list. 3 | The new list should be made by splicing together the nodes of the first two lists. 4 | 5 | Example: 6 | 7 | Input: 1->2->4, 1->3->4 8 | Output: 1->1->2->3->4->4 9 | ''' 10 | 11 | 12 | # Definition for singly-linked list. 13 | class ListNode: 14 | def __init__(self, val): 15 | self.val = val 16 | self.next = None 17 | 18 | 19 | class Solution(object): 20 | def mergeTwoLists(self, l1, l2): 21 | """ 22 | :type l1: ListNode 23 | :type l2: ListNode 24 | :rtype: ListNode 25 | """ 26 | if not l1 or not l2: 27 | return l1 or l2 28 | head = cur = ListNode(0) 29 | while l1 and l2: 30 | if l1.val < l2.val: 31 | cur.next = l1 32 | l1 = l1.next 33 | else: 34 | cur.next = l2 35 | l2 = l2.next 36 | cur = cur.next 37 | cur.next = l1 or l2 38 | return head.next 39 | 40 | 41 | class Solution_Recursive(object): 42 | def mergeTwoLists(self, l1, l2): 43 | """ 44 | :type l1: ListNode 45 | :type l2: ListNode 46 | :rtype: ListNode 47 | """ 48 | if not l1 or not l2: 49 | return l1 or l2 50 | 51 | if l1.val < l2.val: 52 | print('l1.val:', l1.val) 53 | l1.next = self.mergeTwoLists(l1.next, l2) 54 | return l1 55 | else: 56 | print('l2.val:', l2.val) 57 | l2.next = self.mergeTwoLists(l1, l2.next) 58 | return l2 59 | -------------------------------------------------------------------------------- /test_Merge_Intervals_056.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Merge_Intervals_056 import Solution 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 8 | Output: [[1,6],[8,10],[15,18]] 9 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 10 | 11 | Example 2: 12 | 13 | Input: intervals = [[1,4],[4,5]] 14 | Output: [[1,5]] 15 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 16 | ''' 17 | 18 | 19 | class Test_Case(unittest.TestCase): 20 | 21 | def test_answer_01(self): 22 | 23 | intervals = [[1,3],[2,6],[8,10],[15,18]] 24 | result = [[1,6],[8,10],[15,18]] 25 | self.assertEqual(Solution().merge(intervals), result) 26 | 27 | def test_answer_02(self): 28 | 29 | intervals = [[1,4],[4,5]] 30 | result = [[1,5]] 31 | self.assertEqual(Solution().merge(intervals), result) 32 | 33 | def test_answer_03(self): 34 | 35 | intervals = [[1,3]] 36 | result = [[1,3]] 37 | self.assertEqual(Solution().merge(intervals), result) 38 | 39 | def test_answer_04(self): 40 | intervals = [[1,4],[5,6]] 41 | result = [[1,4],[5,6]] 42 | self.assertEqual(Solution().merge(intervals), result) 43 | 44 | def test_answer_05(self): 45 | intervals = [[1,4],[0,4]] 46 | result = [[0,4]] 47 | self.assertEqual(Solution().merge(intervals), result) 48 | 49 | def test_answer_06(self): 50 | intervals = [[1,4],[2,3]] 51 | result = [[1,4]] 52 | self.assertEqual(Solution().merge(intervals), result) 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /P3Sum_015.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers, are there elements 3 | a, b, c in nums such that a + b + c = 0? 4 | Find all unique triplets in the array which gives the sum of zero. 5 | 6 | Notice that the solution set must not contain duplicate triplets. 7 | 8 | Example 1: 9 | Input: nums = [-1,0,1,2,-1,-4] 10 | Output: [[-1,-1,2],[-1,0,1]] 11 | 12 | Example 2: 13 | Input: nums = [] 14 | Output: [] 15 | 16 | Example 3: 17 | Input: nums = [0] 18 | Output: [] 19 | ''' 20 | 21 | import itertools 22 | 23 | 24 | class Solution_Time_Limit_Exceeded(object): 25 | def threeSum(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: List[List[int]] 29 | """ 30 | data = set(filter(lambda x: sum(x) == 0, itertools.combinations(sorted(nums), 3))) 31 | 32 | return [list(d) for d in data] 33 | 34 | class Solution(object): 35 | def threeSum(self, nums): 36 | """ 37 | :type nums: List[int] 38 | :rtype: List[List[int]] 39 | """ 40 | # https://ithelp.ithome.com.tw/articles/10213264 41 | 42 | if len(nums) < 3: 43 | return [] 44 | nums.sort() 45 | res = set() 46 | for i, v in enumerate(nums[:-2]): 47 | # Skip repeated 48 | if i >= 1 and v == nums[i-1]: 49 | continue 50 | d = {} 51 | for x in nums[i+1:]: 52 | # Skip repeated 53 | # if i >= 1 and v == nums[i-1]: 54 | # continue 55 | if x not in d: 56 | d[-v-x] = 1 # 1 -> any number 57 | else: 58 | res.add((v, -v-x, x)) 59 | return list(res) -------------------------------------------------------------------------------- /test_Search_Insert_Position_035.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Search_Insert_Position_035 import * 3 | 4 | ''' 5 | 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. 6 | 7 | You may assume no duplicates in the array. 8 | 9 | Example 1: 10 | Input: [1,3,5,6], 5 11 | Output: 2 12 | 13 | Example 2: 14 | Input: [1,3,5,6], 2 15 | Output: 1 16 | 17 | Example 3: 18 | Input: [1,3,5,6], 7 19 | Output: 4 20 | 21 | Example 4: 22 | Input: [1,3,5,6], 0 23 | Output: 0 24 | 25 | Example 5: 26 | Input: nums = [1], target = 0 27 | Output: 0 28 | ''' 29 | 30 | 31 | class Test_Case(unittest.TestCase): 32 | 33 | def test_answer_01(self): 34 | nums = [1, 3, 5, 6] 35 | target = 5 36 | result = 2 37 | self.assertEqual(Solution().searchInsert(nums, target), result) 38 | 39 | def test_answer_02(self): 40 | nums = [1, 3, 5, 6] 41 | target = 2 42 | result = 1 43 | self.assertEqual(Solution().searchInsert(nums, target), result) 44 | 45 | def test_answer_03(self): 46 | nums = [1, 3, 5, 6] 47 | target = 7 48 | result = 4 49 | self.assertEqual(Solution().searchInsert(nums, target), result) 50 | 51 | def test_answer_04(self): 52 | nums = [1, 3, 5, 6] 53 | target = 0 54 | result = 0 55 | self.assertEqual(Solution().searchInsert(nums, target), result) 56 | 57 | def test_answer_05(self): 58 | nums = [1] 59 | target = 0 60 | result = 0 61 | self.assertEqual(Solution().searchInsert(nums, target), result) 62 | 63 | if __name__ == '__main__': 64 | unittest.main() 65 | -------------------------------------------------------------------------------- /test_Maximum_Subarray_053.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Maximum_Subarray_053 import * 3 | 4 | ''' 5 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 6 | 7 | Example 1: 8 | 9 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 10 | Output: 6 11 | Explanation: [4,-1,2,1] has the largest sum = 6. 12 | 13 | Example 2: 14 | 15 | Input: nums = [1] 16 | Output: 1 17 | 18 | Example 3: 19 | 20 | Input: nums = [0] 21 | Output: 0 22 | 23 | Example 4: 24 | 25 | Input: nums = [-1] 26 | Output: -1 27 | 28 | Example 5: 29 | 30 | Input: nums = [-2147483647] 31 | Output: -2147483647 32 | 33 | ''' 34 | 35 | 36 | class Test_Case(unittest.TestCase): 37 | 38 | def test_answer_01(self): 39 | nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] 40 | result = 6 41 | self.assertEqual(Solution().maxSubArray(nums), result) 42 | 43 | def test_answer_02(self): 44 | nums = [] 45 | result = 0 46 | self.assertEqual(Solution().maxSubArray(nums), result) 47 | 48 | def test_answer_03(self): 49 | nums = [1] 50 | result = 1 51 | self.assertEqual(Solution().maxSubArray(nums), result) 52 | 53 | def test_answer_04(self): 54 | nums = [0] 55 | result = 0 56 | self.assertEqual(Solution().maxSubArray(nums), result) 57 | 58 | def test_answer_05(self): 59 | nums = [-1] 60 | result = -1 61 | self.assertEqual(Solution().maxSubArray(nums), result) 62 | 63 | def test_answer_06(self): 64 | nums = [-2147483647] 65 | result = -2147483647 66 | self.assertEqual(Solution().maxSubArray(nums), result) 67 | 68 | if __name__ == '__main__': 69 | unittest.main() 70 | -------------------------------------------------------------------------------- /test_Merge_Two_Sorted_Lists_021.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Merge_Two_Sorted_Lists_021 import ListNode, Solution 3 | 4 | ''' 5 | 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. 6 | 7 | Example: 8 | 9 | Input: 1->2->4, 1->3->4 10 | Output: 1->1->2->3->4->4 11 | ''' 12 | 13 | 14 | class Test_Case(unittest.TestCase): 15 | 16 | def test_answer_01(self): 17 | # L1 = 1 -> 2 -> 4 18 | l1 = ListNode(1) 19 | l1.next = ListNode(2) 20 | l1.next.next = ListNode(4) 21 | # L2 = 1 -> 3 -> 4 22 | l2 = ListNode(1) 23 | l2.next = ListNode(3) 24 | l2.next.next = ListNode(4) 25 | actual = Solution().mergeTwoLists(l1, l2) 26 | 27 | # expected result 1->1->2->3->4->4 28 | expected = ListNode(1) 29 | expected.next = ListNode(1) 30 | expected.next.next = ListNode(2) 31 | expected.next.next.next = ListNode(3) 32 | expected.next.next.next.next = ListNode(4) 33 | expected.next.next.next.next.next = ListNode(4) 34 | 35 | self.assertEqual(actual.val, expected.val) 36 | self.assertEqual(actual.next.val, expected.next.val) 37 | self.assertEqual(actual.next.next.val, expected.next.next.val) 38 | self.assertEqual(actual.next.next.next.val, expected.next.next.next.val) 39 | self.assertEqual(actual.next.next.next.next.val, expected.next.next.next.next.val) 40 | self.assertEqual(actual.next.next.next.next.next.val, expected.next.next.next.next.next.val) 41 | self.assertEqual(actual.next.next.next.next.next.next, expected.next.next.next.next.next.next) 42 | 43 | 44 | if __name__ == '__main__': 45 | unittest.main() 46 | -------------------------------------------------------------------------------- /Valid_Parentheses_020.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 | Input: "()" 12 | Output: true 13 | 14 | Example 2: 15 | Input: "()[]{}" 16 | Output: true 17 | 18 | Example 3: 19 | Input: "(]" 20 | Output: false 21 | 22 | Example 4: 23 | Input: "([)]" 24 | Output: false 25 | 26 | Example 5: 27 | Input: "{[]}" 28 | Output: true 29 | ''' 30 | 31 | class Solution: 32 | def isValid(self, s): 33 | """ 34 | :type s: str 35 | :rtype: bool 36 | """ 37 | while s.find("()") != -1 or s.find("[]") != -1 or s.find("{}") != -1: 38 | if s.find("()") != -1: 39 | s = s.replace("()", "") 40 | if s.find("[]") != -1: 41 | s = s.replace("[]", "") 42 | if s.find("{}") != -1: 43 | s = s.replace("{}", "") 44 | 45 | return len(s) == 0 46 | 47 | 48 | class Solution_better: 49 | def isValid(self, s): 50 | """ 51 | :type s: str 52 | :rtype: bool 53 | """ 54 | mapping = { 55 | '(': ')', 56 | '{': '}', 57 | '[': ']', 58 | } 59 | stack = [] 60 | for char in s: 61 | if char in mapping: 62 | stack.append(char) 63 | else: 64 | if not stack: 65 | return False 66 | if mapping[stack.pop()] != char: 67 | return False 68 | return False if stack else True 69 | -------------------------------------------------------------------------------- /test_Reverse_Words_in_a_String_151.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Reverse_Words_in_a_String_151 import * 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: s = "the sky is blue" 8 | Output: "blue is sky the" 9 | 10 | Example 2: 11 | 12 | Input: s = " hello world " 13 | Output: "world hello" 14 | Explanation: Your reversed string should not contain leading or trailing spaces. 15 | 16 | Example 3: 17 | 18 | Input: s = "a good example" 19 | Output: "example good a" 20 | Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 21 | 22 | Example 4: 23 | 24 | Input: s = " Bob Loves Alice " 25 | Output: "Alice Loves Bob" 26 | 27 | Example 5: 28 | 29 | Input: s = "Alice does not even like bob" 30 | Output: "bob like even not does Alice" 31 | ''' 32 | 33 | class Test_Case(unittest.TestCase): 34 | 35 | def test_answer_01(self): 36 | s = "the sky is blue" 37 | result = "blue is sky the" 38 | self.assertEqual(Solution().reverseWords(s), result) 39 | 40 | def test_answer_02(self): 41 | s = " hello world " 42 | result = "world hello" 43 | self.assertEqual(Solution().reverseWords(s), result) 44 | 45 | def test_answer_03(self): 46 | s = "a good example" 47 | result = "example good a" 48 | self.assertEqual(Solution().reverseWords(s), result) 49 | 50 | def test_answer_04(self): 51 | s = " Bob Loves Alice " 52 | result = "Alice Loves Bob" 53 | self.assertEqual(Solution().reverseWords(s), result) 54 | 55 | def test_answer_05(self): 56 | s = "Alice does not even like bob" 57 | result = "bob like even not does Alice" 58 | self.assertEqual(Solution().reverseWords(s), result) 59 | 60 | if __name__ == '__main__': 61 | unittest.main() 62 | -------------------------------------------------------------------------------- /Palindrome_Number_009.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 3 | 4 | Example 1: 5 | Input: 121 6 | Output: true 7 | 8 | Example 2: 9 | Input: -121 10 | Output: false 11 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 12 | 13 | Example 3: 14 | Input: 10 15 | Output: false 16 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 17 | ''' 18 | 19 | class Solution: 20 | def isPalindrome(self, x): 21 | """ 22 | :type x: int 23 | :rtype: bool 24 | """ 25 | x = str(x) 26 | if '-' in x: 27 | return False 28 | return x == x[::-1] 29 | 30 | class Solution2: 31 | def isPalindrome(self, x): 32 | """ 33 | :type x: int 34 | :rtype: bool 35 | """ 36 | 37 | if x < 0: 38 | return False 39 | else: 40 | reversed_int = int(str(x)[::-1]) 41 | if x == reversed_int: 42 | return True 43 | return False 44 | 45 | 46 | class Solution_better: 47 | def isPalindrome(self, x): 48 | """ 49 | :type x: int 50 | :rtype: bool 51 | """ 52 | return False if x < 0 else x == int(str(x)[::-1]) 53 | 54 | 55 | class Solution3: 56 | def isPalindrome(self, x): 57 | """ 58 | :type x: int 59 | :rtype: int 60 | """ 61 | # without converting the integer to a string 62 | 63 | if x < 0: 64 | return False 65 | result = 0 66 | original = x 67 | while x: 68 | result = result * 10 + x % 10 69 | x = int(x / 10) 70 | 71 | return result == original 72 | -------------------------------------------------------------------------------- /Merge_Sorted_Array_088.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Given two sorted integer arrays nums1 and nums2, 4 | merge nums2 into nums1 as one sorted array. 5 | 6 | Input: 7 | nums1 = [1,2,3,0,0,0], m = 3 8 | nums2 = [2,5,6], n = 3 9 | 10 | Output: [1,2,2,3,5,6] 11 | ''' 12 | 13 | class Solution(object): 14 | def merge(self, nums1, m, nums2, n): 15 | """ 16 | :type nums1: List[int] 17 | :type m: int 18 | :type nums2: List[int] 19 | :type n: int 20 | :rtype: None Do not return anything, modify nums1 in-place instead. 21 | """ 22 | nums1[m:] = nums2[:n] 23 | nums1.sort() 24 | return nums1 25 | 26 | class SolutionBubbleSort1(object): 27 | def merge(self, nums1, m, nums2, n): 28 | """ 29 | :type nums1: List[int] 30 | :type m: int 31 | :type nums2: List[int] 32 | :type n: int 33 | :rtype: None Do not return anything, modify nums1 in-place instead. 34 | """ 35 | 36 | nums1[m:] = nums2[:n] 37 | s_len = m + n 38 | 39 | while s_len > 1: 40 | s_len -= 1 41 | for i in range(s_len): 42 | if nums1[i] > nums1[i+1]: 43 | nums1[i], nums1[i+1] = nums1[i+1], nums1[i] 44 | return nums1 45 | 46 | class SolutionBubbleSort2(object): 47 | def merge(self, nums1, m, nums2, n): 48 | """ 49 | :type nums1: List[int] 50 | :type m: int 51 | :type nums2: List[int] 52 | :type n: int 53 | :rtype: None Do not return anything, modify nums1 in-place instead. 54 | """ 55 | 56 | nums1[m:] = nums2[:n] 57 | 58 | for j in range(m+n-1, 0, -1): 59 | for i in range(j): 60 | if nums1[i] > nums1[i+1]: 61 | nums1[i], nums1[i+1] = nums1[i+1], nums1[i] 62 | return nums1 -------------------------------------------------------------------------------- /test_Roman_to_Integer_013.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Roman_to_Integer_013 import * 3 | 4 | ''' 5 | Symbol Value 6 | I 1 7 | V 5 8 | X 10 9 | L 50 10 | C 100 11 | D 500 12 | M 1000 13 | 14 | I can be placed before V (5) and X (10) to make 4 and 9. 15 | X can be placed before L (50) and C (100) to make 40 and 90. 16 | C can be placed before D (500) and M (1000) to make 400 and 900. 17 | 18 | Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 19 | 20 | Example 1: 21 | Input: "III" 22 | Output: 3 23 | 24 | Example 2: 25 | Input: "IV" 26 | Output: 4 27 | 28 | Example 3: 29 | Input: "IX" 30 | Output: 9 31 | 32 | Example 4: 33 | Input: "LVIII" 34 | Output: 58 35 | Explanation: L = 50, V= 5, III = 3. 36 | 37 | Example 5: 38 | Input: "MCMXCIV" 39 | Output: 1994 40 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 41 | ''' 42 | 43 | 44 | class Test_Case(unittest.TestCase): 45 | 46 | def test_answer_01(self): 47 | roman = "III" 48 | result = 3 49 | self.assertEqual(Solution().romanToInt(roman), result) 50 | 51 | def test_answer_02(self): 52 | roman = "IV" 53 | result = 4 54 | self.assertEqual(Solution().romanToInt(roman), result) 55 | 56 | def test_answer_03(self): 57 | roman = "LVIII" 58 | result = 58 59 | self.assertEqual(Solution().romanToInt(roman), result) 60 | 61 | def test_answer_04(self): 62 | roman = "MCMXCIV" 63 | result = 1994 64 | self.assertEqual(Solution().romanToInt(roman), result) 65 | 66 | def test_answer_05(self): 67 | roman = "MDCXCV" 68 | result = 1695 69 | self.assertEqual(Solution().romanToInt(roman), result) 70 | 71 | 72 | if __name__ == '__main__': 73 | unittest.main() 74 | -------------------------------------------------------------------------------- /test_Number_of_1_Bits_191.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Number_of_1_Bits_191 import Solution, SolutionBitOperations 3 | 4 | """ 5 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 6 | 7 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 8 | 9 | 10 | Example 1: 11 | 12 | Input: n = 00000000000000000000000000001011 13 | Output: 3 14 | Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. 15 | 16 | Example 2: 17 | 18 | Input: n = 00000000000000000000000010000000 19 | Output: 1 20 | Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. 21 | 22 | Example 3: 23 | 24 | Input: n = 11111111111111111111111111111101 25 | Output: 31 26 | Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits. 27 | 28 | """ 29 | 30 | class Test_Case(unittest.TestCase): 31 | def test_answer_01(self): 32 | n = 11 33 | # 0000 0000 0000 0000 0000 0000 0000 1011 34 | result = 3 35 | # self.assertEqual(Solution().hammingWeight(n), result) 36 | self.assertEqual(SolutionBitOperations().hammingWeight(n), result) 37 | 38 | def test_answer_02(self): 39 | n = 128 40 | # 0000 0000 0000 0000 0000 0000 1000 0000 41 | result = 1 42 | # self.assertEqual(Solution().hammingWeight(n), result) 43 | self.assertEqual(SolutionBitOperations().hammingWeight(n), result) 44 | 45 | def test_answer_03(self): 46 | n = 4294967293 47 | # 1111 1111 1111 1111 1111 1111 1111 1101 48 | result = 31 49 | # self.assertEqual(Solution().hammingWeight(n), result) 50 | self.assertEqual(SolutionBitOperations().hammingWeight(n), result) 51 | 52 | if __name__ == "__main__": 53 | unittest.main() 54 | -------------------------------------------------------------------------------- /test_Valid_Parentheses_020.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Valid_Parentheses_020 import * 3 | 4 | ''' 5 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 6 | 7 | An input string is valid if: 8 | 9 | Open brackets must be closed by the same type of brackets. 10 | Open brackets must be closed in the correct order. 11 | Note that an empty string is also considered valid. 12 | 13 | Example 1: 14 | Input: "()" 15 | Output: true 16 | 17 | Example 2: 18 | Input: "()[]{}" 19 | Output: true 20 | 21 | Example 3: 22 | Input: "(]" 23 | Output: false 24 | 25 | Example 4: 26 | Input: "([)]" 27 | Output: false 28 | 29 | Example 5: 30 | Input: "{[]}" 31 | Output: true 32 | ''' 33 | 34 | 35 | class Test_Case(unittest.TestCase): 36 | 37 | def test_answer_01(self): 38 | input = "()" 39 | result = True 40 | self.assertEqual(Solution().isValid(input), result) 41 | 42 | def test_answer_02(self): 43 | input = "()[]{}" 44 | result = True 45 | self.assertEqual(Solution().isValid(input), result) 46 | 47 | def test_answer_03(self): 48 | input = "(]" 49 | result = False 50 | self.assertEqual(Solution().isValid(input), result) 51 | 52 | def test_answer_04(self): 53 | input = "([)]" 54 | result = False 55 | self.assertEqual(Solution().isValid(input), result) 56 | 57 | def test_answer_05(self): 58 | input = "{[]}" 59 | result = True 60 | self.assertEqual(Solution().isValid(input), result) 61 | 62 | def test_answer_06(self): 63 | input = "}[]{" 64 | result = False 65 | self.assertEqual(Solution().isValid(input), result) 66 | 67 | def test_answer_07(self): 68 | input = "[" 69 | result = False 70 | self.assertEqual(Solution().isValid(input), result) 71 | 72 | 73 | if __name__ == '__main__': 74 | unittest.main() 75 | -------------------------------------------------------------------------------- /test_Reverse_Bits_190.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Reverse_Bits_190 import Solution, SolutionBitOperations 3 | 4 | """ 5 | Reverse bits of a given 32 bits unsigned integer. 6 | 7 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 8 | 9 | Follow up: 10 | If this function is called many times, how would you optimize it? 11 | 12 | Related problem: Reverse Integer 13 | """ 14 | 15 | class Test_Case(unittest.TestCase): 16 | def test_answer_01(self): 17 | n = 8 18 | # 0000 0000 0000 0000 0000 0000 0000 1000 19 | # 0001 0000 0000 0000 0000 0000 0000 0000 20 | result = 268435456 21 | # self.assertEqual(Solution().reverseBits(n), result) 22 | self.assertEqual(SolutionBitOperations().reverseBits(n), result) 23 | 24 | def test_answer_02(self): 25 | n = 43261596 26 | # 0000 0010 1001 0100 0001 1110 1001 1100 27 | # 0011 1001 0111 1000 0010 1001 0100 0000 28 | result = 964176192 29 | # self.assertEqual(Solution().reverseBits(n), result) 30 | self.assertEqual(SolutionBitOperations().reverseBits(n), result) 31 | 32 | def test_answer_03(self): 33 | n = 4294967293 34 | # 1111 1111 1111 1111 1111 1111 1111 1101 35 | # 1011 1111 1111 1111 1111 1111 1111 1111 36 | result = 3221225471 37 | # self.assertEqual(Solution().reverseBits(n), result) 38 | self.assertEqual(SolutionBitOperations().reverseBits(n), result) 39 | 40 | def test_answer_04(self): 41 | n = 0 42 | # 0000 0000 0000 0000 0000 0000 0000 0000 43 | # 0000 0000 0000 0000 0000 0000 0000 0000 44 | result = 0 45 | # self.assertEqual(Solution().reverseBits(n), result) 46 | self.assertEqual(SolutionBitOperations().reverseBits(n), result) 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /Contains_Duplicate_II_219.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | Given an array of integers and an integer k, 4 | find out whether there are two distinct indices i and j 5 | in the array such that nums[i] = nums[j] 6 | and the absolute difference between i and j is at most k. 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,2,3,1], k = 3 11 | Output: true 12 | 13 | Example 2: 14 | 15 | Input: nums = [1,0,1,1], k = 1 16 | Output: true 17 | 18 | Example 3: 19 | 20 | Input: nums = [1,2,3,1,2,3], k = 2 21 | Output: false 22 | 23 | ''' 24 | 25 | class Solution(object): 26 | def containsNearbyDuplicate(self, nums, k): 27 | """ 28 | :type nums: List[int] 29 | :type k: int 30 | :rtype: bool 31 | """ 32 | 33 | temp = dict() 34 | 35 | for i, v in enumerate(nums): 36 | if v in temp: 37 | if i - temp[v] <= k: 38 | return True 39 | temp[v] = i 40 | return False 41 | 42 | 43 | class SolutionSet(object): 44 | def containsNearbyDuplicate(self, nums, k): 45 | """ 46 | :type nums: List[int] 47 | :type k: int 48 | :rtype: bool 49 | 50 | """ 51 | s = set() 52 | for i in range(len(nums)): 53 | if i > k : 54 | s.remove(nums[i-k-1]) # 多思考一下 55 | if nums[i] in s: 56 | return True 57 | s.add(nums[i]) 58 | return False 59 | 60 | 61 | class Solution_Time_Limit_Exceeded(object): 62 | def containsNearbyDuplicate(self, nums, k): 63 | """ 64 | :type nums: List[int] 65 | :type k: int 66 | :rtype: bool 67 | """ 68 | count = 0 69 | data = [] 70 | while count < len(nums): 71 | for i,v in enumerate(nums): 72 | if nums[count] == v and i != count: 73 | data.append(i-count) 74 | count += 1 75 | 76 | for d in set(data): 77 | if abs(d) <= k: 78 | return True 79 | return False 80 | 81 | -------------------------------------------------------------------------------- /Two_Sum_001.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 | 8 | Given nums = [2, 7, 11, 15], target = 9, 9 | 10 | Because nums[0] + nums[1] = 2 + 7 = 9, 11 | return [0, 1]. 12 | 13 | apply Hash Table 14 | ref. https://en.wikipedia.org/wiki/Hash_table 15 | ''' 16 | 17 | 18 | class Solution: 19 | def twoSum(self, nums, target): 20 | """ 21 | :type nums: List[int] 22 | :type target: int 23 | :rtype: List[int] 24 | """ 25 | for index_one, one in enumerate(nums): 26 | for index_two, two in enumerate(nums): 27 | if (one != two) and (one + two == target): 28 | return [index_one, index_two] 29 | 30 | """ 31 | If there is a repetition in nums , will FAILED 32 | """ 33 | 34 | 35 | class Solution_Improve: 36 | def twoSum(self, nums, target): 37 | for index_one in range(len(nums)): 38 | for index_two in range(index_one + 1, len(nums)): 39 | if nums[index_one] + nums[index_two] == target: 40 | return [index_one, index_two] 41 | 42 | 43 | class Solution_better: 44 | def twoSum(self, nums, target): 45 | """ 46 | :type nums: List[int] 47 | :type target: int 48 | :rtype: List[int] 49 | """ 50 | """ 51 | Hash Table 52 | 53 | Search 54 | Average : O(1) 55 | Worst case : O(n) 56 | """ 57 | dict_temp = dict() 58 | for index, value in enumerate(nums): 59 | if target - value in dict_temp: 60 | return [dict_temp[target - value], index] 61 | dict_temp[value] = index 62 | 63 | 64 | class Solution_failed: 65 | # failed test_answer_04 66 | def twoSum(self, nums, target): 67 | correct = [] 68 | for i in range(len(nums)): 69 | if target - nums[i] in nums: 70 | correct.append(i) 71 | return correct -------------------------------------------------------------------------------- /test_Longest_Common_Prefix_014.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Longest_Common_Prefix_014 import * 3 | 4 | ''' 5 | Write a function to find the longest common prefix string amongst an array of strings. 6 | 7 | If there is no common prefix, return an empty string "". 8 | 9 | Example 1: 10 | Input: ["flower","flow","flight"] 11 | Output: "fl" 12 | 13 | Example 2: 14 | Input: ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | Note: 19 | 20 | All given inputs are in lowercase letters a-z. 21 | ''' 22 | 23 | 24 | class Test_Case(unittest.TestCase): 25 | 26 | def test_answer_01(self): 27 | strs = ["flower", "flow", "flight"] 28 | result = "fl" 29 | self.assertEqual(Solution().longestCommonPrefix(strs), result) 30 | 31 | def test_answer_02(self): 32 | strs = ["dog", "racecar", "car"] 33 | result = "" 34 | self.assertEqual(Solution().longestCommonPrefix(strs), result) 35 | 36 | def test_answer_03(self): 37 | strs = [] 38 | result = "" 39 | self.assertEqual(Solution().longestCommonPrefix(strs), result) 40 | 41 | def test_answer_04(self): 42 | strs = [""] 43 | result = "" 44 | self.assertEqual(Solution().longestCommonPrefix(strs), result) 45 | 46 | def test_answer_05(self): 47 | strs = ["a"] 48 | result = "a" 49 | self.assertEqual(Solution().longestCommonPrefix(strs), result) 50 | 51 | def test_answer_06(self): 52 | strs = ["aa", "aa"] 53 | result = "aa" 54 | self.assertEqual(Solution().longestCommonPrefix(strs), result) 55 | 56 | def test_answer_07(self): 57 | input = ["", "b"] 58 | result = "" 59 | self.assertEqual(Solution().longestCommonPrefix(input), result) 60 | 61 | def test_answer_08(self): 62 | input = ["aaa", "aa", "aaa"] 63 | result = "aa" 64 | self.assertEqual(Solution().longestCommonPrefix(input), result) 65 | 66 | def test_answer_09(self): 67 | input = ["aaa", "aa", "aaaa", "aac"] 68 | result = "aa" 69 | self.assertEqual(Solution().longestCommonPrefix(input), result) 70 | 71 | 72 | if __name__ == '__main__': 73 | unittest.main() 74 | -------------------------------------------------------------------------------- /test_Bulls_and_Cows_299.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Bulls_and_Cows_299 import Solution 3 | 4 | ''' 5 | Example 1: 6 | 7 | Input: secret = "1807", guess = "7810" 8 | Output: "1A3B" 9 | Explanation: Bulls are connected with a '|' and cows are underlined: 10 | "1807" 11 | | 12 | "7810" 13 | 14 | Example 2: 15 | 16 | Input: secret = "1123", guess = "0111" 17 | Output: "1A1B" 18 | Explanation: Bulls are connected with a '|' and cows are underlined: 19 | "1123" "1123" 20 | | or | 21 | "0111" "0111" 22 | Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. 23 | 24 | Example 3: 25 | 26 | Input: secret = "1", guess = "0" 27 | Output: "0A0B" 28 | 29 | Example 4: 30 | 31 | Input: secret = "1", guess = "1" 32 | Output: "1A0B" 33 | ''' 34 | 35 | class Test_Case(unittest.TestCase): 36 | 37 | def test_answer_01(self): 38 | secret = "1807" 39 | guess = "7810" 40 | result = "1A3B" 41 | self.assertEqual(Solution().getHint(secret, guess), result) 42 | 43 | def test_answer_02(self): 44 | secret = "1123" 45 | guess = "0111" 46 | result = "1A1B" 47 | self.assertEqual(Solution().getHint(secret, guess), result) 48 | 49 | def test_answer_03(self): 50 | secret = "1" 51 | guess = "0" 52 | result = "0A0B" 53 | self.assertEqual(Solution().getHint(secret, guess), result) 54 | 55 | def test_answer_04(self): 56 | secret = "1" 57 | guess = "1" 58 | result = "1A0B" 59 | self.assertEqual(Solution().getHint(secret, guess), result) 60 | 61 | def test_answer_05(self): 62 | secret = "11" 63 | guess = "10" 64 | result = "1A0B" 65 | self.assertEqual(Solution().getHint(secret, guess), result) 66 | 67 | def test_answer_06(self): 68 | secret = "1123" 69 | guess = "0111" 70 | result = "1A1B" 71 | self.assertEqual(Solution().getHint(secret, guess), result) 72 | 73 | def test_answer_07(self): 74 | secret = "1122" 75 | guess = "0001" 76 | result = "0A1B" 77 | self.assertEqual(Solution().getHint(secret, guess), result) 78 | 79 | if __name__ == '__main__': 80 | unittest.main() 81 | -------------------------------------------------------------------------------- /test_Count_and_Say_038.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Count_and_Say_038 import * 3 | 4 | ''' 5 | The count-and-say sequence is the sequence of integers with the first five terms as following: 6 | 7 | 1. 1 8 | 2. 11 9 | 3. 21 10 | 4. 1211 11 | 5. 111221 12 | 1 is read off as "one 1" or 11. 13 | 11 is read off as "two 1s" or 21. 14 | 21 is read off as "one 2, then one 1" or 1211. 15 | 16 | The following are the terms from n=1 to n=10 of the count-and-say sequence: 17 | 1. 1 18 | 2. 11 19 | 3. 21 20 | 4. 1211 21 | 5. 111221 22 | 6. 312211 23 | 7. 13112221 24 | 8. 1113213211 25 | 9. 31131211131221 26 | 10. 13211311123113112211 27 | ''' 28 | 29 | 30 | class Test_Case(unittest.TestCase): 31 | 32 | def test_answer_01(self): 33 | n = 1 34 | result = '1' 35 | self.assertEqual(Solution().countAndSay(n), result) 36 | 37 | def test_answer_02(self): 38 | n = 2 39 | result = '11' 40 | self.assertEqual(Solution().countAndSay(n), result) 41 | 42 | def test_answer_03(self): 43 | n = 3 44 | result = '21' 45 | self.assertEqual(Solution().countAndSay(n), result) 46 | 47 | def test_answer_04(self): 48 | n = 4 49 | result = '1211' 50 | self.assertEqual(Solution().countAndSay(n), result) 51 | 52 | def test_answer_05(self): 53 | n = 5 54 | result = '111221' 55 | self.assertEqual(Solution().countAndSay(n), result) 56 | 57 | def test_answer_06(self): 58 | n = 6 59 | result = '312211' 60 | self.assertEqual(Solution().countAndSay(n), result) 61 | 62 | def test_answer_07(self): 63 | n = 7 64 | result = '13112221' 65 | self.assertEqual(Solution().countAndSay(n), result) 66 | 67 | def test_answer_08(self): 68 | n = 8 69 | result = '1113213211' 70 | self.assertEqual(Solution().countAndSay(n), result) 71 | 72 | def test_answer_09(self): 73 | n = 9 74 | result = '31131211131221' 75 | self.assertEqual(Solution().countAndSay(n), result) 76 | 77 | def test_answer_10(self): 78 | n = 10 79 | result = '13211311123113112211' 80 | self.assertEqual(Solution().countAndSay(n), result) 81 | 82 | 83 | if __name__ == '__main__': 84 | unittest.main() 85 | -------------------------------------------------------------------------------- /Search_Insert_Position_035.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Example 1: 7 | Input: [1,3,5,6], 5 8 | Output: 2 9 | 10 | Example 2: 11 | Input: [1,3,5,6], 2 12 | Output: 1 13 | 14 | Example 3: 15 | Input: [1,3,5,6], 7 16 | Output: 4 17 | 18 | Example 4: 19 | Input: [1,3,5,6], 0 20 | Output: 0 21 | 22 | Example 5: 23 | Input: nums = [1], target = 0 24 | Output: 0 25 | ''' 26 | 27 | class Solution: 28 | def searchInsert(self, nums, target): 29 | """ 30 | :type nums: List[int] 31 | :type target: int 32 | :rtype: int 33 | """ 34 | 35 | for index, value in enumerate(nums): 36 | if value >= target: 37 | return index 38 | return len(nums) 39 | 40 | 41 | class Solution_bisect: 42 | def searchInsert(self, nums, target): 43 | """ 44 | :type nums: List[int] 45 | :type target: int 46 | :rtype: int 47 | """ 48 | # this is very close the bisect module in python library, which is even conciser. 49 | # ref. https://leetcode.com/problems/search-insert-position/discuss/15378/A-fast-and-concise-python-solution-40ms-binary-search 50 | left = 0 51 | right = len(nums) - 1 52 | while left <= right: 53 | mid = int((left + right) / 2) 54 | # mid = (left + right) // 2 55 | if nums[mid] == target: 56 | return mid 57 | if nums[mid] < target: 58 | left = mid + 1 59 | else: 60 | right = mid - 1 61 | return left 62 | 63 | 64 | class Solution_recursive: 65 | def searchInsert(self, nums, target): 66 | """ 67 | :type nums: List[int] 68 | :type target: int 69 | :rtype: int 70 | """ 71 | return self.recursive(nums, 0, len(nums)-1, target) 72 | 73 | def recursive(self, nums, left, right, target): 74 | mid = (left + right) // 2 75 | if left > right: 76 | return left 77 | if nums[mid] > target: 78 | return self.recursive(nums, left, mid - 1, target) 79 | if nums[mid] < target: 80 | return self.recursive(nums, mid + 1, right, target) 81 | return mid 82 | -------------------------------------------------------------------------------- /test_Rotate_Array_189.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Rotate_Array_189 import * 3 | 4 | ''' 5 | Given an array, rotate the array 6 | 7 | to the right by k steps, where k is non-negative. 8 | 9 | Follow up: 10 | 11 | Try to come up as many solutions as you can, 12 | there are at least 3 different ways to solve this problem. 13 | Could you do it in-place with O(1) extra space? 14 | 15 | 16 | Input: nums = [1,2,3,4,5,6,7], k = 3 17 | Output: [5,6,7,1,2,3,4] 18 | Explanation: 19 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 20 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 21 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 22 | 23 | 24 | Input: nums = [-1,-100,3,99], k = 2 25 | Output: [3,99,-1,-100] 26 | Explanation: 27 | rotate 1 steps to the right: [99,-1,-100,3] 28 | rotate 2 steps to the right: [3,99,-1,-100] 29 | ''' 30 | 31 | class Test_Case(unittest.TestCase): 32 | 33 | def test_answer_01(self): 34 | nums = [1,2,3,4,5,6,7] 35 | k = 3 36 | result = [5,6,7,1,2,3,4] 37 | self.assertEqual(Solution().rotate(nums, k), result) 38 | 39 | def test_answer_02(self): 40 | nums = [-1,-100,3,99] 41 | k = 2 42 | result = [3,99,-1,-100] 43 | self.assertEqual(Solution().rotate(nums, k), result) 44 | 45 | def test_answer_03(self): 46 | nums = [1,2,3,4,5,6,7] 47 | k = 3 48 | result = [5,6,7,1,2,3,4] 49 | self.assertEqual(Solution().rotate(nums, k), result) 50 | 51 | def test_answer_04(self): 52 | nums = [-1,-100,3,99] 53 | k = 2 54 | result = [3,99,-1,-100] 55 | self.assertEqual(Solution().rotate(nums, k), result) 56 | 57 | def test_answer_05(self): 58 | nums = [1] 59 | k = 0 60 | result = [1] 61 | self.assertEqual(Solution().rotate(nums, k), result) 62 | 63 | def test_answer_06(self): 64 | nums = [1,2] 65 | k = 3 66 | result = [2,1] 67 | self.assertEqual(Solution().rotate(nums, k), result) 68 | 69 | def test_answer_07(self): 70 | nums = [1,2,3] 71 | k = 1 72 | result = [3,1,2] 73 | self.assertEqual(Solution().rotate(nums, k), result) 74 | 75 | def test_answer_08(self): 76 | nums = [1,2,3] 77 | k = 2 78 | result = [2,3,1] 79 | self.assertEqual(Solution().rotate(nums, k), result) 80 | 81 | 82 | if __name__ == '__main__': 83 | unittest.main() 84 | -------------------------------------------------------------------------------- /Longest_Increasing_Subsequence_300.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | """ 4 | Input: nums = [10,9,2,5,3,7,101,18] 5 | [2,3,7,101] 6 | Output: 4 7 | 8 | Input: nums = [0,1,0,3,2,3] 9 | Output: 4 10 | 11 | Input: nums = [7,7,7,7,7,7,7] 12 | Output: 1 13 | """ 14 | 15 | 16 | class Solution_DP: 17 | # 忘記可參考 https://www.youtube.com/watch?v=l2rCz7skAlk 18 | # DP = 動態規劃 19 | # 複雜度爲O(n*n) 20 | def lengthOfLIS(self, nums: List[int]) -> int: 21 | if not nums: 22 | return 0 23 | 24 | dp = [1] * len(nums) 25 | 26 | for i in range(1, len(nums)): 27 | for j in range(0, i): 28 | if nums[i] > nums[j]: 29 | dp[i] = max(dp[i], dp[j] + 1) 30 | 31 | return max(dp) 32 | 33 | 34 | class Solution_BinarySearch: 35 | # 忘記可參考 https://www.youtube.com/watch?v=l2rCz7skAlk 36 | # DP + BinarySearch 37 | 38 | # 步驟 39 | # 將第1個數字加入解集; 40 | 41 | # 依次讀取後面的數字,如果此數字比解集中最後一個數字大,則將此數字追加到解集後, 42 | # 否則,用這個數字替換解集中第一個比此數字大的數,解集是有序的,因此查找可以用二分法, 43 | # 複雜度O(log n); 44 | 45 | # 最後的答案是解集的長度(而解集中保存的並不一定是合法解)。 46 | 47 | # 複雜度爲O(n*n) 48 | def lengthOfLIS(self, nums: List[int]) -> int: 49 | 50 | n = len(nums) 51 | if n == 0: 52 | return 0 53 | rst = [nums[0]] 54 | for i in range(1, n): 55 | if nums[i] > rst[-1]: 56 | rst.append(nums[i]) 57 | else: 58 | index = self.binarySearch(rst, nums[i]) 59 | rst[index] = nums[i] 60 | return len(rst) 61 | 62 | def binarySearch(self, seqs, target): 63 | left = 0 64 | right = len(seqs) - 1 65 | while left <= right: 66 | m = (left + right) // 2 67 | 68 | if seqs[m] > target: 69 | right = m - 1 70 | elif seqs[m] < target: 71 | left = m + 1 72 | else: 73 | return m 74 | return left 75 | 76 | 77 | import bisect 78 | 79 | 80 | class Solution_bisect: 81 | def lengthOfLIS(self, nums: List[int]) -> int: 82 | """ 83 | :type nums: List[int] 84 | :rtype: int 85 | """ 86 | n = len(nums) 87 | if n == 0: 88 | return 0 89 | rst = [] 90 | for x in nums: 91 | i = bisect.bisect_left(rst, x) 92 | if i == len(rst): 93 | rst.append(x) 94 | else: 95 | rst[i] = x 96 | return len(rst) 97 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode-python 2 | 3 | LeetCode use Python :memo: 4 | 5 | ## 說明 6 | 7 | 分享 [LeetCode](https://leetcode.com/) 上練習的題目,在這裡把解出來的題目和大家做分享並且記錄一下, 8 | 9 | 並不是全部的題目都是自己寫出來的,有些題目是上網參考別人的答案:smile:, 10 | 11 | 會持續做更新:pencil2: 12 | 13 | ## 題目 14 | 15 | [001-Two Sum](https://github.com/twtrubiks/leetcode-python/blob/master/Two_Sum_001.py) - youtube tutorial [001 Two Sum](https://youtu.be/fo5knjhk-i0) 16 | 17 | [007-Reverse Integer](https://github.com/twtrubiks/leetcode-python/blob/master/Reverse_Integer_007.py) - youtube tutorial [007 Reverse Integer](https://youtu.be/sPK7Lw7Ospg) 18 | 19 | [009-Palindrome Number](https://github.com/twtrubiks/leetcode-python/blob/master/Palindrome_Number_009.py) - youtube tutorial [009 Palindrome Number](https://youtu.be/B2viRb1aJ7Q) 20 | 21 | [013-Roman to Integer](https://github.com/twtrubiks/leetcode-python/blob/master/Roman_to_Integer_013.py) - youtube tutorial [013 Roman to Integer](https://youtu.be/es88R2AYc_0) 22 | 23 | [014-Longest Common Prefix](https://github.com/twtrubiks/leetcode-python/blob/master/Longest_Common_Prefix_014.py) - youtube tutorial [014 Longest Common Prefix]( https://youtu.be/t-oA2U27d4w) 24 | 25 | [020-Valid Parentheses](https://github.com/twtrubiks/leetcode-python/blob/master/Valid_Parentheses_020.py) - youtube tutorial [020 Valid Parentheses](https://youtu.be/snSaKshK-Ws) 26 | 27 | [021-Merge Two Sorted Lists](https://github.com/twtrubiks/leetcode-python/blob/master/Merge_Two_Sorted_Lists_021.py) - youtube tutorial [待新增021 Merge Two Sorted Lists](xxx) - [explanation](https://github.com/twtrubiks/leetcode-python/blob/master/Merge_Two_Sorted_Lists_021_explanation.py) 28 | 29 | [026-Remove Duplicates from Sorted Array](https://github.com/twtrubiks/leetcode-python/blob/master/Remove_Duplicates_from_Sorted_Array_026.py) - youtube tutorial [待新增026 Remove Duplicates from Sorted Array](xxx) - [explanation](https://github.com/twtrubiks/leetcode-python/blob/master/Remove_Duplicates_from_Sorted_Array_026_explanation.py) 30 | 31 | [027-Remove Element](https://github.com/twtrubiks/leetcode-python/blob/master/Remove_Element_027.py) - youtube tutorial [待新增027Remove Element](xxx) - [explanation](https://github.com/twtrubiks/leetcode-python/blob/master/Remove_Element_027_explanation.py) 32 | 33 | [028-Implement strStr()](https://github.com/twtrubiks/leetcode-python/blob/master/Implement_strStr_028.py) - youtube tutorial [待新增028Implement strStr()](xxx) 34 | 35 | [035-Search Insert Position](https://github.com/twtrubiks/leetcode-python/blob/master/Search_Insert_Position_035.py) - youtube tutorial [待新增035Search Insert Position](xxx) 36 | 37 | [038-Count and Say](https://github.com/twtrubiks/leetcode-python/blob/master/Count_and_Say_038.py) - youtube tutorial [待新增038Count and Say](xxx) 38 | 39 | [053-Maximum Subarray](https://github.com/twtrubiks/leetcode-python/blob/master/Maximum_Subarray_053.py) - youtube tutorial [待新增053Maximum Subarray](xxx) 40 | 41 | [058-Length of Last Word](https://github.com/twtrubiks/leetcode-python/blob/master/Length_of_Last_Word_058.py) - youtube tutorial [待新增058Length of Last Word](xxx) 42 | 43 | [066-Plus One](https://github.com/twtrubiks/leetcode-python/blob/master/Plus_One_066.py) - youtube tutorial [待新增066Plus One](xxx) 44 | 45 | [067-Add Binary](https://github.com/twtrubiks/leetcode-python/blob/master/Add_Binary_067.py) - youtube tutorial [待新增067Add Binary](xxx) 46 | 47 | [069-Sqrt(x)](https://github.com/twtrubiks/leetcode-python/blob/master/Sqrtx_069.py) - youtube tutorial [待新增069Sqrt(x)](xxx) 48 | 49 | [070-Climbing Stairs](https://github.com/twtrubiks/leetcode-python/blob/master/Climbing_Stairs_070.py) - youtube tutorial [待新增070Climbing Stairs](xxx) 50 | 51 | [080-Remove Duplicates from Sorted Array II](https://github.com/twtrubiks/leetcode-python/blob/master/Remove_Duplicates_from_Sorted_Array_II_080.py) - youtube tutorial [待新增](xxx) 52 | 53 | ## 執行環境 54 | 55 | * Python 3.6.6 56 | 57 | ## Donation 58 | 59 | 文章都是我自己研究內化後原創,如果有幫助到您,也想鼓勵我的話,歡迎請我喝一杯咖啡:laughing: 60 | 61 | ![alt tag](https://i.imgur.com/LRct9xa.png) 62 | 63 | [贊助者付款](https://payment.opay.tw/Broadcaster/Donate/9E47FDEF85ABE383A0F5FC6A218606F8) 64 | 65 | ## License 66 | 67 | MIT license 68 | --------------------------------------------------------------------------------