By ACM
(Disclaimer, we aren't recruiters and don't know how companies make decisons)
Try do mock interviews with friends (or ACM) to help practice this
for(int i = 0; i < arr.size(); i++)
for(int i = 0; i < arr.size(); i++)
for(int j = 0; j < arr.size(); j++)
Text
def twoSum(arr, S):
sums = []
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
# Here we are only looking for a single pair,
# so we can return after we find it.
if (arr[i] + arr[j] == S):
sums.append(arr[i])
sums.append(arr[j])
return sums;
return None
Text
def twoSum(arr, S):
sums = []
hashTable = {}
for i in range(0, len(arr)):
sumMinusElement = S - arr[i]
# Lets check if we have seen S - arr[i] before. If so, then we have a pair.
if sumMinusElement in hashTable:
sums.append(arr[i])
sums.append(sumMinusElement)
return sums
# Lets put arr[i] in the hash table so that if we get anther value j such
# that arr[j] + arr[i] = s, we check if we have seen arr[i] in O(1).
hashTable[arr[i]] = arr[i]
return None
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
#base cases
if amount == 0:
return 0
if amount <= 0:
return float('inf')
best = float('inf')
for c in coins:
best = min(best, self.coinChange(coins, amount-c))
#deal with some edge cases
if best == float('inf'):
return -1
if best == -1:
return best
return best+1
16
9
11
13
4
6
2
6
4
8
8
6
10
class Solution:
def coinChangeH(self, coins: List[int], amount: int) -> int:
if amount in self.seen:
return self.seen[amount]
if amount == 0:
return 0
if amount <= 0:
return float('inf')
best = float('inf')
for c in coins:
best = min(best, self.coinChangeH(coins, amount-c))
if best == float('inf'):
self.seen[amount] = float('inf')
return float('inf')
self.seen[amount] = best+1
return best+1
def coinChange(self, coins: List[int], amount: int) -> int:
self.seen = {}
res = self.coinChangeH(coins, amount)
if res == float('inf'):
return -1
return res
Some leetcode weirdness requires initializing seen in the main coinChange rather than making it global/member var
Need to make sure to cache results of the failiures too
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root == None:
return []
ret = [[]]
queue = []
queue.append(root)
queue.append(None)
level = 0
while len(queue) > 1:
node = queue[0]
queue.pop(0)
if node == None:
ret.append([])
level+=1
queue.append(None)
else:
ret[level].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return ret