text
stringlengths
37
1.41M
''' There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells. ''' class Solution(object): def latestDayToCross(self, row, col, cells): l,h=0,len(cells)-1 ans=-1 while l<=h: m=(l+h)>>1 if self.isPath(cells,m,row,col): l=m+1 ans=m+1 else: h=m-1 return ans def isPath(self,cells,ind,row,col): grid=[[0 for i in range(col)] for j in range(row)] for i in range(ind+1): x,y=cells[i] grid[x-1][y-1]=1 vis=set() for i in range(col): if grid[0][i]!=1: dq=deque() dq.append((0,i)) dr=[(-1,0),(0,-1),(1,0),(0,1)] while dq: x,y=dq.popleft() if x==row-1: return True for d in dr: dx,dy=d if 0<=x+dx<row and 0<=y+dy<col and grid[x+dx][y+dy]!=1 and (x+dx,y+dy) not in vis: vis.add((x+dx,y+dy)) dq.append((x+dx,y+dy)) return False ------------------------------------------------------------------------------------------------------------------- def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int: grid = [[0]*col for i in range(row)] for i in range(len(cells)): grid[cells[i][0]-1][cells[i][1]-1] = i+1 # use binary search to find the max time lower = 0 upper = row*col while lower<upper: i = (lower+upper)//2 if self.canCross(i, grid): lower = i else: upper = i-1 if i==(lower+upper)//2: if self.canCross(i+1, grid): return i+1 else: return i return lower # given time t, check if it's able to cross using BFS def canCross(self, t: int, grid: List[List[int]]) -> bool: m = len(grid) n = len(grid[0]) cur = set() for j in range(n): cur.add((0,j)) directions = [[0,1],[0,-1],[1,0],[-1,0]] visited = set() while len(cur)>0: next_pos = set() for pos in cur: if pos in visited: continue x,y = pos visited.add(pos) if (0<=x<m) & (0<=y<n): if (x==m-1): if grid[x][y] > t: return True if grid[x][y] > t: # can safely pass this point next_pos.add((x+1,y)) next_pos.add((x-1,y)) next_pos.add((x,y+1)) next_pos.add((x,y-1)) cur = next_pos return False -------------------------------------------------------------------------------------------------------------------- class UF: def __init__(self, m, n): self.n, self.loc_id, c_id = n, dict(), 0 self.col_set = [set() for _ in range(m*n)] for i in range(m): # Assign id for each location (i ,j) for j in range(n): self.loc_id[(i, j)] = c_id self.col_set[c_id].add(j) c_id += 1 self.p = [i for i in range(m*n)] # Initialize parents array `p` def find(self, i): if self.p[i] != i: self.p[i] = self.find(self.p[i]) return self.p[i] def union(self, i, j): pi, pj = self.find(i), self.find(j) if pi != pj: self.p[pj] = pi # Update `pi` self.col_set[pi] = self.col_set[pi] | self.col_set[pj] # Take union of two sets (union all occupied columns) return len(self.col_set[pi]) == self.n # if length of col_set[pi] == self.n, meaning this piece occupied all columns from 1 to `col` inclusive, meaning we are blocked class Solution: def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int: uf, visited = UF(row, col), set() for i, (x, y) in enumerate(cells): x, y = x-1, y-1 visited.add((x, y)) for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (1, -1), (1, 0), (1, 1), (0, 1), (0, -1)]: _x, _y = x+dx, y+dy # Check if neighbor is flooded if 0 <= _x < row and 0 <= _y < col and (_x, _y) in visited: id1, id2 = uf.loc_id[(_x, _y)], uf.loc_id[(x, y)] if uf.union(id1, id2): return i # Union two flooded piece and return index if union return True return -1
''' Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. ''' class Solution: def countSubstrings(self, s: str, t: str) -> int: ans=0 arr=[] for i in range(len(s)):#Get All Substrings for j in range(i+1,len(s)+1): arr.append(s[i:j]) for w in arr: i=0 j=len(w) while j<=len(t): wrd=t[i:j] k=1#Only one difference allowed flag=True for m in range(len(wrd)): if w[m]!=wrd[m]: if k==1: k=0 else: flag=False break if flag and k==0: ans+=1 i+=1 j+=1 return ans ---------------------------------------------------------------------------------------------- class Solution: def countSubstrings(self, s: str, t: str) -> int: ans = 0 for i in range(len(s)): for j in range(len(t)): x = i y = j diff = 0 while x < len(s) and y < len(t): if s[x] != t[y]: diff+=1 if diff ==1: ans+=1 elif diff ==2: break x+=1 y+=1 return ans
''' A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. ''' class Solution: def minPartitions(self, n: str) -> int: return int(max(n))
''' You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 <= i < n and set the value of arr at index i to x. You may repeat this procedure as many times as needed. Return true if it is possible to construct the target array from arr, otherwise, return false. ''' """ALGORITHM TC = O(3n) aprox = O(n) Sc = O(n) for heap Intution came to mind after reading the hint ** INTUTION *** making an max heap with a copy of target. then converting the the max heap array to >> arr mentioned in question """ """ REFERENCE >> https://www.youtube.com/watch?v=voObxZxXoZw&t=0s """ class Solution: def isPossible(self, target: List[int]) -> bool: heap = [] total = 0 for i in range(len(target)): heap.append(-1 * (target[i])) total += target[i] heapq.heapify(heap) while heap: maxVal = -1 * (heapq.heappop(heap)) rem_sum = total - maxVal if maxVal == 1 or rem_sum == 1: return True if rem_sum == 0 or maxVal < rem_sum: return False newMaxVal = int(maxVal % rem_sum) #Changing operation for previous value if newMaxVal == 0: #value converted to less then 1 return False maxVal = newMaxVal heapq.heappush(heap, -1 * (maxVal)) total = newMaxVal + rem_sum return True ---------------------------------------------------------------------------------------------- There is a heap solution with O(n*log(n)) time | O(n) space modify input array by (target[i] = -target[i]), it helps us to use it in Min Heap find sum of all elements in target Start loop: 4) pop smallest element if element is -1, it means that we can retrurn True (it's possible to construct the target array from arr) subtract the element from sum if sum >= element or sum == 0, it mean that we can return False (it's not possible to construct the target array from arr) new_element = element mod sum (however it cant be 0, we should use the closest number to 0, in our case it is output of mod operation or sum) if new_element > -1, we can return False (it's not possible to construct the target array from arr) push new_element to heap add new_element to summ class Solution: def isPossible(self, target: List[int]) -> bool: heap = list(map(lambda x: -x,target)) heapq.heapify(heap) summ = sum(heap) while True: item = heapq.heappop(heap) if item == -1: return True summ-=item if item >= summ or summ == 0: return False item = item % summ if item % summ else summ if item > -1: return False heapq.heappush(heap,item) summ+=item
''' You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to left or from left to right. Repeat the second and third steps until you can't move in the tree. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree. ''' class Solution: def longestZigZag(self, root: Optional[TreeNode]) -> int: res = 0 if not root: return res q= deque() # node, isLeft, depth if root.left: q.append((root.left,True,1)) if root.right: q.append((root.right, False,1)) while q: node,isleft,depth = q.popleft() res = max(res,depth) if isleft: if node.right: q.append((node.right,False,depth+1)) if node.left: q.append((node.left,True,1)) else: if node.left: q.append((node.left,True,depth+1)) if node.right: q.append((node.right,False,1)) return res ----------------------------------------------------------------------------------------------------- class Solution: def longestZigZag(self, root: Optional[TreeNode]) -> int: self.res = 0 self.dfs(root.left,True,1) self.dfs(root.right,False,1) return self.res def dfs(self,node,isLeft,depth): if not node: return self.res = max(self.res,depth) if isLeft: self.dfs(node.left,True,1) self.dfs(node.right,False,depth+1) else: self.dfs(node.left,True,depth+1) self.dfs(node.right,False,1)
''' You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. ''' # my STUPID SOLUTION class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: def f(n): s = 0 a = str(n) for digit in a: digit = int(digit) s+= digit return s l = lowLimit h = highLimit a = [ 0 ]* 100 #for using this array i would get bad point - not knowing the better data structure is hashmap! for i in range(l, h+1): temp = f(i) a[temp] += 1 print(f'max is %d' % max(a)) return max(a) #MUCH BETTER SOLUTION inspired with idea from submissions with hashmap: class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: def numbersum(n): s = str(n) res = 0 for digit in s: res += int(digit) return res #hashmap hashmap = defaultdict(int) for i in range(lowLimit, highLimit+1): value = numbersum(i) hashmap[value]+=1 return max( hashmap.values())
''' Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getMinimumDifference(self, root: Optional[TreeNode]) -> int: if not root: return None def get(root, res): if not root: return None get(root.left,res) res.append(root.val) get(root.right, res) res = [] get(root,res) diff = float('inf') for i in range(len(res)-1): if res[i+1]- res[i] < diff: diff = res[i+1] - res[i] return diff
''' You are controlling a robot that is located somewhere in a room. The room is modeled as an m x n binary grid where 0 represents a wall and 1 represents an empty slot. The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API Robot. You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is 90 degrees. When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell. Design an algorithm to clean the entire room using the following APIs: interface Robot { // returns true if next cell is open and robot moves into the cell. // returns false if next cell is obstacle and robot stays on the current cell. boolean move(); // Robot will stay on the same cell after calling turnLeft/turnRight. // Each turn will be 90 degrees. void turnLeft(); void turnRight(); // Clean the current cell. void clean(); } Note that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall. ''' class Solution: def cleanRoom(self, robot): directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] cleaned = set() def dfs(robot, x, y, direction): if (x, y) in cleaned: return robot.clean() cleaned.add((x, y)) for i, (dx, dy) in enumerate(directions[direction:] + directions[:direction]): nx = x + dx ny = y + dy if robot.move(): dfs(robot, nx, ny, (direction + i) % 4) robot.turnLeft() robot.turnLeft() robot.move() robot.turnLeft() else: robot.turnRight() dfs(robot, 0, 0, 0) --------------------------------------------------------------------- I let the robot always facing the north, and wrote 4 functions to make it move to upward, left, right, and downward, yet still facing the north. (I know, I was just trying to save my brain) And, then it became a pretty normal DFS problem, I named the start point as (0, 0), and everything becomes clear. class Solution: def cleanRoom(self, robot): """ :type robot: Robot :rtype: None """ self.robot = robot self.robot.clean() self.visited = [(0,0)] self.dfs(0, 0) def dfs(self, x, y): if (x-1, y) not in self.visited and self.up(): self.robot.clean() self.visited.append((x-1, y)) self.dfs(x-1, y) self.down() if (x, y-1) not in self.visited and self.left(): self.robot.clean() self.visited.append((x, y-1)) self.dfs(x, y-1) self.right() if (x+1, y) not in self.visited and self.down(): self.robot.clean() self.visited.append((x+1, y)) self.dfs(x+1, y) self.up() if (x, y+1) not in self.visited and self.right(): self.robot.clean() self.visited.append((x, y+1)) self.dfs(x, y+1) self.left() def up(self): return self.robot.move() def left(self): self.robot.turnLeft() result = self.robot.move() self.robot.turnRight() return result def right(self): self.robot.turnRight() result = self.robot.move() self.robot.turnLeft() return result def down(self): self.robot.turnLeft() self.robot.turnLeft() result = self.robot.move() self.robot.turnRight() self.robot.turnRight() return result --------------------------------------------------------------------- import enum from collections import defaultdict from functools import lru_cache from typing import List, Optional, Tuple from collections import deque from itertools import cycle, tee class Direction(enum.Enum): Up = (-1, 0) Right = (0, 1) Down = (1, 0) Left = (0, -1) @lru_cache(maxsize=None) def num_right_rotations(self, other: 'Direction') -> int: if self == other: return 0 it = iter(cycle(Direction)) while True: if self == next(it): break for (i, direction) in enumerate(it, 1): if direction == other: return i raise ValueError(f'{other} is not a valid direction') @lru_cache(maxsize=None) def num_left_rotations(self, other: 'Direction') -> int: if self == other: return 0 return 4 - self.num_right_rotations(other) def __str__(self): return self.name def __repr__(self): return self.name class Status: Unknown = 0 Visited = 1 Cleaned = 2 Blocked = 3 class Solution: def __init__(self): self.graph = defaultdict(set) self.row = 0 self.col = 0 self.direction = Direction.Up self.robot: 'Optional[Robot]' = None self.statuses = defaultdict(lambda: Status.Unknown) self.unreachable = set([]) def add_surroundings(self): current_position = (self.row, self.col) if current_position not in self.statuses: self.statuses[current_position] = Status.Unknown for direction in Direction: neighbor = (current_position[0] + direction.value[0], current_position[1] + direction.value[1]) if neighbor not in self.statuses: self.statuses[neighbor] = Status.Unknown elif self.statuses[neighbor] == Status.Blocked: continue self.graph[current_position].add(neighbor) self.graph[neighbor].add(current_position) def clean_cell(self): self.robot.clean() self.statuses[(self.row, self.col)] = Status.Cleaned def go(self, direction: Direction): self.orient(direction) has_moved = self.robot.move() row, col = self.row + direction.value[0], self.col + direction.value[1] if has_moved: self.row, self.col = row, col self.statuses[(self.row, self.col)] = Status.Visited return has_moved, (row, col) def orient(self, direction: Direction): if direction == self.direction: return num_left_rotations = self.direction.num_left_rotations(direction) num_right_rotations = self.direction.num_right_rotations(direction) if num_left_rotations < num_right_rotations: for _ in range(num_left_rotations): self.robot.turnLeft() else: for _ in range(num_right_rotations): self.robot.turnRight() self.direction = direction def find_path_to_closest_unknown(self, src): queue = deque([src]) visited = {src} edge_to = {} dst = None while queue: vertex = queue.popleft() if self.statuses[vertex] == Status.Unknown: dst = vertex break # we sort the neighbors by the visited status, we need them first for neighbor in sorted(self.graph[vertex], key=lambda x: (self.statuses[x], x)): if neighbor in visited: continue if self.statuses[neighbor] == Status.Blocked: continue edge_to[neighbor] = vertex visited.add(neighbor) queue.append(neighbor) if dst is None: return None path = [] current = dst while current != src: path.append(current) current = edge_to[current] path.append(src) return list(reversed(path)) @staticmethod def translate_path_to_directions(path: List[Tuple[int, int]]) -> List[Direction]: if len(path) <= 1: yield None return for prev, nxt in prev_next(path): if prev == nxt: yield None continue diff = (nxt[0] - prev[0], nxt[1] - prev[1]) yield Direction(diff) def remove_blocked(self, vertex: Tuple[int, int]): del self.graph[vertex] self.statuses[vertex] = Status.Blocked def cleanRoom(self, robot: 'Robot'): self.robot = robot while path := self.find_path_to_closest_unknown((self.row, self.col)): directions = self.translate_path_to_directions(path) # print(f'Position: ({self.row}, {self.col}), path: {path}, directions: {directions}') for direction in directions: if self.statuses[(self.row, self.col)] != Status.Cleaned: self.clean_cell() if direction is not None: has_moved, next_coord = self.go(direction) if not has_moved: self.remove_blocked(next_coord) break self.add_surroundings() def prev_next(t): cur, nxt = tee(t) next(nxt) return zip(cur, nxt) Robot API implementation for testing purposes with render decorator def render(method): cleaned = ' ' dirty = '·' wall = '█' import os from time import sleep def wrapper(*args, **kwargs): operation = method.__name__ self = args[0] def render_top_line(): print(' ', end='') for r in range(self.num_cols): print('▁', end='') print() def render_bottom_line(): print(' ', end='') for r in range(self.num_cols): print('▔', end='') print() def get_direction(): match self.direction: case Direction.Up: return '▲' case Direction.Right: return '▶' case Direction.Down: return '▼' case Direction.Left: return '◀' def render_matrix(): for row in range(self.num_rows): print('▕', end='') for col in range(self.num_cols): element = dirty if self.cleaned_matrix[row][col]: element = cleaned if self.room[row][col] == 0: element = wall if col == self.col and row == self.row: element = get_direction() print(element, end='') print('▏', end='\n') def render_num_operations(): print(f'{self.num_operations}'.ljust(4), f'{operation}'.ljust(20)) self.num_operations += 1 result = method(*args, **kwargs) os.system('clear') render_num_operations() render_top_line() render_matrix() render_bottom_line() print() sleep(0.1) return result return wrapper class Robot: def __init__(self, room: 'List[List[int]]', row: int, col: int) -> None: self.room = room self.row = row self.col = col self.direction = Direction.Up self.num_rows = len(room) self.num_cols = len(room[0]) self.num_operations = 0 self.cleaned_matrix = [ [True for _ in range(self.num_cols)] for _ in range(self.num_rows) ] for r in range(self.num_rows): for c in range(self.num_cols): if room[r][c] == 1: self.cleaned_matrix[r][c] = False @render def move(self) -> bool: dr, dc = self.direction.value row, col = self.row + dr, self.col + dc if row >= self.num_rows or row < 0 or col >= self.num_cols or col < 0: return False if self.room[row][col] == 0: return False self.row, self.col = row, col return True @render def turnLeft(self): self.direction = Direction((-self.direction.value[1], self.direction.value[0])) @render def turnRight(self): self.direction = Direction((self.direction.value[1], -self.direction.value[0])) @render def clean(self): self.cleaned_matrix[self.row][self.col] = True ----------------------------------------------------- # """ # This is the robot's control interface. # You should not implement it, or speculate about its implementation # """ #class Robot: # def move(self): # """ # Returns true if the cell in front is open and robot moves into the cell. # Returns false if the cell in front is blocked and robot stays in the current cell. # :rtype bool # """ # # def turnLeft(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def turnRight(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def clean(self): # """ # Clean the current cell. # :rtype void # """ class Solution: def cleanRoom(self, robot): """ :type robot: Robot :rtype: None """ loc = 0,0 v = set() direct = 0 # 0: up 1: right 2: down 3: left movement = [(-1,0),(0,1),(1,0),(0,-1)] def back(robot): robot.turnRight() robot.turnRight() robot.move() robot.turnRight() robot.turnRight() def helper(loc: tuple, v: Set[tuple], direct: int, robot): robot.clean() v.add(loc) for i in range(4): new_direct = (direct+i)%4 new_loc = loc[0]+movement[new_direct][0], loc[1]+movement[new_direct][1] if new_loc not in v and robot.move(): helper(new_loc, v, new_direct, robot) back(robot) else: v.add(new_loc) robot.turnRight() helper(loc, v, direct, robot) ---------------------------------------------------------------- class Solution: def cleanRoom(self, robot): """ :type robot: Robot :rtype: None """ def dfs(i, j, di, dj): visited.add((i,j)) robot.clean() for _ in range(4): x, y = i + di, j + dj if (x, y) not in visited: canMove = robot.move() if not canMove: visited.add((x, y)) else: dfs(x, y, di, dj) robot.turnRight() robot.turnRight() robot.move() robot.turnLeft() robot.turnLeft() di, dj = dj, -di robot.turnRight() visited = set() dfs(0, 0, 0, 1) -------------------------------------------------------------- Without the Robot API settings, it's a kind of regular DFS problem. So we can build our solution based on DFS. The tricky things are, how to we make our robot object search all four directions without missing, and get back to original place after our recursive call. We can't just input a coordinate (i, j) to our robot. We need to manually set the direction for it and move one step a time. An idea is search left side once first, and then search right side three times. In such way, after a DFS, robot will search all four directions and heads to the opposite direction against where it came from. Then, we have it move extra one unit and it can go back to where it came from, like a recursive DFS return. And we also need to pass current direction down to next DFS so we can calculate the direction sequence in next DFS. It's like (d+k) % 4 for k in (3,0,1,2) where d is original direction and k is the turn. k iterates as (3,0,1,2) because we turn left first and then turn right 3 times. Another thing should be taken care is that after we DFS one path and get back to original place, we need to continue our DFS in current place. And since our direction has been reversed, we should turn left instead of right otherwise two direction would be missed. E.g. Robot reaches point X and heads N (so it comes from S). In current DFS, it turns left first and heads W to DFS. After that sub DFS, it gets back to X and heads E (not W). If it turns right, it will return to S and N and E will be missed. So it should turn left to visit N, then E and return to S. N W X E S It will be clearer if you make a draft. So each time we have done a sub DFS, we reset the "turn left once first and then turn right" pattern. def cleanRoom(robot): def dfs(robot, i, j, d, cleaned): robot.clean() cleaned.add((i,j)) left = True for nd in ((d+k) % 4 for k in (3,0,1,2)): robot.turnLeft() if left else robot.turnRight() di, dj = ((-1,0),(0,1),(1,0),(0,-1))[nd] if (i+di, j+dj) not in cleaned and robot.move(): dfs(robot, i+di, j+dj, nd, cleaned) robot.move() left = True else: left = False dfs(robot, 0, 0, 0, set())
''' You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to after using the swaps. ''' class Solution: def smallestStringWithSwaps(self, s, pairs): d = defaultdict(list) for a,b in pairs: d[a].append(b) d[b].append(a) # def dfs(x,A): if x in d: A.append(x) for y in d.pop(x): dfs(y,A) # s = list(s) while d: x = next(iter(d)) A = [] dfs(x,A) A = sorted(A) B = sorted([ s[i] for i in A ]) for i,b in enumerate(B): s[A[i]] = b return ''.join(s) ------------------------------------------------------------------------------------------------------------- class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: # Start of Union Find Data Structure p = list(range(len(s))) # parent # each element in the pairs == node # used to store each node's parent based on its index # eg. pairs = [[0,3],[1,2]], p = [0, 1, 1, 0] # element 3 in pairs == p index 3 == 0 (because parent node of 3 is 0) def find(x): if x != p[x]: p[x] = find(p[x]) return p[x] def union(x, y): px = find(x) py = find(y) if px != py: p[py] = px # End of Union Find Data Structure # Grouping for x, y in pairs: union(x, y) dic = defaultdict(list) for idx, el in enumerate(p): dic[find(el)].append(idx) # eg. pairs = [[0,3],[1,2]], dic = {0: [0, 3], 1: [1, 2]} # Sorting res = list(s) for key in dic.keys(): idx_list = dic[key] char_list = [s[i] for i in idx_list] char_list.sort() # eg. idx_list = [0, 3], char_list = [b, d] # for loop below, idx = [0, b], char = [3, d] for idx, char in zip(idx_list, char_list): res[idx] = char return "".join(res) ---------------------------------------------------------------------------------------------------------
''' You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an m x n character matrix, grid, of these different types of cells: '*' is your location. There is exactly one '*' cell. '#' is a food cell. There may be multiple food cells. 'O' is free space, and you can travel through these cells. 'X' is an obstacle, and you cannot travel through these cells. You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle. Return the length of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1. ''' Explanation Intuition: We need to find the shortest path from one point to the other. Pretty obvious hint of BFS. First, we need to find where to start. O(m*n) Starting BFS with the help of deque (i, j, cnt), explore 4 neighbors and increment cnt by 1 Mark visited point as X to avoid revisit If # is met, return cnt Time: O(m*n) Space: O(m*n) Implementation class Solution: def getFood(self, grid: List[List[str]]) -> int: m, n = len(grid), len(grid[0]) q = collections.deque() for i in range(m): for j in range(n): if grid[i][j] == '*': q.append((i,j, 0)); break if q: break while q: x, y, cnt = q.popleft() if grid[x][y] == 'X': continue elif grid[x][y] == '#': return cnt grid[x][y] = 'X' for i, j in [(x + _x, y + _y) for _x, _y in [(-1, 0), (1, 0), (0, -1), (0, 1)]]: if 0 <= i < m and 0 <= j < n and grid[i][j] != 'X': q.append((i, j, cnt + 1)) return -1 ---------------------------------------------------------------------- class Solution: def getFood(self, grid: List[List[str]]) -> int: # Get parameters rows = len(grid) cols = len(grid[0]) # Find the start cell for row in range(rows): for col in range(cols): if grid[row][col] == '*': start_row = row start_col = col # Initialization for Breadth First Search state = (start_row, start_col) steps = 0 queue = deque([(state, steps)]) visited = set(state) # Start BFS traverse while queue: # Get the current state and steps (curr_row, curr_col), steps = queue.popleft() # If it found a pizza, return the number of steps so far. # This steps is guaranteed to be the minimum steps because we use BFS if grid[curr_row][curr_col] == '#': return steps # We haven’t found a pizza yet, so go to another cell to find it for next_row, next_col in [ (curr_row + 1, curr_col), (curr_row - 1, curr_col), (curr_row, curr_col + 1), (curr_row, curr_col - 1) ]: # We can go if the next cell is in the grid, a free space, not visited yet, and either a free space or pizza place if 0 <= next_row < rows \ and 0 <= next_col < cols \ and grid[next_row][next_col] in ['O', '#'] \ and (next_row, next_col) not in visited: next_state = (next_row, next_col) # Append the next_state to queue and visit to allow BFS to happen queue.append((next_state, steps + 1)) visited.add(next_state) # Otherwise, it wasn’t able to find a pizza, meaning no parth to find the pizza so return -1 return -1 ------------------------------------------------------------------------------------- from collections import deque def getCurrentPosition(grid, locationMarker='*'): """ Return the row and col coordinates of my location """ for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == locationMarker: return (row, col) return -1 def getGridMarker(location, grid): """Return marker in grid at given location""" return grid[location[0]][location[1]] def findValidLocations(location, grid): """ Return all valid locations next to the provided location """ r, c = location allDirections = [(r+1, c), (r-1, c), (r, c+1), (r, c-1)] return [(i, j) for i, j in allDirections if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and getGridMarker((i,j), grid) in ('O', '#')] class Solution: def getFood(self, grid: List[List[str]]) -> int: myLocation = getCurrentPosition(grid) grid[myLocation[0]][myLocation[1]] = -1 # Mark as visted # Implement a BFS to find food queue = deque([(myLocation, 1)]) # (location, currentSteps) while queue: location, steps = queue.pop() for adjLocation in findValidLocations(location, grid): gridMarker = getGridMarker(adjLocation, grid) if gridMarker == "#": return steps grid[adjLocation[0]][adjLocation[1]] = -1 # Mark as visted queue.appendleft((adjLocation, steps + 1)) return -1 ---------------------------------------------------------------------------------------- Use BFS to find the shortest path to a food from the start position. Store the number of steps it takes to get to the destination in the queue. Time complexity: O(M * N) Space complexity: O(M * N) class Solution: def getFood(self, grid: List[List[str]]) -> int: m, n = len(grid), len(grid[0]) def getStartPos(): for i in range(m): for j in range(n): if grid[i][j] == "*": return (i, j) startX, startY = getStartPos() dirs = [(1,0),(-1,0),(0,1),(0,-1)] visited = [[False for c in range(n)] for r in range(m)] visited[startX][startY] = True q = collections.deque([(0, startX, startY)]) while q: steps, x, y = q.popleft() if grid[x][y] == "#": return steps for dX, dY in dirs: nX, nY = x + dX, y + dY if m > nX >= 0 <= nY < n and grid[nX][nY] != "X" and not visited[nX][nY]: visited[nX][nY] = True q.append((steps+1, nX, nY)) return -1 -------------------------------------------------------------------------------------- class Solution: def getFood(self, grid: List[List[str]]) -> int: directions = [(-1,0), (0,-1), (1,0),(0,1)] m = len(grid) n = len(grid[0]) def bfs(i,j): queue = deque([(i,j, 0)]) while queue: currX, currY, step = queue.popleft() for x, y in directions: nX = currX + x nY = currY + y if 0<=nX<m and 0<=nY<n and grid[nX][nY] != 'X': if grid[nX][nY] == '#': return step+1 # Mark the cell as visited grid[nX][nY] = 'X' queue.append((nX, nY, step+1)) return - 1 for i in range(m): for j in range(n): if grid[i][j] == '*': return bfs(i,j) return -1
''' You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item. The value of each item in items is unique. Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei. Note: ret should be returned in ascending order by value. ''' #my own solution class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: ret = list() if len(items1) >= len(items2): items1, items2 = items2, items1 items1 = dict(items1) items2 = dict(items2) for v, w in items1.items(): if v in items2: temp = [v, items2[v] + w] ret.append(temp) else: ret.append([v, w]) ret = dict(ret) for v, w in items2.items(): print(v, w) if v not in items1 and v not in ret: ret[v] = w ret = list([v, w] for v, w in ret.items()) ret = sorted(ret, key=lambda x: x[0]) return ret ------------------------------------------------------------------------------ class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: hashset = {} for i in range(len(items1)): if items1[i][0] in hashset: hashset[items1[i][0]] += items1[i][1] else: hashset[items1[i][0]] = items1[i][1] for i in range(len(items2)): if items2[i][0] in hashset: hashset[items2[i][0]] += items2[i][1] else: hashset[items2[i][0]] = items2[i][1] ans = [] for i in sorted(hashset): ans.append([i, hashset[i]]) return ans
''' Given an array of integers arr, sort the array by performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 1 <= k <= arr.length. Reverse the sub-array arr[0...k-1] (0-indexed). For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3. Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct. ''' class Solution: def pancakeSort(self, A: List[int]) -> List[int]: end=len(A) res=[] while end>1: maxInd=A.index(max(A[:end])) #step 1 get max if maxInd==end-1: #if Max already at the end then its in the right place decrement end and continue end-=1 continue #making the max element at Index 0, unless if it already was at index 0 if maxInd!=0: A[:maxInd+1]=reversed(A[:maxInd+1]) res.append(maxInd+1) #append flipping size which is maxInd+1 #Now max is at ind=0, flip whole array to make it at the "end" A[:end]=reversed(A[:end]) res.append(end) end-=1 #decrement end return res -------------------------------------------------------------------------------------------- class Solution: def pancakeSort(self, A: List[int]) -> List[int]: x = len(A) k = [] for indx in range(x): max_ = max(A[:x - indx]) max_indx = A.index(max_) + 1 A[:max_indx] = reversed(A[:max_indx]) k.append(max_indx) A[:x - indx] = reversed(A[:x - indx]) k.append(x - indx) return k
''' Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. ''' #my solution class Solution: def f(self, nums): return nums*2 #not my solution class Solution: def getConcatenation(self, nums: List[int]) -> List[int]: n=len(nums) r=[] for i in range(0,2*n): if i<n: r.append(nums[i]) else: r.append(nums[i-n]) return r
''' You are given a 0-indexed integer array candies, where candies[i] represents the flavor of the ith candy. Your mom wants you to share these candies with your little sister by giving her k consecutive candies, but you want to keep as many flavors of candies as possible. Return the maximum number of unique flavors of candy you can keep after sharing with your sister. Example 1: Input: candies = [1,2,2,3,4,3], k = 3 Output: 3 Explanation: Give the candies in the range [1, 3] (inclusive) with flavors [2,2,3]. You can eat candies with flavors [1,4,3]. There are 3 unique flavors, so return 3. Example 2: Input: candies = [2,2,2,2,3,3], k = 2 Output: 2 Explanation: Give the candies in the range [3, 4] (inclusive) with flavors [2,3]. You can eat candies with flavors [2,2,2,3]. There are 2 unique flavors, so return 2. Note that you can also share the candies with flavors [2,2] and eat the candies with flavors [2,2,3,3]. Example 3: Input: candies = [2,4,5], k = 0 Output: 3 Explanation: You do not have to give any candies. You can eat the candies with flavors [2,4,5]. There are 3 unique flavors, so return 3. ''' Move the k-size window from left and right and keep updating the counter ctr which counts the number of each unique candy. When the left end candy's count change from 0 to 1, increase the cnt by 1 (You get that candy back from your sister) When the right end candy' count change from 1 to 0, decrease the cnt by 1 (You share this candy to your sister) def shareCandies(candies: List[int], k: int) -> int: ctr = collections.Counter(candies[k:]) ans = cnt = sum(v != 0 for v in ctr.values()) for i, x in enumerate(candies[k:]): ctr[x] -= 1 cnt += (ctr[candies[i]] == 0) - (ctr[x] == 0) ctr[candies[i]] += 1 ans = max(ans, cnt) return ans -------------------------------------------------------------------------------------------------- class Solution: def shareCandies(self, candies: List[int], k: int) -> int: if k == 0: return len(set(candies)) d = Counter(candies) left = 0 ans = 0 for right, candie in enumerate(candies): d[candie] -= 1 if d[candie] == 0: del d[candie] if right - left + 1 == k: ans = max(ans, len(d)) leftCandie = candies[left] d[leftCandie] = d.get(leftCandie, 0) + 1 left += 1 return ans ----------------------------------------------------------------------------------------- Begin by counting how many of each flavor candy there is. We do this in the form of a hashmap. Next we initialize our starting window of size k, then interate over our candies using this logic: For every candy we add to our window, we remove a flavor from the general set of candies. For every candy we remove from our window, we add to our general set of candies. If we remove all of our candies for a flavor, remove the key from the map. If we ecounter a candy we have removed from our map, add it back in and reinitialize it to 1. The max # of keys in we've encountered at any given window is our answer. class Solution: def shareCandies(self, candies: List[int], k: int) -> int: candy_map = {} for candy in candies: if candy in candy_map: candy_map[candy] += 1 else: candy_map[candy] = 1 for i in range(k): candy_map[candies[i]] -= 1 if candy_map[candies[i]] == 0: del candy_map[candies[i]] unique_candies = len(candy_map) for i in range(1, len(candies)-k+1): if candies[i-1] not in candy_map: candy_map[candies[i-1]] = 1 else: candy_map[candies[i-1]] += 1 if candy_map[candies[i+k-1]] == 1: del candy_map[candies[i+k-1]] else: candy_map[candies[i+k-1]] -= 1 unique_candies = max(unique_candies, len(candy_map)) return unique_candies --------------------------------------------------------------------------------------------------- Explanation Count frequency of each flavor (number) Imagine a window of size k, slide the window to the right Decrease the frequency of the flavor when the flavor enter the window from the right side Increase the frequency of the flavor when the flavor leave the window from the left side Maintain a cur variable to count current maximum flavor left Return the maximum possible cur Implementation class Solution: def shareCandies(self, candies: List[int], k: int) -> int: c = collections.Counter(candies) if not k: return len(c) cur = len(c) for i in range(k): # Initialize window of length `k` c[candies[i]] -= 1 if not c[candies[i]]: cur -= 1 ans = cur for i in range(k, len(candies)): c[candies[i]] -= 1 # decrease frequency when flavor enter the window c[candies[i-k]] += 1 # increase frequency when flavor enter the window if c[candies[i-k]] == 1 and \ candies[i-k] != candies[i]: # adjust `cur` accordingly cur += 1 if not c[candies[i]]: # adjust `cur` accordingly cur -= 1 ans = max(cur, ans) return ans You can also get rid of cur by tracing the size of counter class Solution: def shareCandies(self, candies: List[int], k: int) -> int: c = collections.Counter(candies) if not k: return len(c) for i in range(k): c[candies[i]] -= 1 if not c[candies[i]]: del c[candies[i]] ans = len(c) for i in range(k, len(candies)): c[candies[i]] -= 1 c[candies[i-k]] += 1 if not c[candies[i]]: del c[candies[i]] ans = max(ans, len(c)) return ans
''' You are given a 0-indexed integer array nums of length n. The sum score of nums at an index i where 0 <= i < n is the maximum of: The sum of the first i + 1 elements of nums. The sum of the last n - i elements of nums. Return the maximum sum score of nums at any index. ''' class Solution: def maximumSumScore(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] n = nums n2 = n[::-1] suf = [0] * len(n) suf[0] = n2[0] for i in range(1, len(n2)): suf[i] = suf[i-1] + n2[i] suf = suf[::-1] # 10 6 3 5 pref = [0] * len(n) pref[0] = n[0] for i in range(1, len(n)): pref[i] = pref[i-1] + n[i] print('prefix sum') print(pref) print('suffix sum') print(suf) print('-----------------------------') print('-----------------------------') print('-----------------------------') res = float('-inf') for i in range(len(pref)): print('comparing', pref[i], suf[i]) temp = max(pref[i], suf[i]) if temp > res: res = temp print('res', res) return res ------------------------------------------------------ class Solution: def maximumSumScore(self, nums: List[int]) -> int: ans = -sys.maxsize prefix = [0] for num in nums: prefix.append(prefix[-1] + num) s = prefix[-1] for i, num in enumerate(nums): cur = max(prefix[i+1], s-prefix[i+1]+num) ans = max(ans, cur) return ans ------------------- def maximumSumScore(self, nums: List[int]) -> int: l = 0 r = t = sum(nums) for n in nums: l += n t = max(t, l, r) r -= n return t
''' Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it. ''' from collections import defaultdict def getFolderNames(self, names: List[str]) -> List[str]: used, hashmap = set(), defaultdict(int) result = [] for name in names: k = hashmap[name] current = name while current in used: k += 1 current = '%s(%d)' % (name, k) # alternative to current = name+'('+str(k)+')' hashmap[name] = k result.append(current) used.add(current) return result ------------------------------------------------------------- class Solution: def getFolderNames(self, names: List[str]) -> List[str]: seen = {} arr = [] for i in range(len(names)): if names[i] not in seen: seen[names[i]] = 1 arr.append(names[i]) else: n = seen[names[i]] new_name = names[i] + "(" + str(n) + ")" while new_name in seen: n += 1 new_name = names[i] + "(" + str(n) + ")" arr.append(new_name) seen[names[i]] += 1 seen[new_name] = 1 return arr
''' There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c]. Return the minimum total cost for this robot to return home. ''' class Solution: def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: def getRange(left, right, array): if left > right: right, left = left, right return sum((array[i] for i in range(left,right+1))) totalRowCost = getRange(startPos[0], homePos[0], rowCosts) totalColCost = getRange(startPos[1], homePos[1], colCosts) #Don't pay for the position you start out on return totalRowCost + totalColCost - rowCosts[startPos[0]] - colCosts[startPos[1]]
''' Given two integers a and b, return any string s such that: s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters, The substring 'aaa' does not occur in s, and The substring 'bbb' does not occur in s. ''' class Solution: def strWithout3a3b(self, A: int, B: int) -> str: output = "" a = 0 # length of last sequence of 'a' b = 0 # length of last sequence of 'b' i = 0 size = A + B while i < size: if (a < 2 and A > B) or b==2: output += 'a' b = 0 a += 1 A -= 1 else: output += 'b' b += 1 a = 0 B -= 1 i += 1 return output
''' Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. ''' #my own solution: class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: evens = list(filter(lambda num: num %2 == 0, A)) odds = list(filter(lambda num: num %2 == 1, A)) return evens+ odds # 2 pointer solution import random, time def f(a): low = 0 high = len(a)-1 print(a) while low < high: print('-----------------------') print(a) print() time.sleep(2) while a[low] %2 == 0 and low < high: time.sleep(3) print('even number found %d' % a[low]) low+=1 print('found odd instead of even! %d' % a[low]) while a[high] %2 == 1 and low < high: time.sleep(3) print('odd number found %d' % a[high]) high-=1 print('found even instead of odd! %d' % a[high]) print('swapping %d %d'% (a[low], a[high])) a[low],a[high] = a[high], a[low] print() print(a) res = [] for i in range(10): num = random.randint(1, 400) if num not in res: res.append(num) f(res)
''' Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false. ''' class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: first = None def count(node): nonlocal first total = 0 if node: if node.val == x: first = node total += count(node.left) + count(node.right) + 1 return total s = count(root) # Get total number of nodes, and x node (first player's choice) l = count(first.left) # Number of nodes on left branch r = count(first.right) # Number of nodes on right branch p = s-l-r-1 # Number of nodes on parent branch (anything else other than node, left subtree of node or right subtree of node) return l+r < p or l+p < r or r+p < l
''' Given the root of a binary tree, return the number of uni-value subtrees. A uni-value subtree means all nodes of the subtree have the same value. ''' def countUnivalSubtrees(self, root): self.count = 0 self.checkUni(root) return self.count # bottom-up, first check the leaf nodes and count them, # then go up, if both children are "True" and root.val is # equal to both children's values if exist, then root node # is uniValue suntree node. def checkUni(self, root): if not root: return True l, r = self.checkUni(root.left), self.checkUni(root.right) if l and r and (not root.left or root.left.val == root.val) and \ (not root.right or root.right.val == root.val): self.count += 1 return True return False ---------------------------------------------------------- # this question is as simple as.... """ 1. How do you calculate the total unival subtrees? a. You add the ones on the left to the ones on the right and add the root if it is unival too. 2. How do you determine if a subtree is unival? 1. if recurse through all the nodes in the tree and arive at a null then we are at a leaf. Leafs are by default unival, so return true. 2. if we have a right subtree and it's root node value isnt the same as our current root value then it is not a unival subtree so return false 3. same as number 2 but for left subtree 4. if the curr node has both left and right that are unival subtrees and we know that the rootval matches the left and right child vals then we have a unival subtree. Now, just put 1 & 2 together by callig the respective functions recursively """ class Solution: def countUnivalSubtrees(self, root: TreeNode) -> int: if not root: return 0 # the total count will equal the total count of the left subtree and the total count of the right subtree total_count = self.countUnivalSubtrees(root.left) + self.countUnivalSubtrees(root.right) #but, if the left and right subtrees are also unival then we need to add the root if it is unival too! if self.isUniVal(root.left) and self.isUniVal(root.right): if self.isUniVal(root): total_count += 1 return total_count def isUniVal(self, root): # it is a leaf, so it is unival if not root: return True if root.right and root.right.val != root.val: return False if root.left and root.left.val != root.val: return False #order matters here, we also know that root.val must be equal to left and right because we just checked it above if self.isUniVal(root.left) and self.isUniVal(root.right): return True ------------------------------------------------------------------------ Each node is either a leaf or the root of a subtree. The set of values in a given subtree is the union of three sets: The set of values of its left subtree. The set of values of its right subtree The set consisting only of the subtree's root. Once we get the union of the three sets, we simply check that its length is equal to 1 in order to know if the subtree is a univalue or not. If this is the case, we increment the count. def countUnivalSubtrees(self, root: TreeNode) -> int: self.count = 0 def dfs(node, acc): if not node: return acc left = dfs(node.left, acc) right = dfs(node.right, acc) acc = left.union(right) acc.add(node.val) self.count += (len(acc) == 1) return acc dfs(root, set()) return self.count ---------------------------------------------------------------------------------- I don't like the accepted solution because it is using an instance variable to keep count. Although it is more readable, I believe a cleaner way is to not have shared state across instance and this is what I have done. def countUnivalSubtrees(self, root): """ :type root: TreeNode :rtype: int """ # at any point if you know two things: # 1) count of univalue subtrees from its left descendants and if its a univalue subtree # 2) count of univalue subtrees from its right descendants and if its a univalue subtree # Then you can easily calculate outcome of the current level # count to return will atleast be sum of 1) and 2) # Only two possible scenarios for the current level: # 1) Add +1 to count and return True if both left/(and)right subtrees are univalue and value of left,right and current level is the same i.e. it is a univalue subtreee # 2) keep count same and return False if the current level is not a univalue subtree # just handle some corner cases and we are done def count_subtree(root): """ return: count, boolean indicating if its a univalue subtree """ if not root: return 0, False if not root.left and not root.right: return 1, True left_count, left_is_univalue = count_subtree(root.left) right_count, right_is_univalue = count_subtree(root.right) if root.left and root.right: if left_is_univalue and right_is_univalue: if root.left.val == root.right.val == root.val: return left_count + right_count + 1, True elif root.left and left_is_univalue: if root.left.val == root.val: return left_count + right_count + 1, True elif root.right and right_is_univalue: if root.right.val == root.val: return left_count + right_count +1 , True return left_count + right_count, False count, is_uni = count_subtree(root) return count --------------------------------------------------------------------- The idea is that the following conditions result in the increment of the result counter: The node is a leaf (has no children) The node and it's children have the same value The node completes a tree recursively def countUnivalSubtrees(self, root: TreeNode) -> int: self.count = 0 def hasChildren(node): if node.left or node.right: return True return False def isUniValSubTree(node): if node is None: return True if not hasChildren(node): self.count += 1 return if node.left and node.right: if node.left.val == node.right.val and node.left.val == node.val: self.count += 1 elif node.left and not node.right: if node.left.val == node.val and not hasChildren(node.left): self.count += 1 elif node.right and not node.left: if node.right.val == node.val and not hasChildren(node.right): self.count += 1 isUniValSubTree(node.left) isUniValSubTree(node.right) isUniValSubTree(root) return self.count
''' You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal. Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise. Note: The frequency of a letter x is the number of times it occurs in the string. You must remove exactly one letter and cannot chose to do nothing. ''' class Solution: def equalFrequency(self,word: str) -> bool: freq = list(Counter(word).values()) if len(set(freq)) > 2: return False for i in range(len(freq)): freq[i] -= 1 len_ = len(set(freq)) if len_ == 1 or (len_ == 2 and freq[i] == 0): return True freq[i] += 1 return False ---------------------------------------------------------------- class Solution: def equalFrequency(self, word: str) -> bool: dic = Counter(word) count = Counter(dic.values()) l1 = count.most_common() ### here are some cases help you understand better ### ### like abccc abc ,aabbcc, aaa ### return (len(l1) == 2 and l1[-1][1] == 1 and abs(l1[0][0] - l1[1][0]) == 1)\ or (len(l1) == 1 and l1[0][0] == 1) or len(dic) == 1
''' You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1. Return an array containing the answers to the queries. ''' class Solution: def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: intervals.sort(key = lambda x: x[0]) query_results = {} heap = [] i = 0 for q in sorted(queries): query_results[q] = -1 # populate heap with (size, end) so we can get the smallest valid interval for the query while i < len(intervals) and q >= intervals[i][0]: start, end = intervals[i] heapq.heappush(heap, (1 + end - start, end)) i += 1 # clean up heap by popping invalid results. Any results not valid now will not be valid for # any future queries, since we are looping through the queries in ascending order. while heap and q > heap[0][1]: heapq.heappop(heap) # After cleanup, the front of the heap is guarnteed to be the smallest sized interval # that is valid for the given query. if heap: query_results[q] = heap[0][0] # we must return the query results in the same order we got them return [query_results[q] for q in queries] ----------------------------------------------------------------------------------------------------------------------------------- class Solution: def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: hashMap = {} intervals.sort() minHeap = [] i_l = len(intervals) i = 0 for q in sorted(queries): while i < i_l and intervals[i][0] <= q: start, end = intervals[i] heapq.heappush(minHeap, [(end-start+1), end]) i += 1 while minHeap and minHeap[0][1] < q: heapq.heappop(minHeap) hashMap[q] = minHeap[0][0] if minHeap else -1 return [hashMap[q] for q in queries] ------------------------------------------------------------------------------------------- class Solution: def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: ans = [-1] * len(queries) intervals.sort(key = lambda i: i[1] - i[0]) queries = sorted([q, i] for i, q in enumerate(queries)) for left, right in intervals: idx = bisect.bisect(queries, [left]) while idx < len(queries) and queries[idx][0] <= right: ans[queries.pop(idx)[1]] = right - left + 1 return ans --------------------------------------------------------------------------------------------------------- class Solution: def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: intervals.sort(key=lambda i:i[0]) result = {} heap = [] i = 0 for q in sorted(queries): # add the intervals into heap for the given query while i < len(intervals) and intervals[i][0] <= q: interval_start,interval_end = intervals[i] heapq.heappush(heap,(interval_end-interval_start+1,interval_end)) i+=1 # pop out the invalid intervals from the heap against which the given query will not overlap the interval while heap and heap[0][1] < q: heapq.heappop(heap) # after the while loop ends we will at all potential intervals that satisfy the query # take the min if heap in not null otherwise -1 min_val = heap[0][0] if heap else -1 result[q] = min_val return [result[q] for q in queries]
''' The profiler will execute your code by executing the command python main.py. This problem does not require any input data, we will run your code once to determine whether the printed result is a multiplication table. When printing, print the multiplication in the order of increasing Multiplier, Print the multiplication formula with the same multiplier on the same line, and print the multiplication in the order of increasing multiplicand on the same line, and separate the adjacent multiplicand by a space, but there can be no Spaces at the end of the line. ''' for i in range(1,10): for j in range(1,i+1): if j != i : print("%d*%d=%d" %(j,i, i*j) ,sep = ' ', end = ' ') else: print("%d*%d=%d" %(j,i, i*j) , end = '') print()
''' Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n). ''' class Solution: def minSwaps(self, grid: List[List[int]]) -> int: # find the number of tailing zero of each row zero, n = [], len(grid) for row in grid: tmp = 0 while row and row.pop() == 0: tmp += 1 zero.append(tmp) # similar to insertion sort res = 0 for i in range(n): # skip since satisfies if zero[i] >= n-i-1: continue # find the closest valid one for j in range(i+1, n): if zero[j] >= n-i-1: break # check if zero[j] is valid if zero[j] < n-i-1: return -1 # insert step, move [i:j] one index forward zero[i+1:j+1] = zero[i:j] # add number of moves res += j-i return res ------------------------------------------------------------------------------- class Solution: def minSwaps(self, grid: List[List[int]]) -> int: lenth=len(grid) zeros=[0]*lenth for i in range(lenth): row=grid[i] for j in range(lenth): if row[-j-1]==0: zeros[i]=j+1 else: break count=0 for i in range(lenth): print(zeros) if zeros[i]<lenth-1-i: did=0 for next in range(lenth-i-1): if zeros[i+next+1]>=lenth-1-i: did=1 k=i+next+1 while k - i >0: count+=1 zeros[k],zeros[k-1] =zeros[k-1],zeros[k] k-=1 break if did==0: return -1 return count ---------------------------------------------------------------------------------------------------------- class Solution: def minSwaps(self, grid) -> int: """ This program computes the minimum number of swaps of adjacent rows that will create a valid grid. A grid is valid when all cells above the main diagonal are 0. :param grid: binary square matrix (0's and 1's) :type grid: list[list[int]] :return: minimum number of swaps needed to create valid grid (all cells above the diagonal are 0) :rtype: int """ """ Initialize: - length of grid (length) - number of swaps (swaps) is the eventual answer - number of zeros (zeros) we are looking for in the current row above the diagonal - first index above the diagonal (start) in the current row """ length = len(grid) swaps = 0 zeros = length - 1 start = 1 """ Determine minimum number of swaps needed to create valid grid. - In order for it to be possible to create a valid grid where the length of each row is length, there must exist a row that ends with length - 1 zeros, a row that ends with length - 2 zeros, and so on down to one zero. - In the first pass through the while loop, search for the first row that ends with length - 1 zeros. Count the number of swaps needed to move the row to the top row of the grid. Remove the row from the current location. Since we do not examine this row again, there is no need to insert it at the top of the grid. - Repeat for the next pass, but decrement the number of zeros. - Continue until the number of zeros is 1 or no row is found that meets the qualification for a valid matrix. - If it is possible to create a valid matrix, return the total number of swaps. Otherwise, return -1. """ while zeros > 0: swapped = False for k in range(length): if sum(grid[k][start:]) == 0: swaps += k grid.remove(grid[k]) swapped = True zeros -= 1 start += 1 break if not swapped: return -1 else: length -= 1 return swaps
''' You are given a list of integers rooms and an integer target. Return the first integer in rooms that's target or larger. If there is no solution, return -1. ''' class Solution: def solve(self, rooms, target): for i in range(len(rooms)): if rooms[i] >=target: return rooms[i] return -1 #another class Solution: def solve(self, rooms, target): return next((x for x in rooms if x >= target), -1)
''' You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend. ''' class Solution: def maxEvents(self, events: List[List[int]]) -> int: events.sort() total_days = max(end for start, end in events) day = 0 event_id = 0 num_events_attended = 0 min_heap = [] for day in range(1, total_days+1): # Add all the events that start today while event_id < len(events) and events[event_id][0] == day: heappush(min_heap, events[event_id][1]) event_id += 1 # Remove all the events whose end date was before today while min_heap and min_heap[0] < day: heappop(min_heap) # if any event that can be attended today, let's attend it if min_heap: heappop(min_heap) num_events_attended += 1 return num_events_attended
''' You are given an m x n 0-indexed 2D array of positive integers heights where heights[i][j] is the height of the person standing at position (i, j). A person standing at position (row1, col1) can see a person standing at position (row2, col2) if: The person at (row2, col2) is to the right or below the person at (row1, col1). More formally, this means that either row1 == row2 and col1 < col2 or row1 < row2 and col1 == col2. Everyone in between them is shorter than both of them. Return an m x n 2D array of integers answer where answer[i][j] is the number of people that the person at position (i, j) can see. ''' Explanation Below is a Python 3 implementation of hint section in the problem description Two things need to be aware in Python implementation Python built-in bisect library only works with ascendingly-ordered sequence, thus we will need a deque to make sure the sequence behaves like a mono-stack while maintaining increasing order When doing binary search, there are two cases need to be considered num = 3, s = [1], in this case, binary search will give us idx = 1 num = 3, s = [1,4], in this case, binary search will give us idx = 1, but since 4 is the first number larger than 3, it should be considered as visiable too. In conclusion, we will need to plus 1 if idx < len(s) else 0 Time: O(mnlog(mn)) = O(mnlog(n) + mnlog(m)) For more intuition, please read hint section in the problem description Implementation class Solution: def seePeople(self, heights: List[List[int]]) -> List[List[int]]: m, n = len(heights), len(heights[0]) ans = [[0] * n for _ in range(m)] s = collections.deque() # a deque behave like mono-stack for i in range(m): # look right for j in range(n-1, -1, -1): num = heights[i][j] idx = bisect.bisect_left(s, num) # binary search on an increasing order sequence ans[i][j] += idx + (idx < len(s)) # if `idx` is not out of bound, meaning the next element in `s` is the first one large than `num`, we can count it too while s and s[0] <= num: # keep a mono-descreasing stack s.popleft() s.appendleft(num) s.clear() for j in range(n): # look below for i in range(m-1, -1, -1): num = heights[i][j] idx = bisect.bisect_left(s, num) ans[i][j] += idx + (idx < len(s)) while s and s[0] <= num: s.popleft() s.appendleft(num) s.clear() return ans -------------------------------------------------------------------------------------------------------------------------------- class Solution: def seePeople(self, heights: List[List[int]]) -> List[List[int]]: m, n = len(heights), len(heights[0]) ans = [[0] * n for _ in range(m)] for i in range(m): stack = [] for j in range(n): prev = -inf while stack and heights[i][stack[-1]] < heights[i][j]: if prev < heights[i][stack[-1]]: ans[i][stack[-1]] += 1 prev = heights[i][stack.pop()] if stack and prev < heights[i][stack[-1]]: ans[i][stack[-1]] += 1 stack.append(j) for j in range(n): stack = [] for i in range(m): prev = -inf while stack and heights[stack[-1]][j] < heights[i][j]: if prev < heights[stack[-1]][j]: ans[stack[-1]][j] += 1 prev = heights[stack.pop()][j] if stack and prev < heights[stack[-1]][j]: ans[stack[-1]][j] += 1 stack.append(i) return ans
''' Given an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target. Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi). Return the string "-1" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| for i from 1 to n, as a string with three places after the decimal. ''' def minimizeError(self, prices: List[str], target: int) -> str: float_prices = [float(price) for price in prices] # 1. Compute the min rounded sum: rounded_sum = 0 rounding_error = 0 for price in float_prices: rounded_price = floor(price) rounded_sum += rounded_price rounding_error += price - rounded_price if rounded_sum >= target: # STOP return '%.3f' % rounding_error if rounded_sum == target else '-1' elif rounded_sum + len(prices) < target: return '-1' # 2. Replace 1 floor by ceil at a time until we reach target: choose the price with the min rounding error float_prices.sort(key=lambda price: ceil(price) - price) # ... Sort prices by ceil error to get the min rounding error for price in float_prices: rounded_sum += ceil(price) - floor(price) # +1 or +0 rounding_error += (ceil(price) - price) - (price - floor(price)) # Replace the floor rounding by the ceil rounding if rounded_sum >= target: break return '%.3f' % rounding_error if rounded_sum == target else '-1'
''' Given a lowercase alphabet string s, return the index of the first recurring character in it. If there are no recurring characters, return -1. ''' class Solution: def solve(self, s): if len(s) <=1: return -1 d = dict() for i in range(len(s)): if s[i] not in d: d[s[i]] = [i,1] else: return i return -1 #another class Solution: def solve(self, s): a = set() n = min(len(s), 27) for i in range(n): if s[i] in a: return i else: a.add(s[i]) return -1
''' You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki]. The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki. Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions ''' def minimumMoney(self, transactions: List[List[int]]) -> int: goodTransactions = [txn for txn in transactions if txn[0] <= txn[1]] badTransactions = [txn for txn in transactions if txn[0] > txn[1]] badTransactions.sort(key=lambda x: x[1]) need = 0 cur_amount = 0 for cost,cashback in badTransactions: cur_amount += cost need = max(need,cur_amount) cur_amount -= cashback if goodTransactions: costliest_good_transaction = max(goodTransactions, key=lambda x: x[0]) cur_amount += costliest_good_transaction[0] need = max(need, cur_amount) return need ---------------------------------------------------------------------------------------- class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: ans = val = 0 for cost, cashback in transactions: ans += max(0, cost - cashback) val = max(val, min(cost, cashback)) return ans + val
''' You are given a 0-indexed integer array nums. A pair of indices i, j where 0 <= i < j < nums.length is called beautiful if the first digit of nums[i] and the last digit of nums[j] are coprime. Return the total number of beautiful pairs in nums. Two integers x and y are coprime if there is no integer greater than 1 that divides both of them. In other words, x and y are coprime if gcd(x, y) == 1, where gcd(x, y) is the greatest common divisor of x and y. ''' class Solution: def countBeautifulPairs(self, nums: List[int]) -> int: res = 0 n = len(nums) for i in range(n): for j in range(i+1,n): first = int(str(nums[i])[0]) last = int(str(nums[j])[-1]) if gcd(first,last) == 1: res+=1 return res ------------------------------------------------------------------------------------ def countBeautifulPairs(self, nums: List[int]) -> int: pairs = 0 for i, num in enumerate(nums): d = num % 10 for j in range(i): n = nums[j] while n >= 10: n //= 10 pairs += gcd(d, n) == 1 return pairs
''' You are playing a Flip Game with your friend. You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner. Return all possible states of the string currentState after one valid move. You may return the answer in any order. If there is no valid move, return an empty list []. ''' class Solution: def generatePossibleNextMoves(self, currentState: str) -> List[str]: s = list(currentState) moves = list() i = 0 while i < len(s)-1: if s[i] == s[i+1] == '+': s[i] = s[i+1] = '-' moves.append(''.join(s)) s[i] = s[i+1] = '+' i += 1 print(moves) return moves
''' Your code needs to read data n, m and n parameters from the standard input stream (console) in the form of A B C D. You need to calculate a matrix of n * m, the matrix element calculation formula is M[i][j]= \begin{cases} C[i]& \text{j = 0}\\ (A[i] * M[i][j - 1] + B[i]) \ \%\ D[i] & \text{j != 0} \end{cases}M[i][j]={ C[i] (A[i]∗M[i][j−1]+B[i]) % D[i] j = 0 j != 0 among them, M[i][j] is the element of i row and j column in the required matrix, A[i], B[i], C[i] and D[i] is the input parameter. After calculating the result, print the matrix to the standard output stream (console). ''' # write your code here # read data from console # output the answer to the console according to the requirements of the question n = int(input()) m = int(input()) t = list() for _ in range(n): q = list(input().split()) q = list(map(int, q)) t.append(q) M = [ [0 for i in range(m)] for j in range(n) ] for i in range(n): for j in range(m): if j == 0: M[i][j] = t[i][2] else: M[i][j] = (t[i][0] * M[i][j-1] + t[i][1])% t[i][3] #printing the matrix for r in M: print(*r)
''' You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: 0 <= i <= nums.length - 2, nums[i] == key and, nums[i + 1] == target. Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. ''' class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: d = dict() for i in range(len(nums)-1): if nums[i] == key: if nums[i+1] not in d: d[nums[i+1]] = 1 else: d[nums[i+1]] += 1 maxi = max(d.values()) for k, v in d.items(): if v == maxi: print(k) return k
''' There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi. You will start on the 1st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take. ''' class Solution: def scheduleCourse(self, courses: List[List[int]]) -> int: courses.sort(key=lambda x: x[1]) cur_time = 0 res = [] for duration,lastday in courses: heappush(res,-duration) cur_time += duration if cur_time > lastday: longest_duration_course_taken = -heappop(res) cur_time -= longest_duration_course_taken return len(res) -----------------------------------------------------------------------------------------------------
''' Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits. Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0". ''' class Solution: def largestNumber(self, cost: List[int], target: int) -> str: @cache def fn(x): """Return max integer given target x.""" if x == 0: return 0 if x < 0: return -inf return max(fn(x - c) * 10 + i + 1 for i, c in enumerate(cost)) return str(max(0, fn(target)))
''' There is a special keyboard with all keys in a single row. Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|. You want to type a string word. Write a function to calculate how much time it takes to type it with one finger. ''' class Solution: def calculateTime(self, keyboard: str, word: str) -> int: r = [i for i in range(0, 26)] abc = dict(zip(keyboard, r)) total = 0 prev = 0 for ch in word: total += abs( abc[ch] - prev ) prev = abc[ch] print(total) return total
''' На вход подается строка str. Необходимо написать функцию magic_dict, которая будет составлять словарь, в котором ключами будут уникальные символы из str, а значениями - количество вхождений этих символов в строку str. При этом расположены элементы словаря должны быть в порядке лексикографического возрастания ключей. ''' from collections import Counter class Answer: def magic_dict(self, str): res = Counter(str) res = [[k, v] for k, v in res.items()] res.sort(key=lambda x: x[0]) res = dict(res) return res
''' Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. ''' class Solution: def search(self, nums: List[int], target: int) -> int: low = 0 high = len(nums)-1 while low <=high: mid = (low + high)//2 if target == nums[mid]: return mid elif target > nums[mid]: low = mid+1 else: high = mid-1 return -1
''' Given an array of strings words, return true if it forms a valid word square. A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns). ''' class Solution: def validWordSquare(self, words: List[str]) -> bool: # Iterate each row to check the valid square for i, r in enumerate(words): c = ''.join([r[i] for r in words if i < len(r)]) if len(c) != len(r) or c != r: return False return True #another class Solution: def validWordSquare(self, words: List[str]) -> bool: for index, word in enumerate(words): # Check if kth row word is the same as kth column word if not self.match(index, word, words): return False return True def match(self, index, word, words): # Get all the letters at specified index and make into a new word new_word = "" for cur_word in words: # Break immediately if we have Index error as not all word length will be the same try: new_word += cur_word[i] except IndexError: break # check if created word matches the original word return new_word == word
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. ''' #gives TLE error import math def f(nums): local_sum = 0 global_sum = float('-inf') print(nums) res = [] for r in range(len(nums)): print('-------------------------------------') before = 0 #print(nums[r:i]) for i in range(r,len(nums)): #print('-------------------------------------------') print(nums[r:i]) local_sum = nums[i] + before #print('local sum: %d = nums[i]: %d + %d' %( local_sum, nums[i], before)) before = local_sum if local_sum > global_sum: global_sum = local_sum print('global sum %d ' % global_sum) res.append(global_sum) a = [-2,1,-3,4,-1,2,1,-5,4] f(a) #optimal solution ''' observation is that negative numbers dont add anything & since we need a contigous array, we have to reset the current sum! ''' class Solution: def maxSubArray(self, nums: List[int]) -> int: max_sum = nums[0] cur_sum = max_sum for i in range(1, len(nums)): cur_sum = max( nums[i]+ cur_sum, nums[i]) max_sum = max(cur_sum, max_sum) return max_sum #slightly different class Solution: def maxSubArray(self, nums: List[int]) -> int: max_sum = nums[0] cur_sum = max_sum for i in range(1, len(nums)): if nums[i] + cur_sum >= nums[i]: cur_sum = nums[i] + cur_sum else: cur_sum = nums[i] max_sum = max(cur_sum, max_sum) return max_sum
''' A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order. ''' from collections import defaultdict """ https://www.notion.so/paulonteri/Hashtables-Hashsets-220d9f0e409044c58ec6c2b0e7fe0ab5#cf22995975274881a28b544b0fce4716 """ class Solution(object): def invalidTransactions(self, transactions): """ - Record all transactions done at a particular time. Recording the person and the location. Example: `['alice,20,800,mtv','bob,50,1200,mtv','bob,20,100,beijing']` :\n ` { 20: {'alice': {'mtv'}, 'bob': {'beijing'}}, 50: {'bob': {'mtv'}} } ` \n `{time: {person: {location}, person2: {location1, location2}}, time: {person: {location}}}` - For each transaction, check if the amount is invalid - and add it to the invalid transactions if so. - For each transaction, go through invalid times (+-60), check if a transaction by the same person happened in a different city - and add it to the invalid transactions if so. """ invalid = [] # Record all transactions done at a particular time # including the person and the location. transaction_time = defaultdict(dict) for transaction in transactions: name, str_time, amount, city = transaction.split(",") time = int(str_time) if name not in transaction_time[time]: transaction_time[time][name] = {city, } else: transaction_time[time][name].add(city) for transaction in transactions: name, str_time, amount, city = transaction.split(",") time = int(str_time) # # check amount if int(amount) > 1000: invalid.append(transaction) continue # # check if person did transaction within 60 minutes in a different city for inv_time in range(time-60, time+61): if inv_time not in transaction_time: continue if name not in transaction_time[inv_time]: continue trans_by_name_at_time = transaction_time[inv_time][name] # check if transactions were done in a different city if city not in trans_by_name_at_time or len(trans_by_name_at_time) > 1: invalid.append(transaction) break return invalid -------------------------------------- from collections import defaultdict """ https://www.notion.so/paulonteri/Hashtables-Hashsets-220d9f0e409044c58ec6c2b0e7fe0ab5#cf22995975274881a28b544b0fce4716 """ class Solution(object): def invalidTransactions(self, transactions): invalid = [] tr_time = defaultdict(dict) for tr in transactions: tr = tr.split(',') name = (tr[0]) time = (int(tr[1])) amount = (int(tr[2])) city = (tr[3]) if name not in tr_time[time]: tr_time[time][name] = {city,} else: tr_time[time][name].add(city) for t in transactions: name, time , amount,city =t.split(',') time = int(time) if int(amount)>1000: invalid.append(t) continue for q in range(time-60, time+61): if q not in tr_time: continue if name not in tr_time[q]: continue t_by_time = tr_time[q][name] if city not in t_by_time or len(t_by_time)>1: invalid.append(t) break return invalid --------------------------------------------------------- class Solution(object): def invalidTransactions(self, transactions): """ :type transactions: List[str] :rtype: List[str] """ r = {} inv = [] for i in transactions: split = i.decode("utf-8").split(",") name = str(split[0]) time = int(split[1]) amount = int(split[2]) city = str(split[3]) if time not in r: r[time] = { name: [city] } else: if name not in r[time]: r[time][name]=[city] else: r[time][name].append(city) for i in transactions: split = i.decode("utf-8").split(",") name = str(split[0]) time = int(split[1]) amount = int(split[2]) city = str(split[3]) if amount > 1000: inv.append(i) continue for j in range(time-60, time+61): if j not in r: continue if name not in r[j]: continue if len(r[j][name]) > 1 or (r[j][name][0] != city): inv.append(i) break return inv
''' Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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).” ''' ----------------------------------------------------------------- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root == None or root == p or root == q: return root # Find p/q in left subtree l = self.lowestCommonAncestor(root.left, p, q) # Find p/q in right subtree r = self.lowestCommonAncestor(root.right, p, q) # If p and q found in left and right subtree of this node, then this node is LCA if l and r: return root # Else return the node which returned a node from it's subtree such that one of it's ancestor will be LCA return l if l else r ----------------------------------------------------------------------- def lowestCommonAncestor(self, root, p, q): stack = [root] parent = {root: None} while p not in parent or q not in parent: node = stack.pop() if node.left: parent[node.left] = node stack.append(node.left) if node.right: parent[node.right] = node stack.append(node.right) ancestors = set() while p: ancestors.add(p) p = parent[p] while q not in ancestors: q = parent[q] return q
''' You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap. ''' class Solution: def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int: # help function to count overlaps in A (shifted) and B: def check_overlap(side_x, down_x, A, B): overlap_right_down = 0 overlap_right_up = 0 overlap_left_down = 0 overlap_left_up = 0 n = len(A) for i in range(n): for j in range(n): if i+side_x < n and j+down_x < n: overlap_right_down += A[i+side_x][j+down_x] & B[i][j] if i-side_x >= 0 and j+down_x < n: overlap_left_down += A[i-side_x][j+down_x] & B[i][j] if i-side_x >= 0 and j-down_x >= 0: overlap_left_up += A[i-side_x][j-down_x] & B[i][j] if j-down_x >= 0 and i+side_x < n: overlap_right_up += A[i+side_x][j-down_x] & B[i][j] return max(overlap_right_down, overlap_left_down, overlap_right_up, overlap_left_up) # try all options: max_overlap = 0 for i in range(len(A)): for j in range(len(A)): max_overlap = max(max_overlap, check_overlap(i, j, A, B)) return max_overlap
''' A wonderful string is a string where at most one letter appears an odd number of times. For example, "ccjjc" and "abab" are wonderful, but "ab" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string. ''' class Solution: def wonderfulSubstrings(self, word: str) -> int: n = len(word) mask = 0 prefix = defaultdict(int) prefix[0] += 1 ans = 0 for w in word: mask ^= 1 << (ord(w) - ord('a')) # no difference ans += prefix[mask] for i in range(10): # only differed by one digit tmp = mask ^ (1 << i) ans += prefix[tmp] prefix[mask] += 1 return ans
''' You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length. Return the number of steps performed until nums becomes a non-decreasing array. ''' class Solution(object): def totalSteps(self, nums): """ :type nums: List[int] :rtype: int """ s, a, r = [], [0] * len(nums), 0 for i in range(len(nums) - 1, -1, -1): while s and nums[i] > nums[s[-1]]: a[i] = max(a[i] + 1, a[s.pop()]) s.append(i) r = max(r, a[i]) return r
#Given a singly linked list, group all odd nodes together followed by the even nodes. #Please note here we are talking about the node number and not the value in the nodes # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head h_odd = head h_even = head.next odd = h_odd even = h_even while even != None: if even.next != None: odd.next = even.next else: odd.next = h_even return h_odd odd = odd.next even.next = odd.next even = even.next odd.next = h_even return h_odd
''' You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer. The second greater integer of nums[i] is nums[j] such that: j > i nums[j] > nums[i] There exists exactly one index k such that nums[k] > nums[i] and i < k < j. If there is no such nums[j], the second greater integer is considered to be -1. For example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1. Return an integer array answer, where answer[i] is the second greater integer of nums[i]. ''' class Solution: def secondGreaterElement(self, nums: List[int]) -> List[int]: ans = [-1] * len(nums) s, ss = [], [] for i, x in enumerate(nums): while ss and nums[ss[-1]] < x: ans[ss.pop()] = x buff = [] while s and nums[s[-1]] < x: buff.append(s.pop()) while buff: ss.append(buff.pop()) s.append(i) return ans ---------------------------------------------------------------------------------- class Solution: def secondGreaterElement(self, nums: List[int]) -> List[int]: st1,st2=[],[] heapify(st2) ans=[-1 for i in range(len(nums))] for i in range(len(nums)): while st2 and nums[-st2[0]]<nums[i]: ans[-heappop(st2)]=nums[i] while st1 and nums[st1[-1]]<nums[i]: heappush(st2,-st1.pop()) st1.append(i) return ans
''' Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). ''' class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: n, m = len(nums1), len(nums2) dp = [-math.inf] * (m + 1) for i in range(1, n + 1): dp, old_dp = [-math.inf], dp for j in range(1, m + 1): dp += max( old_dp[j], # not select i dp[-1], # not select j old_dp[j - 1], # not select either max(old_dp[j - 1], 0) + nums1[i - 1] * nums2[j - 1], # select both ), return dp[-1] ------------------------------------------------------------------------------------------------------------- from functools import lru_cache class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: @lru_cache(None) def helper(i, j): if i == 0 or j == 0: return -math.inf return max(helper(i - 1, j - 1), helper(i, j - 1), helper(i - 1, j), max(helper(i - 1, j - 1), 0) + nums1[i - 1] * nums2[j - 1]) return helper(len(nums1), len(nums2))
''' Given a positive integer num, return the sum of its digits. Bonus: Can you do it without using strings? ''' class Solution: def solve(self, num): total = 0 while num: total += num%10 num = num//10 print(total) return total
''' Given a csv file path path, you are asked to read the contents of the csv file, then change 'name' in the first line to 'student_name', and then write the modified contents back to path. ''' import csv def get_write_csv(path:str): with open(path, 'r')as f: lines = f.readlines() lines[0] = lines[0].replace('name', 'student_name') with open(path, 'w') as f2: f2.writelines(lines) f2.close()
''' You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0. ''' class Solution: def tallestBillboard(self, rods: List[int]) -> int: dp = {0: 0} for x in rods: for k, v in dp.copy().items(): dp[k+x] = max(dp.get(k+x, 0), v) if k >= x: dp[k-x] = max(dp.get(k-x, 0), v+x) else: dp[x-k] = max(dp.get(x-k, 0), v+k) return dp[0]
''' Given a list of integer nums, return the earliest index i such that the sum of the numbers left of i is equal to the sum of numbers right of i. If there's no solution, return -1. Sum of an empty list is defined to be 0. ''' class Solution: def solve(self, nums): r = sum(nums) l = 0 for i,x in enumerate(nums): r -= x if r == l: return i l += x return -1 --------------------------------------- #wrong solution def solve(nums): pref = [] pref.append(nums[0]) for i in range(1, len(nums)): pref.append(nums[i] + pref[i-1]) print('array') print(nums) print() print('pref is') pref.insert(0, 0) print(pref) # suffix n = len(nums) suf = [0 for _ in range(n)] suf[n-1] = nums[n-1] for i in range(n-2, -1, -1): suf[i] = suf[i+1] + nums[i] print() suf.append(0) print('suf') suf = sorted(suf, reverse=False) print(suf) for i in range(len(pref)): if pref[i] == suf[i]: return i return -1
''' A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. ''' class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: times = releaseTimes r = keysPressed res = [None] * len(times) res[0] = (times[0], r[0]) for i in range(1,len(times)): res[i] = ( times[i] - times[i-1] , r[i]) maxi = max(item[0] for item in res) #print(maxi) temp = list() for item in res: if item[0] == maxi: temp.append(item[1]) temp.sort() print( temp[-1]) return temp[-1]
''' You are given two integers n and maxValue, which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i] is a value from 1 to maxValue, for 0 <= i < n. Every arr[i] is divisible by arr[i - 1], for 0 < i < n. Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7. ''' class Solution: def idealArrays(self, n: int, mx: int) -> int: @lru_cache(None) def gen(k): return math.comb(n-1, k-1) q = deque([[i, 1] for i in range(1, mx+1)]) res = 0 while q: cur, l = q.popleft() res += gen(l) nxt = cur * 2 if l == n or nxt > mx: continue while nxt <= mx: q.append([nxt, l+1]) nxt += cur return res % (10**9 + 7) ------------------------------------------------------------------------------------------------------------------------------------------ class Solution: def idealArrays(self, n: int, maxValue: int) -> int: MOD = 10 ** 9 + 7 ans = maxValue freq = {x: 1 for x in range(1, maxValue + 1)} for k in range(1, n): if not freq: break nxt = collections.defaultdict(int) for x in freq: for m in range(2, maxValue // x + 1): ans += math.comb(n - 1, k) * freq[x] nxt[m * x] += freq[x] freq = nxt ans %= MOD return ans
''' Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). ''' class Solution: def checkPossibility(self, nums: List[int]) -> bool: counter = 0 n = nums for i in range(1,len(n)): if n[i] < n[i-1]: if i == 1 or n[i-2] < n[i]: n[i-1] = n[i] counter+=1 else: n[i] = n[i-1] counter+=1 return counter <=1
''' This question is about implementing a basic elimination algorithm for Candy Crush. Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules: If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary. After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps. If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board. You need to perform the above rules until the board becomes stable, then return the stable board. ''' class Solution: def candyCrush(self, board: List[List[int]]) -> List[List[int]]: #start the while loop while True: # check for the candies to be crushed crush = set() for i in range(len(board)): for j in range(len(board[0])): if j>1 and board[i][j] and board[i][j] == board[i][j-1] == board[i][j-2]: crush |= {(i,j), (i,j-1), (i,j-2)} if i>1 and board[i][j] and board[i][j] == board[i-1][j] == board[i-2][j]: crush |= {(i,j), (i-1,j), (i-2,j)} # crush the candies. if not crush: break for i, j in crush: board[i][j] = 0 # drop the candies for col in range(len(board[0])): idx = len(board)-1 for row in range(len(board)-1, -1, -1): if board[row][col]>0: board[idx][col] = board[row][col] idx -= 1 for row in range(idx+1): board[row][col] = 0 return board ---------------------------------- class Solution: def __init__(self): self.m = 0 self.n = 0 self.candyToCrush = set() def getCandiesToCrush(self, x, y, board, val): """ Get indices of the candies that needs to be crushed """ # for non-zero values if val != 0: # check horizontally if x + 2 < self.m and board[x+1][y] == val and board[x+2][y] == val: self.candyToCrush.update([(x,y), (x+1,y), (x+2,y)]) # check vertically if y + 2 < self.n and board[x][y+1] == val and board[x][y+2] == val: self.candyToCrush.update([(x,y), (x,y+1), (x,y+2)]) def crushCandies(self, board): """ Crush the candies by replacing the candy id to 0 """ for i, j in self.candyToCrush: board[i][j] = 0 return board def applyGravity(self, board): """ Drop the candies """ for j in range(self.n): # initialize top, bottom top = bottom = self.m - 1 while top >= 0: if board[top][j] != 0: board[bottom][j], board[top][j] = board[top][j], board[bottom][j] bottom-=1 top-=1 return board def candyCrush(self, board: List[List[int]]) -> List[List[int]]: self.m = len(board) self.n = len(board[0]) # reset the hashset self.candyToCrush = set() for i in range(self.m): for j in range(self.n): self.getCandiesToCrush(i, j, board, board[i][j]) # stable state achieved if len(self.candyToCrush) == 0: return board # crush candies board = self.crushCandies(board) # apply gravity board = self.applyGravity(board) return self.candyCrush(board)
class Answer: def selection_sort(self, nums): def selectionSort(array, size): for ind in range(size): min_index = ind for j in range(ind + 1, size): # select the minimum element in every iteration if array[j] < array[min_index]: min_index = j # swapping the elements to sort the array (array[ind], array[min_index]) = (array[min_index], array[ind]) return array return selectionSort( nums, len(nums))
''' You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Add a positive integer to an element of a given index in the array nums2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length). Implement the FindSumPairs class: FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2. void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val. int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot. ''' class FindSumPairs: def __init__(self, nums1: List[int], nums2: List[int]): self.nums1Count = collections.Counter(nums1) self.nums2Count = collections.Counter(nums2) self.nums2 = nums2 def add(self, index: int, val: int) -> None: self.nums2Count[self.nums2[index]] -= 1 self.nums2[index] += val self.nums2Count[self.nums2[index]] += 1 def count(self, tot: int) -> int: res = 0 for num, count in self.nums1Count.items(): res += count * self.nums2Count[tot - num] return res
''' You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time. Remove a train car from anywhere in the sequence which takes 2 units of time. Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods. ''' def minimumTime(self, s): n = len(s) dp = [0] * n left = right = 0 for i, c in enumerate(s): left = min(left + (c == '1') * 2, i + 1) dp[i] = left for i in range(n - 1, -1 , -1): c = s[i] right = min(right + (c == '1') * 2, n - 1 - i + 1) if i: dp[i - 1] += right return min([n] + dp) ------------------------------------------------------------------------------------------------------------------------ class Solution: def minimumTime(self, s: str) -> int: ans = inf prefix = 0 for i, ch in enumerate(s): if ch == '1': prefix = min(2 + prefix, i+1) ans = min(ans, prefix + len(s)-1-i) return ans
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". ''' #my own solution class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: words = strs if len(words) == 1: return words[0] mini = min(words, key=len) words.remove(mini) good_prefix = '' for i in range(1, len(mini)+1): prefix_to_check = mini[:i] temp = list() curr_prefix = '' for word in words: word_prefix = word[:i] print(word_prefix) if word_prefix != prefix_to_check: break else: temp.append(word_prefix) curr_prefix = word_prefix print('list temporary') print('length of temp', len(temp), '\t', *temp) print() if len(temp) == len(words): good_prefix = curr_prefix print('actual prefix', good_prefix) return good_prefix #another better solution class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: l = list(zip(*strs)) ans = '' for i in l: temp = ''.join(i) s = set(temp) if len(s)!=1: return ans else: ans+= temp[0] return ans
''' There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: OrderedStream(int n) Constructs the stream to take n values. String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order. ''' class OrderedStream: def __init__(self, n: int): self.od = [None]*(n+1) self.counter = 1 self.len = n+1 def insert(self, idKey: int, value: str): self.od[idKey] = value if idKey != self.counter: return [] elif idKey == self.counter: temp = [] while self.len > self.counter and self.od[self.counter] is not None : temp.append(self.od[self.counter]) self.counter+=1 return temp
''' There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. ''' ''' The code below takes a very simple approach to this problem, yet it manages to achieve a Top 92% Speed rating. The algorithm is the following: We first create explicit watering ranges for each Tap, and sort them. This solves 99% of the problem :) By looking at the given Diagram, we note that the problem actually consists in watering all the middle points [0.5 , 1.5, ... , n-0.5 ]. Starting from x=0.5 we query all the Tap ranges starting before "x", and find the further reaching Tap. We pick this Tap as our anwer. If our chosen Tap is unable to water "x", we exit with an error (-1). Otherwise, we move to the point "+0.5" to the right from it. We repeat the previous steps until we reach "n-0.5". That's the code, I hope you guys find it helpful. I think I achieved a High Speed Rating because, after the sorting step, the code does very few O(n) operations. For n = 10000, the difference between O(n) and O(n log n) is very small. If the operations after the sorting step are simple, the difference can be easily compensated. ''' class Solution: def minTaps(self, n, ranges): # Shameless Range conversion for i,x in enumerate(ranges): ranges[i] = [i-x,i+x] # Sorting Step ranges.sort(reverse=True) # Reverse, so pop() behaves like popleft() # Main Loop x, res = 0.5, 0 # Try to water points in the middle while x<n: b = -1 while ranges and ranges[-1][0]<=x: # Idea: 1) Query/Pop all points Starting before "x" # 2) Pick the one reaching furthest # 3) After one fail, points start at x<a (leave for later) b = max(b,ranges.pop()[1]) if b<0 or b<x: # We didn't find anything, or b<x (we never watered "x" at all) return -1 x = b + 0.5 res += 1 return res
''' You are given an integer n representing the number of playing cards you have. A house of cards meets the following conditions: A house of cards consists of one or more rows of triangles and horizontal cards. Triangles are created by leaning two cards against each other. One card must be placed horizontally between all adjacent triangles in a row. Any triangle on a row higher than the first must be placed on a horizontal card from the previous row. Each triangle is placed in the leftmost available spot in the row. Return the number of distinct house of cards you can build using all n cards. Two houses of cards are considered distinct if there exists a row where the two houses contain a different number of cards. Example 1: Input: n = 16 Output: 2 Explanation: The two valid houses of cards are shown. The third house of cards in the diagram is not valid because the rightmost triangle on the top row is not placed on top of a horizontal card. Example 2: Input: n = 2 Output: 1 Explanation: The one valid house of cards is shown. Example 3: Input: n = 4 Output: 0 Explanation: The three houses of cards in the diagram are not valid. The first house of cards needs a horizontal card placed between the two triangles. The second house of cards uses 5 cards. The third house of cards uses 2 cards. ''' Each row takes 3*n-1 cards (n is number of traingles) Bottom up (number of traingles must be less than its adjacent down row) Base conditions 0 or 2 cards remaining, count as one valid way to build previous down row has only 2 triangles and left more than 2 cards, no way to build class Solution: def houseOfCards(self, n: int) -> int: @lru_cache(None) def dp(n, prev): if n <= 2: return int(n != 1) if prev < 2: return 0 ans = 0 for i in range(2, min(prev, (n+1)//3+1)): ans += dp(n - 3*i + 1, i) return ans return dp(n, 10**5) -------------------------------------------------------------------------------------------------- Approach #1 - O(N^3) DP, Pre-calculation n = 500 dp = [collections.Counter() for _ in range(n+1)] # dp[total cards][horizontal cards at top_level] = frequency for i in range(1, n+1): if (i-2) % 3 == 0: dp[i][(i-2)//3-1] += 1 for j in range(i//2+1, i): for floor, cnt in dp[j].items(): if (i - j - 2) % 3 == 0: tmp = (i - j - 2) // 3 dp[i][tmp-1] += cnt if floor >= tmp else 0 class Solution: def houseOfCards(self, n: int) -> int: return sum(dp[n].values()) Approach #2 - O(N^2) DP Below is a Python re-write of leafybillow's solution. O(N^2) solution, very nice. class Solution: def houseOfCards(self, n: int) -> int: t_max = (n+3)//3; dp = [0] * (n+1); dp[0]=1; for t in range(1, t_max+1): base = 3*t-1; for i in range(n, base-1, -1): dp[i] += dp[i-base] return dp[n] --------------------------------------------------------------------------------------------------- class Solution: def houseOfCards(self, n: int) -> int: ways = [Counter() for _ in range(n + 1)] for cards in range(1, n + 1): for triangles_in_top_row in range(1, (cards + 1) // 3 + 1): remaining = cards - 3 * triangles_in_top_row + 1 if remaining > 0: for last_row_triangles, last_row_ways in ways[remaining].items(): if last_row_triangles > triangles_in_top_row: ways[cards][triangles_in_top_row] += last_row_ways elif remaining == 0: ways[cards][triangles_in_top_row] = 1 return ways[n].total() Explanation: ways[i] is a Counter indicating the number of ways to use all of i cards when the top row has various number of triangles. For example, ways[2] = {1: 1} means there is one way to use 2 cards and the top row has just one triangle. Another example: ways[16] = {1: 1, 2: 1}.
''' Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n > 2. It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k. ''' def findMinFibonacciNumbers(self, k): res, a, b = 0, 1, 1 while b <= k: a, b = b, a + b while a > 0: if a <= k: k -= a res += 1 a, b = b - a, a return res ----------------------------------------------------------------------------------------- To find the decomposition into the sum of Fibonnaci numbers we will iteratively (recursively) take the greatest Fibonnaci number that is smaller than the current reamainder and return the 1 plus the decomposition of the new remainder. 1 corresponds to the new found Fibonnaci that, and the recursion will descend just until we compute the whole solution. Cheers. class Solution: def findMinFibonacciNumbers(self, k): n1 = 1 n2 = 1 while n2 < k: temp = n2 n1, n2 = n2, n1+n2 if n2==k: return 1 return self.findMinFibonacciNumbers(k-n1)+1 ---------------------------------------------------------------------------------------------------------- d=[0,1] i=1 while d[i]<=k: i+=1 d+=[d[i-1]+d[i-2]] s=0 ct=0 d.remove(d[-1]) for i in d[::-1]: s+=i if s>k: s=s-i else: ct+=1 if s==k: return ct -------------------------------------------------------------------------------------- class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib_sq = [1, 1] while fib_sq[-1] + fib_sq[-2] <= k: fib_sq.append(fib_sq[-1]+fib_sq[-2]) counter = 0 for i in range(len(fib_sq)-1, -1, -1): if fib_sq[i] <= k: counter += 1 k -= fib_sq[i] return counter
''' You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0. In one operation: choose an index i such that 0 <= i < nums.length, increase your score by nums[i], and replace nums[i] with ceil(nums[i] / 3). Return the maximum possible score you can attain after applying exactly k operations. The ceiling function ceil(val) is the least integer greater than or equal to val. ''' class Solution: def maxKelements(self, nums: List[int], k: int) -> int: nums = [-i for i in nums] heapify(nums) res = 0 for i in range(k): t = -heappop(nums) res += t heappush(nums, -ceil(t / 3)) return res ---------------------------------------------------------------------------------------- class Solution: def maxKelements(self, nums: List[int], k: int) -> int: score = 0 pq = [] for num in nums: heapq.heappush(pq, (-num, num)) while k > 0: max_element = heapq.heappop(pq)[1] score += max_element updated_value = max_element // 3 + (max_element % 3 != 0) heapq.heappush(pq, (-updated_value, updated_value)) k -= 1 return score
''' You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s of length n, where s[i] is the character assigned to node i. Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them. ''' class Solution: def longestPath(self, parent: List[int], s: str) -> int: children = collections.defaultdict(list) for i, p in enumerate(parent): children[p].append(i) max_length = 1 def dfs(idx): nonlocal max_length if idx not in children: return 1 first, second = 0, 0 for child in children[idx]: curr = dfs(child) if s[idx]!=s[child]: if curr > first: second = first first = curr elif curr > second: second = curr max_length = max(max_length, first+second+1) return first+1 dfs(0) return max_length --------------------------------------
''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ''' class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 l = 0 r = len(height)-1 leftMax, rightMax = height[l], height[r] res = 0 while l < r: if leftMax < rightMax: l+=1 leftMax = max(leftMax, height[l]) res += leftMax - height[l] else: r-=1 rightMax = max(rightMax, height[r]) res += rightMax - height[r] return res ---------------------------- #stack based class Solution: def trap(self, height: List[int]) -> int: n = len(height) ans = 0 stack = [] for i in range(n): l = len(stack) if l == 0 or height[i] < height[stack[l - 1]]: stack.append(i) else: while(l > 0 and height[stack[l - 1]] <= height[i]): ht = height[stack.pop()] l = l - 1 ans = ans + (0 if l == 0 else (min(height[i],height[stack[l - 1]]) - ht) * (i - stack[l - 1] - 1)) stack.append(i) return ans
''' Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. ''' class Solution: def maxVowels(self, s: str, k: int) -> int: vowels = ["a","e","i","o","u"] #start point of the window start = 0 #number of vowels in a window of k length window = 0 #answer maxCount = 0 #end pointer of the window of k length for end in range(len(s)): #current letter letter = s[end] #is it in vowel ? if letter in vowels: window += 1 #once the length of window is equals to k then we check for number of vowels #this will happen each iteration once we first get the window of length k if end - start + 1 == k: #setting the maxcount maxCount = max(maxCount,window) #first pointer value left = s[start] #if first pointer is a vowel #we sub from the running window of k length number of vowels as it will be missing for the next #iteration if left in vowels: window -= 1 #we shrink the window by one by movingh the start pointer to right start = start + 1 #if a window has the max number of possible vowels which is k #then we just quit as we have gotten the largest possible value if maxCount == k: return maxCount return maxCount ------------------------------------------------------------------------------------------------------------------------------- class Solution: def maxVowels(self, s: str, k: int) -> int: n = len(s) v = 0 for i in range(k): if s[i] in "aeiou": v += 1 res = v for i in range(n - k): if s[i] in "aeiou": v -= 1 if s[i + k] in "aeiou": v += 1 res = max(res, v) return res --------------------------------------------------------------------------------------------------- class Solution: def maxVowels(self, s: str, k: int) -> int: letterList = [i for i in s] maxCount = 0 vowels = ['a', 'e', 'i', 'o', 'u'] if k == 1 : for i in vowels : if i in letterList : return 1 else : for i in range(len(letterList)-k+1) : if i == 0 : toCheck = letterList[i:i+k] totalVowelCount = toCheck.count('a') + toCheck.count('e') + toCheck.count('i') + toCheck.count('o') + toCheck.count('u') else : if letterList[i-1] in vowels : totalVowelCount -= 1 if (letterList[i+k-1] in vowels) : totalVowelCount += 1 if totalVowelCount > maxCount : maxCount = totalVowelCount return maxCount
''' You are given a 0-indexed integer array nums and an integer k. Your task is to perform the following operation exactly k times in order to maximize your score: Select an element m from nums. Remove the selected element m from the array. Add a new element with a value of m + 1 to the array. Increase your score by m. Return the maximum score you can achieve after performing the operation exactly k times. ''' class Solution: def maximizeSum(self, nums: List[int], k: int) -> int: nums= [-n for n in nums] heapify(nums) ans = 0 for i in range(k): temp = -heapq.heappop(nums) ans+= temp temp +=1 heapq.heappush(nums,-temp) return ans ---------------------------------------------------------------------------------------------------------------------- class Solution: def maximizeSum(self, nums: List[int], k: int) -> int: max_num = max(nums) ans = 0 for _ in range(k): ans += max_num max_num += 1 return ans
''' You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation. Intution here is to find the first index of zero. All the ones on the left of first zero are already at most optimal position and need not be changed. Example - 11100101 Now using the first rule ( '10' -> '01' ) all the zeroes can be shifted to the right of binary. This gives us 11100011 Now, n zeroes can be converted to (n-1) ones and 1 zero using second rule ( '00' -> '10' ). This gives us 11111011 which is the max binary string after changes. ''' class Solution: def maximumBinaryString(self, binary: str) -> str: # Find the first zero first_zero = binary.find('0') # If there are no zeroes then no optimization is needed if(first_zero == -1): return binary # Counting number of zeros count_zeroes = binary.count('0', first_zero) return '1' * (first_zero) + '1' * (count_zeroes-1) + '0' + '1' * (len(binary) - first_zero - count_zeroes)
''' Implement a hash table with the following methods: HashTable() constructs a new instance of a hash table put(int key, int val) updates the hash table such that key maps to val get(int key) returns the value associated with key. If there is no such key, then return -1. remove(int key) removes both the key and the value associated with it in the hash table. This should be implemented without using built-in hash table. ''' class Node: def __init__(self, key=None, value=None): self.key = key self.value = value self.next = None class HashTable: def __init__(self): self.hashmap = [None for i in range(1001)] def find_index(self, key): return key % 1001 def find(self, key, node): prev = None cur = node while cur and cur.key != key: prev = cur cur = cur.next return prev def put(self, key, value): index = self.find_index(key) if self.hashmap[index] is None: self.hashmap[index] = Node() node = self.hashmap[index] node = self.find(key, node) if node.next: node.next.value = value else: node.next = Node(key, value) def get(self, key): index = self.find_index(key) if self.hashmap[index] is None: return -1 node = self.hashmap[index] node = self.find(key, node) if node.next: return node.next.value else: return -1 def remove(self, key): index = self.find_index(key) if self.hashmap[index] is None: return node = self.hashmap[index] node = self.find(key, node) if node.next: node.next = node.next.next else: return ---------------------------------------------------------------------------------------------------------- #my own rewriting class Node: def __init__(self, key= None, value=None): self.key = key self.value = value self.next = None class HashTable: def __init__(self): self.hashmap = [None for i in range(1001)] def find_index(self,key): return key % 1001 def find(self,key, node): #return prev prev = None cur = node while cur and cur.key != key: prev = cur cur = cur.next return prev def put(self, key,value): index = self.find_index(key) if self.hashmap[index] is None: self.hashmap[index] = Node() node = self.hashmap[index] #this first finds the node node = self.find(key,node)#this gives back prev of the node if node.next: #this code adds value to the prev node.next.value = value else: node.next = Node(key,value) def get(self,key): index = self.find_index(key) if self.hashmap[index] is None: return -1 else: node = self.hashmap[index] node = self.find(key,node) if node.next: return node.next.value else: return -1 #so for every operation - you always find the index of the key instead of directly looking via key! def remove(self,key): index = self.find_index(key) if self.hashmap[index] is None: return else: node = self.hashmap[index] node = self.find(key,node)#this gives back prev node if node.next: node.next = node.next.next else: return
''' A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. ''' First, by appending nums to nums, you can ignore the effect of split case. Then, you look at the window whose width is width. Here, width = the number of 1's in the original nums. This is because you have to gather all 1's in this window at the end of some swap operations. Therefore, the number of swap operation is the number of 0's in this window. The final answer should be the minimum value of this. class Solution: def minSwaps(self, nums: List[int]) -> int: width = sum(num == 1 for num in nums) #width of the window nums += nums res = width curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width] for i in range(width, len(nums)): curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists res = min(res, curr_zeros) #update if needed return res
''' Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. ''' def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: # count frequency of characters count = collections.Counter() # Check only for minSize for i in range(len(s) - minSize + 1): t = s[i : i+minSize] if len(set(t)) <= maxLetters: count[t] += 1 return max(count.values()) if count else 0 --------------------------------------------- class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: s1 = [] count ={} while minSize <= maxSize: for i in range(0,len(s)): if (i+ minSize) <=len(s) and len(set(s[i: i+ minSize])) <= maxLetters: s1.append(s[i: i+ minSize]) minSize += 1 for i in s1: count[i] = count[i] + 1 if i in count else 1 return max(count.values()) if count else 0 ----------------------------------------------------------- def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: d = defaultdict(int) for i in range(len(s)-minSize+1): if len(set(s[i:i+minSize]))<=maxLetters: d[s[i:i+minSize]] +=1 return max(d.values()) if d else 0
''' You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: Choose any piles[i] and remove floor(piles[i] / 2) stones from it. Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations. floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). ''' class Solution: def minStoneSum(self, piles: List[int], k: int) -> int: heap = [-p for p in piles] heapq.heapify(heap) for _ in range(k): cur = -heapq.heappop(heap) heapq.heappush(heap, -(cur-cur//2)) return -sum(heap) ------------------------------------------------------------------------ def minStoneSum(self, A, k): A = [-a for a in A] heapq.heapify(A) for i in xrange(k): heapq.heapreplace(A, A[0] / 2) return -sum(A) ----------------------------------------------------- import heapq class Solution: def minStoneSum(self, piles: List[int], k: int) -> int: """ To use Max Heap, we need to convert all values to -ve integers """ for i in range(len(piles)): piles[i]= -1 * piles[i] """ Creating heap of the given list """ heapq.heapify(piles) """ while k > 0, applying the provided operation to the maximum value """ while k: a = heapq.heappop(piles) a = a//2 heapq.heappush(piles, a) k -= 1 """ The elements in the list are updated, now the contain the minimum possible sum """ return abs(sum(piles))
''' You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0. You may assume that you have an infinite number of each kind of coin. The answer is guaranteed to fit into a signed 32-bit integer. ''' def change(self, amount, coins): """ :type amount: int :type coins: List[int] :rtype: int """ dp = [0] * (amount + 1) dp[0] = 1 for i in coins: for j in range(1, amount + 1): if j >= i: dp[j] += dp[j - i] return dp[amount] --------------------------------------------------- ''' Abstract model transform. Fill knapsack of wieght W with N items with each item is unlimited supply. <=> Fill knapsack of $amount with C coins with each coin is unlimied supply. Hint: Think of dynamic programming strategy with bottom-up update Make change with small coin to large coin. Update method count from small amount to large amount. State transfer function: DP[ 0 ] = 1 as initialization (i.e., $0 is reached by taking no coins. ). And update with formula DP[ current_amount ] = DP[ current_amount ] + DP[ current_amount- coin ] ''' class Solution: def change(self, amount: int, coins: List[int]) -> int: # base case: # amount 0's method count = 1 (by taking no coins) change_method_count = [1] + [ 0 for _ in range(amount)] # make change with current coin, from small coin to large coin for cur_coin in coins: # update change method count from small amount to large amount for small_amount in range(cur_coin, amount+1): # current small amount can make changed with current coin change_method_count[small_amount] += change_method_count[small_amount - cur_coin] return change_method_count[amount] ---------------------------------------------------------------------------------------------------------- class Solution: def change(self, amount: int, coins: List[int]) -> int: """ The logic is we find number of ways we can make change for each amount from 1 to amount. Because, let's say we know how many ways we can make change for amount = 2,3,4. Then for a coins array of 1,3 we can say that number of ways we can make change for 5 is equal to number of ways we can make change for (5-1=4) + (5-3=2). """ dp = [0] * (amount + 1) dp[0] = 1 # Why we are looping through coins first and then through amount for each coin is # If we loop through amount first and then coins for each amount, we might get # duplicate ways because of unorderness. Example: Using 1, 3. we can make 5 # by 1 + 1 + 3, 1 + 3 + 1, 3 + 1 + 1. But actually all these 3 possibilites # are same. This will be avoided if we loop through coins first. Since, we # will only consider each coin once for each amount for coin in coins: # Why we are starting loop from coin instead of 0 is, if i < coin, i - coin # will ge -ve. In normal words, if current amount is 2 and if coin is 5, we # anyway can't make an amount of 2 from coin 5. for i in range(coin, amount + 1): dp[i] += dp[i - coin] return dp[-1]
''' In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0]. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists. Example 1: Input: x = 2, y = 1 Output: 1 Explanation: [0, 0] → [2, 1] Example 2: Input: x = 5, y = 5 Output: 4 Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5] ''' All solutions below are based on symmetry, meaning (x, y), (-x, y), (x, -y), (-x, -y) will have the same results. Approach #1 - One-direction BFS with pruning Use pruning to remove unnecessary location -1 <= a+dx <= x+2 and -1 <= b+dy <= y+2: Time Complexity: O(|x|*|y|) class Solution: def minKnightMoves(self, x: int, y: int) -> int: q = collections.deque([(0, 0, 0)]) x, y, visited = abs(x), abs(y), set([(0,0)]) while q: a, b, step = q.popleft() if (a, b) == (x,y): return step for dx, dy in [(1,2),(2,1),(1,-2),(2,-1),(-1,2),(-2,1)]: # no need to have (-1, -2) and (-2, -1) since it only goes 1 direction if (a+dx, b+dy) not in visited and -1 <= a+dx <= x+2 and -1 <= b+dy <= y+2: visited.add((a+dx, b+dy)) q.append((a+dx, b+dy, step+1)) return -1 Approach #2 - Two-direction BFS with pruning Start BFS from both origin & target coordinates Use pruning to remove unnecessary location -1 <= a+dx <= x+2 and -1 <= b+dy <= y+2: Time Complexity: O(|x|*|y|), ideally half time costs of approach #1 class Solution: def minKnightMoves(self, x: int, y: int) -> int: x, y = abs(x), abs(y) qo = collections.deque([(0, 0, 0)]) qt = collections.deque([(x, y, 0)]) do, dt = {(0,0): 0}, {(x,y): 0} while True: ox, oy, ostep = qo.popleft() if (ox, oy) in dt: return ostep + dt[(ox, oy)] tx, ty, tstep = qt.popleft() if (tx, ty) in do: return tstep + do[(tx, ty)] for dx, dy in [(1,2),(2,1),(1,-2),(2,-1),(-1,2),(-2,1),(-1,-2),(-2,-1)]: if (ox+dx, oy+dy) not in do and -1 <= ox+dx <= x+2 and -1 <= oy+dy <= y+2: qo.append((ox+dx, oy+dy, ostep+1)) do[(ox+dx,oy+dy)] = ostep+1 if (tx+dx, ty+dy) not in dt and -1 <= tx+dx <= x+2 and -1 <= ty+dy <= y+2: qt.append((tx+dx, ty+dy, tstep+1)) dt[(tx+dx,ty+dy)] = tstep+1 return -1 Approach #3 - DFS + Math + Memoization Try to move from target to origin as fast as possible When reaching to certain point, handle the special situation and return the result Time Complexity: O(|x|*|y|) class Solution: def minKnightMoves(self, x: int, y: int) -> int: @lru_cache(None) def dp(x,y): if x + y == 0: return 0 elif x + y == 2: return 2 return min(dp(abs(x-1),abs(y-2)), dp(abs(x-2),abs(y-1))) + 1 return dp(abs(x),abs(y)) Approach #4 - Math Pretty much the same idea as previous With Math induction, you will find a pattern with division, which can replace previous DFS process Time Complexity: O(1) class Solution: def minKnightMoves(self, x: int, y: int) -> int: x, y = abs(x), abs(y) if (x < y): x, y = y, x if (x == 1 and y == 0): return 3 if (x == 2 and y == 2): return 4 delta = x - y if (y > delta): return delta - 2 * int((delta - y) // 3); else: return delta - 2 * int((delta - y) // 4); ------------------------------------------------------------------------------------- I don't believe we need to use any formulas in an actual interview. I had given the following solution for a mock and an actual interview and got through to next round. class Solution: def minKnightMoves(self, s: int, e: int) -> int: q = collections.deque() q.append([0,0,0]) visited = set() visited.add((0,0)) while q: x,y,steps = q.popleft() if x==s and y==e: return steps dirs = [(x-1,y-2),(x-2,y-1),(x-2,y+1),(x-1,y+2),(x+1,y-2),(x+2,y-1),(x+1,y+2),(x+2,y+1)] for i,j in dirs: if (i,j) not in visited: q.append([i,j,steps+1]) visited.add((i,j)) return -1 --------------------------------------------------------------------------------------- Naive BFS is trival, we need some optimizations. Since the board is symemtric, quadrant has no effect to the final answer(steps to the target). We can put the target to the first quadrant for convenice. x, y = abs(x), abs(y) Notice that for some points on the edge or close to the edge, like (1 ,1), we need some help for other quadrants to reach the point with minimum steps. So we relax the bound to (-2, inf) for both x, y. -2 is the max range a knight can reach within 1 step. class Solution: def minKnightMoves(self, x: int, y: int) -> int: if x == y == 0: return 0 dirs = [(-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)] q = collections.deque([(0, 0)]) step = 0 visited = set() x, y = abs(x), abs(y) while q: step += 1 qSize = len(q) for _ in range(qSize): nextX, nextY = q.popleft() for dx, dy in dirs: newX, newY = nextX + dx, nextY + dy if (newX, newY) == (x, y): return step if newX < -2 or newY < -2 or (newX, newY) in visited: continue visited.add((newX, newY)) q.append((newX, newY)) return step ---------------------------------------------------------------------------------------- def minKnightMoves(self, x: int, y: int) -> int: # let's do bfs # Because of the symmetry, we can just look into the first # quadrant and also push only positive coordinates to the queue # also look for x >= -5 and y >= -5 case. # x >= 0 and y >= 0 is sufficient to pass all the leetcode test case, # but code fails when x = 1 and y = 1 ( [0,0]->[-1,2]->[1,1] ) if x == 0 and y == 0: return 0 return self.bfs(abs(x), abs(y)) def bfs(self, x, y): moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)] q = [(0, 0, 0)] visited = set() visited.add((0, 0)) while len(q) > 0: i, j, dis = q.pop(0) for move in moves: a, b = i + move[0], j + move[1] if (a,b) not in visited and a >= -5 and b >= -5: if a == x and b == y: return dis + 1 q.append((a, b, dis+1)) visited.add((a, b)) -------------------------------------------------------------------------------------- class Solution: def minKnightMoves(self, x: int, y: int) -> int: ## RC ## ## APPROACH : BFS ## if x == 0 and y == 0: return 0 # must directions = [(1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1)] queue = collections.deque([(0, 0, 0)]) visited = set([(0,0)]) x, y = abs(x), abs(y) # as knight moves are symmetric we donot need to BFS in all four quadrants, moves to reach (-2,100) and (2, 100) and (-2,-100) and (2,-100) are all same. so we are moving only in first quadrant. while queue: i, j, d = queue.popleft() for di, dj in directions: if ((i + di, j + dj) not in visited) and ( d < 2 or (i + di >= 0 and j + dj >= 0)): # d < 2, for x,y = (1,1) ans will be 4 without this ans is 2 if i + di == x and j + dj == y: return d + 1 queue.append((i + di, j + dj, d + 1)) visited.add((i + di, j + dj)) ------------------------------------------------------------------------------- from collections import deque class Solution: def minKnightMoves(self, x: int, y: int) -> int: if x == 0 and y == 0: return 0 queue = deque([(0,0,0)]) directions = [[-2,1],[-2,-1],[-1,2],[-1,-2],[1,2],[1,-2],[2,1],[2,-1]] visited = set() visited.add((0,0)) while queue: cur_r,cur_c,move = queue.popleft() for d_r,d_c in directions: i_r,i_c = cur_r + d_r, cur_c + d_c if (i_r,i_c) not in visited: if i_r == x and i_c == y: return move + 1 queue.append((i_r,i_c,move+1)) visited.add((i_r,i_c))
''' You are given a 0-indexed array words containing n strings. Let's define a join operation join(x, y) between two strings x and y as concatenating them into xy. However, if the last character of x is equal to the first character of y, one of them is deleted. For example join("ab", "ba") = "aba" and join("ab", "cde") = "abcde". You are to perform n - 1 join operations. Let str0 = words[0]. Starting from i = 1 up to i = n - 1, for the ith operation, you can do one of the following: Make stri = join(stri - 1, words[i]) Make stri = join(words[i], stri - 1) Your task is to minimize the length of strn - 1. Return an integer denoting the minimum possible length of strn - 1. ''' class Solution: def minimizeConcatenatedLength(self, words: List[str]) -> int: @lru_cache(maxsize=None) def f(first,last,index): if len(words)-1<index: return 0 w=words[index] return max((w[-1]==first) + f(w[0],last,index+1), (last==w[0]) + f(first,w[-1],index+1)) return len(''.join(words)) - f(words[0][0],words[0][-1],1)
''' An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz". For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not. Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring. ''' --- At each position, it either belongs to previous continues substring or it is the beginning of a new substring. class Solution: def longestContinuousSubstring(self, s: str) -> int: cur = 1 ### We are currently at 0 position, so the length is 1. res = 1 ### At least the string should contain 1 letter. for i in range(1,len(s)): ### If the ith letter is continued from the previous letter, ### update the curLength and store the maximum length to res if ord(s[i])-ord(s[i-1])==1: cur = cur+1 res = max(cur,res) ### This is the start of a new substring with length 1. else: cur = 1 return res
''' You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules. ''' class TopVotedCandidate: def __init__(self, persons: List[int], times: List[int]): self.topVoted = [0] * len(times) countVotes = Counter() currentTop = persons[0] for i, (person, time) in enumerate(zip(persons, times)): countVotes[person] += 1 if countVotes[person] >= countVotes[currentTop]: currentTop = person self.topVoted[i] = (time, currentTop) def q(self, t: int) -> int: left, right = 0, len(self.topVoted) - 1 while left <= right: mid = (left + right) // 2 time, top = self.topVoted[mid] if time == t: return top if time < t: left = mid + 1 else: right = mid - 1 time, top = self.topVoted[right] return top ------------------------------------------------------------------------- class TopVotedCandidate: def __init__(self, persons: List[int], times: List[int]): self.leading =[] self.times = [] count = defaultdict(int) ma = 0 for i , p in enumerate(persons): count[p]+=1 if count[p]>= ma: ma= count[p] self.leading.append(p) self.times.append(times[i]) def search(self, ar , target): l,r = 0,len(ar)-1 while l<=r: mid = l+(r-l)//2 if ar[mid] == target: return mid elif ar[mid] > target: r = mid-1 else: l= mid+1 return l-1 def q(self, t: int) -> int: index = self.search(self.times, t) return self.leading[index]
''' There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). ''' class Solution: def numTeams(self, rating: List[int]) -> int: res = 0 for i in range(1, len(rating) - 1): less, greater = [0, 0], [0, 0] for j in range(i): if rating[j] < rating[i]: less[0] += 1 else: greater[0] += 1 for k in range(i+1, len(rating)): if rating[i] < rating[k]: less[1] += 1 else: greater[1] += 1 res += less[0] * less[1] + greater[0] * greater[1] return res -----------------------------------------------------------------------------------
''' Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1. ''' class Solution: def maximumDifference(self, nums: List[int]) -> int: maxi = -1 for i in range(len(nums)): for j in range(i+1, len(nums)): diff = nums[j] - nums[i] if diff > maxi and nums[i] < nums[j]: print('found %d' % diff) print('indices are %d %d' % (i, j)) print(nums[j], nums[i]) maxi = diff print('maxi diff is %d' % maxi) return maxi #another solution 1 pass class Solution: def maximumDifference(self, nums: List[int]) -> int: maxdiff = -1 min_num = nums[0] for i in range(len(nums)): maxdiff = max(maxdiff, nums[i] - min_num) min_num = min(nums[i], min_num) return maxdiff if maxdiff != 0 else -1
''' Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "". getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "". Note that each function must run in O(1) average time complexity. ''' class Node: def __init__(self, elements=[]): self.left = None self.right = None self.elements = set(elements) def addBetween(self, node1, node2): self.left = node1 self.right = node2 node1.right = self node2.left = self def deleteNode(self): left, right = self.left, self.right left.right = right right.left = left class AllOne: def __init__(self): self.keyToNum = {} self.numToNode = {} self.head, self.tail = Node(), Node() self.head.right = self.tail self.tail.left = self.head def inc(self, key: str) -> None: keyToNum = self.keyToNum numToNode = self.numToNode if key not in keyToNum: keyToNum[key] = 1 if 1 in numToNode: numToNode[1].elements.add(key) else: newNode = Node([key]) numToNode[1] = newNode newNode.addBetween(self.head, self.head.right) else: oldNum = keyToNum[key] oldNode = numToNode[oldNum] newNum = oldNum + 1 keyToNum[key] = newNum if newNum in numToNode: numToNode[newNum].elements.add(key) else: newNode = Node([key]) numToNode[newNum] = newNode newNode.addBetween(oldNode, oldNode.right) oldNode.elements.discard(key) if not oldNode.elements: oldNode.deleteNode() del numToNode[oldNum] def dec(self, key: str) -> None: keyToNum = self.keyToNum numToNode = self.numToNode if key not in keyToNum: return oldNum = keyToNum[key] oldNode = numToNode[oldNum] if oldNum == 1: del keyToNum[key] else: newNum = oldNum - 1 keyToNum[key] = newNum if newNum in numToNode: newNode = numToNode[newNum] newNode.elements.add(key) else: newNode = Node([key]) numToNode[newNum] = newNode oldLeft = oldNode.left newNode.addBetween(oldLeft, oldNode) oldNode.elements.discard(key) if not oldNode.elements: oldNode.deleteNode() del numToNode[oldNum] def getMaxKey(self) -> str: if self.tail.left == self.head: return '' else: for e in self.tail.left.elements: return e def getMinKey(self) -> str: if self.head.right == self.tail: return '' else: for e in self.head.right.elements: return e ----------------------------------------------------------------------------------------------------- class Block(object): def __init__(self, val=0): self.val = val self.keys = set() self.before = None self.after = None def remove(self): self.before.after = self.after self.after.before = self.before self.before, self.after = None, None def insert_after(self, new_block): old_after = self.after self.after = new_block new_block.before = self new_block.after = old_after old_after.before = new_block class AllOne(object): def __init__(self): self.begin = Block() # sentinel self.end = Block() # sentinel self.begin.after = self.end self.end.before = self.begin self.mapping = {} # key to block def inc(self, key): if not key in self.mapping: # find current block and remove key current_block = self.begin else: current_block = self.mapping[key] current_block.keys.remove(key) if current_block.val + 1 != current_block.after.val: # insert new block new_block = Block(current_block.val + 1) current_block.insert_after(new_block) else: new_block = current_block.after new_block.keys.add(key) # update new_block self.mapping[key] = new_block # ... and mapping of key to new_block if not current_block.keys and current_block.val != 0: # delete current block if not seninel current_block.remove() def dec(self, key): if not key in self.mapping: return current_block = self.mapping[key] del self.mapping[key] # could use self.mapping.pop(key) current_block.keys.remove(key) if current_block.val != 1: if current_block.val - 1 != current_block.before.val: # insert new block new_block = Block(current_block.val - 1) current_block.before.insert_after(new_block) else: new_block = current_block.before new_block.keys.add(key) self.mapping[key] = new_block if not current_block.keys: # delete current block current_block.remove() def getMaxKey(self): if self.end.before.val == 0: return "" key = self.end.before.keys.pop() # pop and add back to get arbitrary (but not random) element self.end.before.keys.add(key) return key def getMinKey(self): if self.begin.after.val == 0: return "" key = self.begin.after.keys.pop() self.begin.after.keys.add(key) return key --------------------------------------------------------------------------------------------------------------------------------- class Node: def __init__(self, val= 0): self.val = val self.next = None self.pre = None self.arr = set() class AllOne(object): def __init__(self): """ Initialize your data structure here. """ self.head = Node() self.tail = Node() self.head.next, self.tail.pre = self.tail, self.head self.d = {} def move_forward(self, node, key): if node.val+1 != node.next.val: newNode = Node(node.val+1) newNode.pre, newNode.next = node, node.next newNode.pre.next = newNode.next.pre = newNode else: newNode = node.next newNode.arr.add(key) return newNode def pre(self, node, key): if node.val-1 != node.pre.val: newNode = Node(node.val-1) newNode.pre, newNode.next = node.pre, node newNode.pre.next = newNode.next.pre = newNode else: newNode = node.pre newNode.arr.add(key) return newNode def inc(self, key): """ Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: None """ if key not in self.d: node = self.head else: node = self.d[key] node.arr.discard(key) self.d[key] = self.move_forward(node, key) def dec(self, key): """ Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. :type key: str :rtype: None """ if key in self.d: node = self.d[key] node.arr.discard(key) if node.val != 1: self.d[key] = self.pre(node, key) else: del self.d[key] def getMaxKey(self): """ Returns one of the keys with maximal value. :rtype: str """ node = self.tail.pre while node and len(node.arr) == 0: node = node.pre if not node: return "" val = node.arr.pop() node.arr.add(val) return val def getMinKey(self): """ Returns one of the keys with Minimal value. :rtype: str """ node = self.head.next while node and len(node.arr) == 0: node = node.next if not node: return "" val = node.arr.pop() node.arr.add(val) return val ---------------------------------------------------------------------------------------------------- class Node: def __init__(self, val): self.next = None self.pre = None self.val = val self.data = set() class AllOne(object): def __init__(self): """ Initialize your data structure here. """ self.head = Node(0) self.tail = Node(0) self.head.next, self.tail.pre = self.tail, self.head self.memo = {} def add(self, node, key): if node.val+1 != node.next.val: newNode = Node(node.val+1) newNode.pre, newNode.next = node, node.next newNode.pre.next = newNode.next.pre = newNode else: newNode = node.next newNode.data.add(key) return newNode def add_prev(self, node, key): if node.val-1 != node.pre.val: newNode = Node(node.val-1) newNode.pre, newNode.next = node.pre, node newNode.pre.next = newNode.next.pre = newNode else: newNode = node.pre newNode.data.add(key) return newNode def inc(self, key): """ Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: None """ if key not in self.memo: self.memo[key] = self.add(self.head, key) else: node = self.memo[key] self.memo[key] = self.add(node, key) node.data.remove(key) if not node.data: node.pre.next, node.next.pre = node.next, node.pre node.next = node.pre = None def dec(self, key): """ Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. :type key: str :rtype: None """ if key in self.memo: node = self.memo[key] node.data.remove(key) del self.memo[key] if node.val > 1: self.memo[key] = self.add_prev(node, key) if not node.data: node.pre.next, node.next.pre = node.next, node.pre node.next = node.pre = None def getMaxKey(self): """ Returns one of the keys with maximal value. :rtype: str """ if not self.tail.pre.data: return "" num = self.tail.pre.data.pop() self.tail.pre.data.add(num) return num def getMinKey(self): """ Returns one of the keys with Minimal value. :rtype: str """ if not self.head.next.data: return "" num = self.head.next.data.pop() self.head.next.data.add(num) return num
''' You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers. Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives. ''' class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: start, end, res = [], [], [] for i in flowers: start.append(i[0]) end.append(i[1]) start.sort() #bisect only works with sorted data end.sort() for p in persons: num = bisect_right(start, p) - bisect_left(end, p) res.append(num) return res #bisect_right(start, p) gives you the number of flowers that are in full bloom at person p. #bisect_left(end, p) gives you number of flowers that are not in full bloom at person p. #we have to tighten our bound to get exact number of flowers that are in bloom or not, thats why we are using right and left of bisect module. ------------------------------------------------------------------------------------------------------- from heapq import heappush, heappop class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: out = [0 for _ in range(len(persons))] persons = [(arrival, i) for i, arrival in enumerate(persons)] persons.sort() flowers.sort() heap = [] f_idx = 0 for arrival, person_idx in persons: while f_idx < len(flowers) and flowers[f_idx][0] <= arrival: heappush(heap, flowers[f_idx][1]) f_idx += 1 while len(heap) and heap[0] < arrival: heappop(heap) out[person_idx] = len(heap) return out
''' There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d. Notice that the distance between the two cities is the number of edges in the path between them. ''' class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: def bfs(source, verticies): q = collections.deque() q.append((source, 0)) visited = set() visited.add(source) while q: furthest_node, furthest_dist = node, dist = q.popleft() for nei in adj[node]: if nei in verticies and nei not in visited: q.append((nei, dist+1)) visited.add(nei) return furthest_node, furthest_dist, visited def get_diameter(bitmask, counter): if counter < 2: return # check if all 1's are connected, if not return set_of_verticies = set() for vertex, is_set in enumerate(bitmask): if is_set: set_of_verticies.add(vertex) source = vertex farthest_node, _, visited_nodes_set = bfs(source, set_of_verticies) if len(visited_nodes_set) < len(set_of_verticies): return # not connected visited_nodes_set.clear() _, diam, _ = bfs(farthest_node, set_of_verticies) ans[diam]+=1 return def dfs(start_idx, counter): if start_idx > n: get_diameter(bitmask, counter) return # do not set start_idx to 1 dfs(start_idx+1, counter) # set start_idx to 1 bitmask[start_idx] = 1 dfs(start_idx+1, counter+1) # revert start_idx bitmask[start_idx] = 0 adj = collections.defaultdict(list) for n1, n2 in edges: adj[n1].append(n2) adj[n2].append(n1) ans = [0] * n bitmask = [0] * (n+1) counter = 0 dfs(1, 0) return ans[1:]
''' Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Find the leftmost occurrence of the substring part and remove it from s. Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string. ''' class Solution: def removeOccurrences(self, s: str, part: str) -> str: n=len(part) while part in s: i=s.index(part) s=s[:i]+s[i+n:] return s -------------------------------------------------------------------------- def removeOccurrences(self, s: str, part: str) -> str: while part in s: s=s.replace(part,"",1) return s
''' Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs. A pair (i, j) is fair if: 0 <= i < j < n, and lower <= nums[i] + nums[j] <= upper ''' class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: def countLess(val: int) -> int: res, j = 0, len(nums) - 1 for i in range(len(nums)): while i < j and nums[i] + nums[j] > val: j -= 1 res += max(0, j - i) return res nums.sort() return countLess(upper) - countLess(lower - 1) ------------------------------------------------------------------------------------------- class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: # First, note that the answer does not change if we sort the array nums.sort() fairCtr = 0 for i in range(len(nums)): # For each index find the left and right elements for which the sums lie between lower and upper l = bisect_left(nums, lower - nums[i]) r = bisect_right(nums, upper - nums[i]) fairCtr += (r - l) # check if index i lies in the interval, subtract one (we don't want to double count index i) if l <= i < r: fairCtr -= 1 return fairCtr // 2 ------------------------------------------------------------------ class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: nums.sort() ans = 0 lo = hi = len(nums)-1 for i, x in enumerate(nums): while 0 <= hi and x + nums[hi] > upper: hi -= 1 while 0 <= lo and x + nums[lo] >= lower: lo -= 1 ans += hi - lo if lo < i <= hi: ans -= 1 return ans//2
''' You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0. Return the maximum profit we can achieve after assigning the workers to the jobs. ''' class Solution(object): def maxProfitAssignment(self, difficulty, profit, worker): jobs = zip(difficulty, profit) jobs.sort() ans = i = best = 0 for skill in sorted(worker): while i < len(jobs) and skill >= jobs[i][0]: best = max(best, jobs[i][1]) i += 1 ans += best return ans ---------------------------------------------------------------------- class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: for i in range(len(difficulty)): difficulty[i] = (difficulty[i], profit[i]) difficulty.sort(key = lambda x:x[0]) # O(NlogN) i, L = 0, len(difficulty) ans, most = 0, 0 for wker in sorted(worker): while i < L and difficulty[i][0] <= wker: most = max(most, difficulty[i][1]) i += 1 ans += most return ans
''' A square matrix is said to be an X-Matrix if both of the following conditions hold: All the elements in the diagonals of the matrix are non-zero. All other elements are 0. Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false. ''' class Solution: def isD(self,i,j,l): return i == j or i+j == l-1 def checkXMatrix(self, grid: List[List[int]]) -> bool: l = len(grid) for i in range(l): for j in range(l): if self.isD(i,j,l): if grid[i][j] == 0: return False else: if grid[i][j]!= 0: return False return True ------------------------------------ class Solution: def checkXMatrix(self, grid: List[List[int]]) -> bool: n = len(grid) for i in range(n): for j in range(n): if i == j or i + j == n-1: if grid[i][j] == 0: return False else: if grid[i][j] != 0: return False return True --------------------------------------------- def checkXMatrix(self, grid: List[List[int]]) -> bool: m, n = len(grid), len(grid[0]) # problem states that m == n def isDiagonal(i,j): return i == j or (i + j + 1 == m) def isValid(i,j): return isDiagonal(i,j) == bool(grid[i][j]) # if it's diagonal, it's != 0; if it's not diagonal, it's 0 return all(isValid(i,j) for i,j in product(range(m), range(n)))
''' You are given a 0-indexed string street. Each character in street is either 'H' representing a house or '.' representing an empty space. You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at index i - 1 and/or index i + 1. A single bucket, if placed adjacent to two houses, can collect the rainwater from both houses. Return the minimum number of buckets needed so that for every house, there is at least one bucket collecting rainwater from it, or -1 if it is impossible. Explanation If s == 'H', return -1 If s starts with HH', return -1 If s ends with HH', return -1 If s has 'HHH', return -1 Each house H needs one bucket, that's s.count('H') Each 'H.H' can save one bucket by sharing one in the middle, that's s.count('H.H') (greedy count without overlap) So return s.count('H') - s.count('H.H') Key Point I'm not greedy, Python count is greedy for me, Complexity Time O(n) Space O(1) ''' def minimumBuckets(self, s): return -1 if 'HHH' in s or s[:2] == 'HH' or s[-2:] == 'HH' or s == 'H' else s.count('H') - s.count('H.H') ------------------------------------------------------------------------------------------------------------------------- class Solution: def minimumBuckets(self, street: str) -> int: n = len(street) buckets = 0 prevBucket = -2 for i, c in enumerate(street): if c == '.' or prevBucket == i - 1: continue buckets += 1 if i != n - 1 and street[i + 1] == '.': prevBucket = i + 1 elif not i or street[i - 1] == 'H': return -1 return buckets
''' You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. ''' Intuition Greedily paint nodes one by one. Because there is no node that has more than 3 neighbors, always one possible color to choose. def gardenNoAdj(self, N, paths): res = [0] * N G = [[] for i in range(N)] for x, y in paths: G[x - 1].append(y - 1) G[y - 1].append(x - 1) for i in range(N): res[i] = ({1, 2, 3, 4} - {res[j] for j in G[i]}).pop() return res --------------------------------------------------------------------------- class Solution: def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]: G = defaultdict(list) for path in paths: G[path[0]].append(path[1]) G[path[1]].append((path[0])) colored = defaultdict() def dfs(G, V, colored): colors = [1, 2, 3, 4] for neighbour in G[V]: if neighbour in colored: if colored[neighbour] in colors: colors.remove(colored[neighbour]) colored[V] = colors[0] for V in range(1, N + 1): dfs(G, V, colored) ans = [] for V in range(len(colored)): ans.append(colored[V + 1]) return ans
''' Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. ''' We can use 5 bits to represent the parity of the number of occurrences of vowels. For example, we can use 0/1 for even/odd numbers, then if we have 4a, 3e, 2i, 1o, 0u, the representation would be 01010. As we scan through the array, we can update the representation in O(1) time by using the XOR operation, and then store the index where every different representation first appeared. When we encounter a representation, say 01010 again at index j, we can look back on the index i where 01010 first appeared, and we know that the substring from i to j must be a valid string, and it is the longest valid substring that ends at j. def findTheLongestSubstring(self, s: str) -> int: vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16} d, n, r = {0: -1}, 0, 0 for i, c in enumerate(s): if c in vowels: n ^= vowels[c] if n not in d: d[n] = i else: r = max(r, i - d[n]) return r ----------------------------------------------------------------------------------- class Solution: def findTheLongestSubstring(self, s: str) -> int: def countVowels(ct): if not ct['a'] % 2 and not ct['e'] % 2 and not ct['i'] % 2 and not ct['o'] % 2 and not ct['u'] % 2: return True return False #Reducer #Slider #0 - len(s) #0 - len(s) -1 -> 1 - len(s) for i in range(len(s)): ctr = collections.Counter(s[:len(s) - i]) for j in range(i+1): #window = s[j:(len(s)+j) - i] if j != 0: ctr[s[j - 1]] -= 1 ctr[s[len(s)+j - i - 1]] += 1 if countVowels(ctr): return sum(ctr.values()) return 0 ------------------------------------------------------------------- v = {'a':0, 'e':1, 'i':2, 'o':3, 'u':4} curr = 0 left = dict() left[0] = -1 ans = 0 for index, i in enumerate(s): if(i in v): curr ^= (1<<v[i]) if(curr not in left): left[curr] = index else: ans = max(ans, index - left[curr]) return ans ---------------------------------------------------------------------------------- def findTheLongestSubstring(self, s: str) -> int: vowels = {'a': 16, 'e': 8, 'i': 4, 'o': 2, 'u': 1} vote_dict = {0: -1} vcount = 0 ans = 0 for idx, c in enumerate(s): if c in vowels.keys(): vcount = vcount ^ vowels[c] if vcount in vote_dict.keys(): ans = max(ans, idx - vote_dict[vcount]) else: vote_dict[vcount] = idx return ans
''' You are given two positive integer arrays nums1 and nums2, both of length n. The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7. ''' class Solution: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: nums1, nums2 = zip(*sorted(zip(nums1, nums2))) mad = [abs(nums1[i] - nums2[i]) for i in range(len(nums1))] M = sum(mad) MOD = 10**9 + 7 best = 0 for i in range(len(nums1)): if nums1[i] != nums2[i]: j = bisect.bisect_left(nums1, nums2[i]) if j == len(nums1): best = max(best, mad[i] - abs(nums1[-1] - nums2[i])) elif j == 0: best = max(best, mad[i] - abs(nums1[0] - nums2[i])) else: new = min(abs(nums1[j] - nums2[i]), abs(nums1[j-1] - nums2[i])) best = max(best, mad[i] - new) return (M - best) % MOD
''' from exponential program - kazak devs - Elzhan Zeinulla, 22 oct 2022 convert number to int. the number has commas separating every 3 digits: 1,700 = 1700 1,900,456 = 1900456 1 bln = 1000000000 1 trln = 1000000000000 ''' def f(s): s = s.split(',') temp = 0 pow = 0 s = s[::-1] # O(n) for i in range(len(s)): temp += (10**pow) * int(s[i]) pow += 3 print(temp) if __name__ == '__main__': s = '1,070' s = '1,567,003' s = '3,100,567,003' f(s)
''' Given a string s, determine if it is valid. A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times: Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty. Return true if s is a valid string, otherwise, return false. ''' class Solution: def isValid(self, s: str) -> bool: stack=[] for i in s: if i == 'a':stack.append(i) elif i=='b': if not stack:return False else: if stack[-1]=='a':stack.pop() else:return False stack.append(i) else: if not stack:return False else: if stack[-1]=='b':stack.pop() else:return False return len(stack)==0 ----------------------------------------------------------- class Solution: def isValid(self, S: str) -> bool: while S.count('abc'): S = S.replace('abc','') return not S
''' Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next #horrible solution class Solution: def isPalindrome(self, head: ListNode) -> bool: res = [] l = head while l: print(l.val) res.append(int(l.val)) l = l.next print(res) if len(res) % 2 == 0: mid = len(res)//2 lower_half = res[:mid] upper_half = res[mid:] upper_half = list(reversed(upper_half)) if lower_half == upper_half: return True else: return False else: mid = len(res)//2 lower = res[:mid] upper = res[(mid+1):] upper = list(reversed(upper)) if upper == lower: return True else: return False return True # concise solution # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: if not head or not head.next: return True res = [head.val,] while head.next: head = head.next res.append(head.val) return res[::-1] == res
''' 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 directly connected to both cities, it is only counted once. The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads, return the maximal network rank of the entire infrastructure. ''' class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: if roads == []: #egde case check return 0 #create adjacency matrix to check if edge present or not in O(1) time adj=[[0]*(n) for i in range(n)] for i in roads: adj[i[0]][i[1]] = 1 adj[i[1]][i[0]] = 1 node_degrees = defaultdict(int) for i in roads: node_degrees[i[0]]+=1 node_degrees[i[1]]+=1 maxx1, maxx2 = 0, 0 ans = 0 for i, k in node_degrees.items(): #O(N) if k >= maxx1: maxx1 = k maxx2 = 0 for j, l in node_degrees.items(): #O(N) if l >= maxx2 and j!=i: maxx2 = l if adj[i][j] == 1 or adj[j][i] == 1: #O(1) ans = max(ans, maxx1 + maxx2 - 1) else: ans = max(ans, maxx1 + maxx2 ) return ans -------------------------------------------------------------------------------- from collections import defaultdict from itertools import combinations class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: # Variables rank = 0 indegree = defaultdict(lambda: set()) nodes = [i for i in range(n)] # Update indegree hashmap for x,y in roads: indegree[x].add(y) indegree[y].add(x) # Try every pair of different cities and calculate its network rank. # The network rank of two vertices is sum of their degrees discarding the common edge. # For all combinations of nodes check network rank. # If two nodes are connected then consider the edge between them only once, # that is add -1 to sum of their indegrees else add 0. for x,y in combinations(nodes, 2): rank = max(rank, len(indegree[x]) + len(indegree[y]) # check if there is a road connecting two different cities - (1 if (([x,y] in roads) or ([y,x] in roads)) else 0)) return rank -----------
''' Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning. ''' def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: cnt = idx = 0 for i, num in enumerate(self.nums): if num != target: continue if cnt == 0: idx = i cnt = 1 else: # this random will already give me numbers # between 0 and cnt inclusive # so for 2nd number I am getting random number 0 and 1 # so each having a probability of 1/2 # similarly for three numbers it will be 1/3 rnd = random.randint(0, cnt) if (rnd == cnt): idx = i cnt += 1 return idx ----------------------------------------------------------------------------------------- from random import randint class Solution: def __init__(self, nums: List[int]): self.nums = nums # Time complexity: O(n), where "n" is the length of self.nums def pick(self, target: int) -> int: # how many samples with value "target" we have seen so far n_samples = 0 # result, selected index reservoir = 0 # iterate over all the values in self.nums for index, value in enumerate(self.nums): if value == target: # target value is found, increment the number of samples with value "target" found so far n_samples += 1 # if it is the first sample found, just keep it index if n_samples == 1: reservoir = index else: # if there are more than 1 sample, randomly select any of them nth_sample = randint(1, n_samples) # if the selected sample matches the first sample selected initially, then replace it if nth_sample == 1: reservoir = index return reservoir ---------------------------------------------------------------------------------------------------------- class Solution: def __init__(self, nums: List[int]): # Reservoir Sampling (which can handle the linked list with unknown size), time complexity O(n) (init: O(1), pick: O(n)), space complextiy O(1) self.nums = nums def pick(self, target: int) -> int: # https://docs.python.org/3/library/random.html count = 0 chosen_index = None for i in range(len(self.nums)): if self.nums[i] != target: continue count += 1 if count == 1: chosen_index = i elif random.random() < 1 / count: chosen_index = i return chosen_index --------------------------------------------------------------------------------------- class Solution { private int[] nums; private Random rand; public Solution(int[] nums) { // Do not allocate extra space for the nums array this.nums = nums; this.rand = new Random(); } public int pick(int target) { List<Integer> indices = new ArrayList<>(); int n = this.nums.length; int count = 0; int idx = 0; for (int i = 0; i < n; ++i) { if (this.nums[i] == target) { indices.add(i); } } int l = indices.size(); // pick an index at random int randomIndex = indices.get(rand.nextInt(l)); return randomIndex; } }
''' You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. Meetings are allocated to rooms in the following manner: Each meeting will take place in the unused room with the lowest number. If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting. When a room becomes unused, meetings that have an earlier original start time should be given the room. Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number. A half-closed interval [a, b) is the interval between a and b including a and not including b. ''' class Solution: def mostBooked(self, n, A): rooms = [0] * n A.sort() heap = [] avail = [i for i in range(n)] for [i, j] in A: while heap and heap[0][0] <= i: heapq.heappush(avail, heapq.heappop(heap)[1]) if not avail: [k, idx] = heapq.heappop(heap) i, j = k, j + k - i heapq.heappush(avail, idx) ready = heapq.heappop(avail) heapq.heappush(heap, [j, ready]) rooms[ready] += 1 return rooms.index(max(rooms)) -------------------------------------------------------------------------------- class Solution: def mostBooked(self, n: int, meetings: List[List[int]]) -> int: currentMeetHeap = [] numOfMeet = n * [0] currentMeet = n * [False] meetings.sort() # Removes ended meetings from the heap. def clearEnded(cutoff): while len(currentMeetHeap)>0 and cutoff>=currentMeetHeap[0][0]: ended = heapq.heappop(currentMeetHeap) currentMeet[ended[1]] = False def addMeeting(room, end): currentMeet[room] = True numOfMeet[room] += 1 heapq.heappush(currentMeetHeap, [end,room]) def getFirstMax(): maxMeet = 0 maxMeetRoom = 0 for i in range(len(numOfMeet)): meets = numOfMeet[i] if meets > maxMeet: maxMeet = meets maxMeetRoom = i return maxMeetRoom for meeting in meetings: # First check if theres any empty rooms at the start of the current meeting. # If so, use this room. clearEnded(meeting[0]) added = False for i in range(n): if not currentMeet[i]: addMeeting(i, meeting[1]) added = True break if (added): continue # If no meeting rooms initially available, pull a meeting from the heap. # We need to adjust the end time to account for the wait. firstAvailable = heapq.heappop(currentMeetHeap) addMeeting(firstAvailable[1], meeting[1]+(firstAvailable[0]-meeting[0])) return getFirstMax()