Home

Happy Number

202. Happy Number Solution Use set to remember the visited numbers. def isHappy(self, n): """ :type n: int :rtype: bool """ visited = set() while n not in visited: s = 0 visited.add(n) while n != 0: s += (n % 10) ** 2 n = n / 10 if s == 1: return True n = s return False ...

Read more

Count and Say

38. Count and Say Solution Reference def countAndSay(self, n): s = '1' for _ in range(n - 1): s = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(s)) return s

Read more

Pascal's Triangle

118. Pascal’s Triangle Solution def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] res = [[1]] for i in range(2, numRows+1): row = [1] * i for j in range(1, i-1): row[j] = res[-1][j-1] + res[-1][j] res.append(row) ...

Read more

Number of 1 Bits

191. Number of 1 Bits Solution def hammingWeight(self, n): """ :type n: int :rtype: int """ res = 0 while n != 0: tmp = n n = n >> 1 if n << 1 != tmp: res += 1 return res

Read more

Missing Number

268. Missing Number Solution Find the real number index in the arr. Set the number at the arr[index] to a updated number, which contains both the information that it is set and its original number. Find the unset number. def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ N = len(nums) # pri...

Read more

First Unique Character in a String

387. First Unique Character in a String Solution Get all indexes of characters in the string. Can use array and ascii number instead. If the length of indexes is 1, collect the index. Find the minimum of them. def firstUniqChar(self, s): """ :type s: str :rtype: int """ dic = collections.defaultdict(lis...

Read more

Maximum Nesting Depth of the Parentheses

1614. Maximum Nesting Depth of the Parentheses Solution The string is a valid parentheses string. We only need to count( for the number of parentheses. Remember to update the result if possible. def maxDepth(self, s): res = cur = 0 for c in s: if c == '(': cur += 1 res = max(res, cur...

Read more

Maximal Network Rank

1615. Maximal Network Rank There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is dir...

Read more