1. Valid Anagram (Leetcode Number: 242)
Create 2 empty lists that store the letters from two strings separately -> Sort the elements in order -> Compare 2 lists and return true if they are equal, otherwise return false
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# return sorted(s)==sorted(t)
hashlists = []
hashlistt = []
for letters in s:
hashlists.append(letters)
for lettert in t:
hashlistt.append(lettert)
hashlistss = sorted(hashlists)
print(hashlistss)
hashlisttt = sorted(hashlistt)
print(hashlisttt)
return sorted(hashlists) == sorted(hashlistt)
2. Intersection of Two Arrays(Leetcode Number: 349)
LIST VS SET
---set consumes more space than list
Create an empty return_list and convert the 2 input lists into sets -> get 2 sets sorted -> convert them back to lists -> starting from the first element of list1 till the last one in the list, check if it's in list2 -> If yes, append the element to return_list
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1 = list(sorted(set(nums1)))
set2 = list(sorted(set(nums2)))
return_list = []
for index in range(len(set1)):
if set1[index] in set2:
return_list.append(set1[index])
return return_list
3. Happy Number (Leetcode Number: 202)
In the while True loop, n should be always overwrite by the result returned from getsum. It will cause error if replace the n on the left side with another variable name as n must be the only correct variable and variable name in this case.
class Solution:
def isHappy(self, n: int) -> bool:
def getsum(num):
sum_num = 0
while num:
sum_num += (num % 10)**2
num = num // 10
return sum_num
record = set()
while True:
n = getsum(n)
if n == 1:
return True
elif n in record:
return False
else:
record.add(n)
4. Two Sum (Leetcode Number: 1)
First time failed due to using the wrong conditional statement if dic.get(ano_num) instead of the correct one if ano_num in dic
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Create a dictionary
dic = {}
for index in range(len(nums)):
ano_num = target - nums[index]
key = nums[index]
if ano_num in dic:
return [index, dic[ano_num]]
else:
dic[key] = index