fromcollectionsimportdefaultdictclassSolution(object):deftwoSum(self,nums,target):"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""# # Let's try a simple solution first# # O(n^2) - Time, O(1) - space# for i, first in enumerate(nums):# for j, second in enumerate(nums):# if i == j: continue# if first + second == target:# return [i, j]## Two pass hash map## O(n^2) - Time, O(n) space# data = defaultdict(list)# for i, x in enumerate(nums):# data[x].append(i)# for k, v in data.items():# chk_s = target - k# diff = data.get(chk_s)# if diff:# if len(diff) > 1:# return [diff[0], diff[1]]# else:# if chk_s != k:# return [v[0], data[chk_s][0]]## Cleaner hashmap solution## Two pass hashmap## O(n) - time , O(n) - space# data = {}# for i, x in enumerate(nums):# data[x] = i# for i, x in enumerate(nums):# diff = target - x# if diff in data and i != data[diff]:# return [i, data[diff]]## Cleaner hashmap solution## One pass hashmap## O(n) - time , O(n) - spacedata={}fori,xinenumerate(nums):diff=target-xifdiffindata:return[i,data[diff]]data[x]=i
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
1
2
3
4
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
1
2
3
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
classSolution(object):defmaxProfit(self,prices):"""
:type prices: List[int]
:rtype: int
"""## O(n^2) don't pass# max_profit = 0# for i, x in enumerate(prices):# for y in prices[i:]:# max_profit = max(max_profit, y-x)# return int(max_profit)# O(n) - time , O(1) - spaceprice=prices[0]max_profit=0forxinprices:ifx<price:price=xcontinuepotential_profit=x-priceifpotential_profit>max_profit:max_profit=potential_profitreturnmax_profit
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and
removing all non-alphanumeric characters, it reads the same forward and
backward. Alphanumeric characters include letters and numbers.
Given a string s, return trueif it is a palindrome, orfalseotherwise.
Example 1:
1
2
3
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
1
2
3
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
1
2
3
4
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
classSolution(object):defisPalindrome(self,s):"""
:type s: str
:rtype: bool
"""# Fast and accepted# s = s.lower()# s = [x for x in s if x.isalnum()]# # print(s)# len_s = len(s)# for i in range(len_s//2):# if s[i] == s[-i-1]:# continue# else:# return False# return True# Fasters=s.lower()s=[xforxinsifx.isalnum()]len_s=len(s)returnall(s[i]==s[-i-1]foriinrange(len_s//2))
# Definition for a binary tree node.classTreeNode:def__init__(self,val=0,left=None,right=None):self.val=valself.left=leftself.right=rightdefbuild_binary_tree(root):"""
create a binary tree from array
root: array
"""tot_nodes=len(root)tree_nodes=[]foriinrange(tot_nodes):tree_nodes.append(TreeNode(val=root[i]))foriinrange(tot_nodes//2):tree_nodes[i].left=tree_nodes[i*2+1]tree_nodes[i].right=tree_nodes[i*2+2]returntree_nodes[0]deftraverse_binary_tree(root):"""
Traverse a binary tree
root: TreeNode
"""bt_arr=[]stack=[root]whilestack:node=stack.pop(0)bt_arr.append(node.val)ifnode.left:stack.append(node.left)ifnode.right:stack.append(node.right)returnbt_arrclassSolution(object):definvertTree(self,root):"""
:type root: TreeNode
:rtype: TreeNode
"""stack=[root]whilestack:node=stack.pop(0)ifnode:ifnode.left:stack.append(node.left)ifnode.right:stack.append(node.right)node.left,node.right=node.right,node.leftreturnroot
Given two strings s and t, return trueiftis an anagram ofs, andfalseotherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the vaoriginal letters exactly once.
Example 1:
1
2
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
1
2
Input: s = "rat", t = "car"
Output: false
Constraints:
1 <= s.length, t.length <= 5 * 10^4
s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
1
2
3
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
1
2
3
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
fromtypingimportListclassSolution:defsearch(self,nums:List[int],target:int)->int:# O(log(N)) solutionstart,end=0,len(nums)-1whilestart<=end:# this prevents memory issues if numbers are too bigmid=start+(end-start)//2iftarget==nums[mid]:returnmideliftarget<=nums[mid]:end=mid-1else:start=mid+1return-1
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
Return the modified image after performing the flood fill.
1
2
3
4
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Example 2:
1
2
3
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
Output: [[0,0,0],[0,0,0]]
Explanation: The starting pixel is already colored 0, so no changes are made to the image.
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:
1
2
3
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
Example 2:
1
2
3
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Example 3:
1
2
Input: root = [2,1], p = 2, q = 1
Output: 2
Constraints:
The number of nodes in the tree is in the range [2, 105].
fromtypingimportList# Definition for a binary tree node.classTreeNode:def__init__(self,x):self.val=xself.left=Noneself.right=NoneclassSolution:deflowestCommonAncestor(self,root:TreeNode,p:TreeNode,q:TreeNode)->TreeNode:whileroot:# if root is higher than both p and q, then the lowest ancestor# must be on the left side of the root and vice versaifroot.val>p.valandroot.val>q.val:root=root.leftelifroot.val<p.valandroot.val<q.val:root=root.rightelse:returnroot
Instead of BST, the following code finds out LCA if the tree is Binary Tree
fromtypingimportList# Definition for a binary tree node.classTreeNode:def__init__(self,x):self.val=xself.left=Noneself.right=Noneself.parent=Noneself.level=0classSolution:defbuild_tree(self,nodes=[])->TreeNode:tot_nodes=len(nodes)tree_nodes=[]foriinrange(tot_nodes):tree_nodes.append(TreeNode(x=nodes[i]))foriinrange(tot_nodes//2):tree_nodes[i].left=tree_nodes[i*2+1]tree_nodes[i].right=tree_nodes[i*2+2]returntree_nodes[0]deftraverse_binary_tree(self,root):bt_arr=[]stack=[root]whilestack:node=stack.pop(0)bt_arr.append(node.val)ifnode.left:stack.append(node.left)ifnode.right:stack.append(node.right)returnbt_arrdefsearch(self,root:TreeNode,tgt:TreeNode)->TreeNode:stack=[root]whilestack:node=stack.pop(0)ifnode:ifnode.val==tgt.val:returnnodeifnode.left:node.left.parent=nodestack.append(node.left)ifnode.right:node.right.parent=nodestack.append(node.right)defbacktrace_root(self,tgt:TreeNode)->List:path=[]path=[tgt]whiletgt:path.append(tgt.parent)tgt=tgt.parentreturnpathdeflowestCommonAncestor(self,root:TreeNode,p:TreeNode,q:TreeNode)->TreeNode:head=rootroot.parent=Noneroot.level=0stack=[root]level=0# Add parents to treewhilestack:node=stack.pop(0)ifnode:level+=1ifnode.left:node.left.parent=nodenode.left.level=levelstack.append(node.left)ifnode.right:node.right.parent=nodenode.right.level=levelstack.append(node.right)path_p=self.backtrace_root(p)path_q=self.backtrace_root(q)# print([x.val for x in path_p ])# print([x.val for x in path_q if x])# print(path_p, path_q)common_nodes=set(path_p).intersection(set(path_q))common_nodes.remove(None)common_nodes=list(common_nodes)common_nodes=sorted(common_nodes,key=lambdax:x.level)returncommon_nodes[-1]if__name__=="__main__":p=TreeNode(x=2)q=TreeNode(x=4)# nodes = [6,2,8,0,4,7,9,"null","null",3,5]nodes=[6,2,8,0,4,7,9,"null","null",3,5]obj=Solution()root=obj.build_tree(nodes)print(obj.traverse_binary_tree(root))print(root.val,root.parent)p=obj.search(root=root,tgt=p)q=obj.search(root=root,tgt=q)print(p.val,p.parent,p.left,p.right)print(q.val,q.parent,q.left,q.right)print(obj.lowestCommonAncestor(root,p,q).val)