text stringlengths 37 1.41M |
|---|
#Given an integer num, return a string of its base 7 representation.
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0: return '0'
map = '0123456'
result = ''
neg = False
if num < 0:
neg= True
num = -num
while num > 0:
digit = num% 7
num = (num-digit)//7
result += str(map[digit])
res =result[::-1]
if neg:
res = '-' + res
return res
|
'''
A perfectly straight street is represented by a number line. The street has building(s) on it and is represented by a 2D integer array buildings, where buildings[i] = [starti, endi, heighti]. This means that there is a building with heighti in the half-closed segment [starti, endi).
You want to describe the heights of the buildings on the street with the minimum number of non-overlapping segments. The street can be represented by the 2D integer array street where street[j] = [leftj, rightj, averagej] describes a half-closed segment [leftj, rightj) of the road where the average heights of the buildings in the segment is averagej.
For example, if buildings = [[1,5,2],[3,10,4]], the street could be represented by street = [[1,3,2],[3,5,3],[5,10,4]] because:
From 1 to 3, there is only the first building with an average height of 2 / 1 = 2.
From 3 to 5, both the first and the second building are there with an average height of (2+4) / 2 = 3.
From 5 to 10, there is only the second building with an average height of 4 / 1 = 4.
Given buildings, return the 2D integer array street as described above (excluding any areas of the street where there are no buldings). You may return the array in any order.
The average of n elements is the sum of the n elements divided (integer division) by n.
A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
'''
Explanation
This question is a variation of the typical sweep line question like 253. Meeting Rooms II.
I would recommend to try out 253. Meeting Rooms II first, as the intuition of my solution is coming from the second official solution of it.
Please see more explanation with the code comments below
Time: O(NlogN) because of sorting
Space: O(N) due to the use of entries
Implementation
class Solution:
def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]:
entries = []
for s, e, h in buildings: # sweep line build
entries.append((s, h)) # positive height `h` means starting block of a building
entries.append((e, -h)) # negative height `-h` means ending block of a building
entries.sort() # sort
entries.append([0, 0]) # add a dummy last node for edge case
n, ans = len(entries), []
prev, prev_idx = None, None # prev: previous average, prev_idx: lower bound index with same average
i = cur = cnt = 0 # i: index of `entries`, cur: prefix sum to `i`, cnt: number of buildings
while i < n-1:
while i < n-1 and entries[i][0] == entries[i+1][0]: # keep reading info at the same index
idx, h = entries[i]
cnt += 1 if h > 0 else -1 # cnt number of building
cur += h # prefix sum
i += 1
else: # always read one step when either (after while loop) or (never going in the while loop)
idx, h = entries[i]
cnt += 1 if h > 0 else -1
cur += h
i += 1
if not cnt: # cnt can be `0` when leaving all visited building, e.g. [[1,2,1],[5,6,1]]
ans.append([prev_idx, idx, prev]) # thus, we will append segment here
prev = prev_idx = None # since we will be starting a new segment, we need to set `prev` and `prev_idx` to None, like the initial condition
continue # no need going any further when `cnt == 0`
avg = cur // cnt # calculate average
if prev != avg: # when prev != avg, meaning building height differs, we need to record a segment
if prev: # only if `prev` is not None, to handle scenarios like `prev = None, avg = 1`
ans.append([prev_idx, idx, prev])
prev, prev_idx = avg, idx # update `prev` and `prev_idx`
return ans
------------------------------------------------
The Big Idea: Maintain two pointers into sorted lists of the start and endpoints of the buildings as we move left to right down the 'street'. Merge adjacent segments with the same average height and add new segments as we go.
class Solution:
def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]:
B = len(buildings)
starts = sorted((s, h) for (s, _, h) in buildings)
ends = sorted((e, -h) for (_, e, h) in buildings)
sp = 0
ep = 0
street = []
seg_start = -1
total_height = 0
bldgs = 0
while sp < B:
if starts[sp][0] < ends[ep][0]:
(point, height) = starts[sp]
sp += 1
if bldgs and point > seg_start:
avg = total_height // bldgs
if (street and
street[-1][1] == seg_start and
street[-1][2] == avg):
street[-1][1] = point
else:
street.append([seg_start, point, avg])
bldgs += 1
else:
(point, height) = ends[ep]
ep += 1
if point > seg_start:
avg = total_height // bldgs
if (street and
street[-1][1] == seg_start and
street[-1][2] == avg):
street[-1][1] = point
else:
street.append([seg_start, point, avg])
bldgs -= 1
seg_start = point
total_height += height
# Drain the endpoints list
while ep < B:
(point, height) = ends[ep]
ep += 1
if point > seg_start:
avg = total_height // bldgs
if (street and
street[-1][1] == seg_start and
street[-1][2] == avg):
street[-1][1] = point
else:
street.append([seg_start, point, avg])
bldgs -= 1
seg_start = point
total_height += height
return street
---------------------------------------------------------------
The algorithm has 3 steps:
Put the lines into a heap
Sweep through the lines and calculate average heights on the fly
Merge the buildings attached to each other if their average heights are the same
class Solution:
def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]:
import heapq
# Step 1
START, END = 1, 0
heap = []
for start, end, height in buildings:
heap.extend(((start, START, height), (end, END, height)))
heapq.heapify(heap)
# Step 2
res = []
start, height = -1, 0
count = 0 # number of overlapped buildings
while heap:
line, kind, h = heapq.heappop(heap)
if kind == START:
if count > 0 and line > start:
res.append((start, line, height // count))
start = line
height += h
count += 1
else:
if line > start:
res.append((start, line, height // count))
start = line
count -= 1
height -= h
# Step 3
merged = []
START, END, HEIGHT = 0, 1, 2
for start, end, height in res:
if merged and start == merged[-1][END] and height == merged[-1][HEIGHT]:
merged[-1][HEIGHT] = end
else:
merged.append([start, end, height])
return merged
----------------------------------------------------------
class Solution:
def averageHeightOfBuildings(self, a: List[List[int]]) -> List[List[int]]:
# cast events to deltas against the total_height & total_count
events = defaultdict(lambda: [0, 0])
for s,e,h in a:
events[s] = list(map(add, events[s], [h, 1]))
events[e] = list(map(add, events[e], [-h, -1]))
events = dict(sorted(events.items()))
def average_height(tot, cnt):
if cnt == 0:
return 0
else:
return tot // cnt
ret = []
# current average height
tot = 0
cnt = 0
pos = -inf
for POS,(dt, dc) in events.items():
TOT = tot + dt
CNT = cnt + dc
h = average_height(tot, cnt)
H = average_height(TOT, CNT)
# end of segment
if h != H:
# mute zero height segments
if h != 0:
ret.append([pos, POS, h])
pos = POS
tot = TOT
cnt = CNT
return ret
|
'''
An ugly number is a positive integer that is divisible by a, b, or c.
Given four integers n, a, b, and c, return the nth ugly number.
'''
from math import gcd
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
def lcm( x, y):
# From number theory,
# gcd(x,y) * lcm(x,y) = x * y
return x * y // gcd(x,y)
# -----------------------------------
def total_num_of_multiples( number, a, b, c):
# From set theory,
# count the total number of mutiples of a, b, c, range from 1 to number.
ab = lcm(a,b)
bc = lcm(b,c)
ac = lcm(a,c)
abc = lcm(a, bc)
result = number // a + number // b + number // c
result -= number // ab + number // bc + number // ac
result += number // abc
return result
# -----------------------------------
# Goal:
# Find the smallest number k, such that k has n multiples of a, b, or c.
# Binary search approach
lower = 1
upper = 2 * (10 ** 9)
while lower < upper:
mid = lower + (upper - lower) // 2
count_of_u_number = total_num_of_multiples(mid, a, b, c)
if count_of_u_number >= n:
upper = mid
else:
lower = mid+1
return lower
|
'''
You are given an elevation map represents as an integer array heights where heights[i] representing the height of the terrain at index i. The width at each index is 1. You are also given two integers volume and k. volume units of water will fall at index k.
Water first drops at the index k and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules:
If the droplet would eventually fall by moving left, then move left.
Otherwise, if the droplet would eventually fall by moving right, then move right.
Otherwise, rise to its current position.
Here, "eventually fall" means that the droplet will eventually be at a lower level if it moves in that direction. Also, level means the height of the terrain plus any water in that column.
We can assume there is infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than one grid block, and each unit of water has to be in exactly one block.
'''
def pourWater(self, heights, V, K):
for _ in range(V):
mark = K # where to fall water
l = K - 1 # search left
while l>=0:
if heights[l] < heights[mark]:
mark = l
elif heights[l] > heights[mark]:
break
l -= 1
if mark < K:
heights[mark] += 1
continue
r = K + 1 # search right
while r < len(heights):
if heights[r] < heights[mark]:
mark = r
elif heights[r] > heights[mark]:
break
r += 1
heights[mark] += 1
return heights
|
'''
You are given an array points where points[i] = [xi, yi] represents a point on an X-Y plane.
Straight lines are going to be added to the X-Y plane, such that every point is covered by at least one line.
Return the minimum number of straight lines needed to cover all the points.
'''
Explanation
The data scale for this question is very small (maximum 10 points, range in [-100, 100])
By basic Math, we all know Two points define a line. This tells us:
If there are n points, the maximum number of lines we need will be
math.ceil(n / 2)
If we use k line to cover m points, then the maximum number of lines we need now will be
k + math.ceil((n-m)/2)
Whenever there is a line that covers more than 2 points, it will be very useful
A line can be defined as y = a*x + b
With above intuition, we will then
Calculate a and b in formula y = a*x + b, given two points (x1, y1) and (x2, y2)
a = (y2-y1) / (x2-x1)
b = y1 - a * x1
If x1 == x2, just set a = x1, b = sys.maxsize meaning these two points are on the same vertical line
The representation is not Mathmatically correct. It just a unique way to represent vertical lines here.
Gathering all lines that covers more than 2 points, save in lines
Given 10 points, the maximum number of lines that cover more than 2 points will be 9, as shown below
xxx
xxx
xxxx
This will lead to a mask size of 2 ** 9 == 512, which is still pretty small scale
Use bitmasking to try out all possible combinations on lines
Meanwhile, calculate the minimum number of lines needed to cover all points
Implementation
class Solution:
def minimumLines(self, points: List[List[int]]) -> int:
n, line_points = len(points), collections.defaultdict(set)
for i in range(n): # calculate `line_points`
x1, y1 = points[i]
for j in range(i+1, n):
x2, y2 = points[j]
if x1 == x2: # handle divided by zero case
a, b = x1, sys.maxsize # for `b`, you can use any number not in range of [-100, 100]
else:
a = (y2 - y1) / (x2 - x1)
b = y1 - a * x1
line_points[(a, b)].add((x1, y1))
line_points[(a, b)].add((x2, y2))
lines = [line for line, points in line_points.items() if len(points) > 2] # filtering out lines that cover more than 3 points
ans, m = math.ceil(n / 2), len(lines) # based on Math, set default value for ans
for i in range(1, 2**m): # bitmasking on `lines` (try out all combinations)
j, cnt = 0, bin(i).count('1') # cnt = number of line used for current masking
cur_points = set() # current points covered on selected lines
while i > 0:
if i % 2:
cur_points |= line_points[lines[m-1-j]] # set union operaion on '1' bits
i >>= 1
j += 1
ans = min(ans, cnt + math.ceil( (n-len(cur_points))/2 )) # check if current masking is better
return ans
--------------------------------------
class Solution:
def minimumLines(self, points: List[List[int]]) -> int:
slope_calc = lambda p1, p2: (p2[1] - p1[1]) / (p2[0] - p1[0]) if p2[0] != p1[0] else math.inf
def helper(lines, points):
if len(points) == 0:
return len(lines)
point = points[0]
# add to existing line
for p, slope in lines:
s = slope_calc(point, p)
if s == slope:
return helper(lines, points[1:])
# if we have a single point and it doesn't belong to an existing
# line, we must have another line to cover it.
if len(points) == 1:
return len(lines) + 1
# creating new line in the case we have two or more points
# (cover two at once). iterating through all possibilities.
best = math.inf
for i in range(1, len(points)):
p = points[i]
slope = slope_calc(point, p)
lines.append((point, slope))
best = min(best, helper(lines, points[1:i] + points[i + 1:]))
lines.pop(-1)
return best
return helper([], points) if len(points) > 1 else 1
----------------------------------------------------------------
class Solution:
def minimumLines(self, points: List[List[int]]) -> int:
# 最终状态一定会被分为 一条只包含若干个个点的线 和 其他若干条线 两部分
# 所以只需要穷举每一个状态的所有分成两部分的方法,找到最小的即可
# 初始值就是把所有仅包含一条线的状态初始成 1
n = len(points)
kpoint = {}
dp = defaultdict(lambda:inf)
for i in range(n):
for j in range(i+1,n):
p1,p2 = points[i],points[j]
if p1[0] == p2[0]:
k = inf
else:
k = (p1[1] - p2[1])/(p1[0]-p2[0])
kpoint[(i,j)] = k
kpoint[(j,i)] = k
def isOneLine(state):
ct = state.bit_count()
if ct ==1 or ct == 2:
return True
else:
prev = None
ks = set()
for j in range(n):
if (state >> j) & 1 != 0:
if prev is not None:
k = kpoint[(prev,j)]
if len(ks) == 0:
ks.add(k)
elif k not in ks:
return False
else:
prev = j
return True
for state in range(1<<n):
if isOneLine(state):
dp[state] = 1
dp[0] = 0
for state in range(1<<n):
subset = state
while subset > 0:
dp[state] = min(dp[state], dp[subset] + dp[state-subset])
subset = (subset - 1) & state
return dp[(1<<n)-1]
|
'''
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.
After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.
However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.
Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.
'''
class Solution:
def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:
if sum(dist)/speed > hoursBefore: return -1 # impossible
@cache
def fn(i, k):
"""Return min time (in distance) of traveling first i roads with k skips."""
if k < 0: return inf # impossible
if i == 0: return 0
return min(ceil((fn(i-1, k) + dist[i-1])/speed) * speed, dist[i-1] + fn(i-1, k-1))
for k in range(len(dist)):
if fn(len(dist)-1, k) + dist[-1] <= hoursBefore*speed: return k
|
'''
(This problem is an interactive problem.)
Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship.
You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary.
Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle.
Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
constraints:
On the input ships is only given to initialize the map internally. You must solve this problem "blindfolded". In other words, you must find the answer using the given hasShips API, without knowing the ships position.
0 <= bottomLeft[0] <= topRight[0] <= 1000
0 <= bottomLeft[1] <= topRight[1] <= 1000
topRight != bottomLeft
'''
Intuition:
Leaves are single grid points, either containing ships or not. Our goal is to count all the leaves containing ships.
def countShips(self, sea, topRight, bottomLeft):
x1, y1 = bottomLeft.x, bottomLeft.y
x2, y2 = topRight.x, topRight.y
if x1 > x2 or y1 > y2 or not sea.hasShips(topRight, bottomLeft):
return 0
if x1 == x2 and y1 == y2:
return 1
x, y = (x1+x2)//2, (y1+y2)//2
return self.countShips(sea, Point(x,y2), Point(x1,y+1)) + \
self.countShips(sea, Point(x2,y2), Point(x+1,y+1)) + \
self.countShips(sea, Point(x,y), Point(x1,y1)) + \
self.countShips(sea, Point(x2,y), Point(x+1,y1))
----------------------------------------------------------------------------------------------------------------------------------
class Solution(object):
def countShips(self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point') -> int:
X, Y = topRight.x - bottomLeft.x, topRight.y - bottomLeft.y
if X == Y == 0:
// area is a point, hasShips returns exact count of ships: 1 or 0
return sea.hasShips(topRight, bottomLeft)
if not sea.hasShips(topRight, bottomLeft):
return 0
// there is at least 1 ship in the area
// divide area to two by the longest edge
if X > Y:
half = bottomLeft.x + X // 2
midTopRight = Point(half, topRight.y)
midBottomLeft = Point(half + 1, bottomLeft.y)
return self.countShips(sea, midTopRight, bottomLeft) + self.countShips(sea, topRight, midBottomLeft)
else:
half = bottomLeft.y + Y // 2
midTopRight = Point(topRight.x, half)
midBottomLeft = Point(bottomLeft.x, half + 1)
return self.countShips(sea, midTopRight, bottomLeft) + self.countShips(sea, topRight, midBottomLeft)
--------------------------------------------------------------------------------------------------------------------
class Solution(object):
def countShips(self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point') -> int:
filled_xs = []
num_xs_found = 0
result = 0
def recur_x(left_x, right_x):
nonlocal num_xs_found
if num_xs_found == 10:
return
has_ships = sea.hasShips(Point(right_x, topRight.y), Point(left_x, bottomLeft.y))
if has_ships:
if right_x == left_x:
filled_xs.append(left_x)
num_xs_found += 1
else:
mid_x = (left_x + right_x) // 2
recur_x(left_x, mid_x)
recur_x(mid_x + 1, right_x)
def recur_y(x, bottom_y, top_y):
nonlocal result
has_ships = sea.hasShips(Point(x, top_y), Point(x, bottom_y))
if has_ships:
if top_y == bottom_y:
result += 1
else:
mid_y = (bottom_y + top_y) // 2
recur_y(x, bottom_y, mid_y)
recur_y(x, mid_y + 1, top_y)
recur_x(bottomLeft.x, topRight.x)
for x in filled_xs:
recur_y(x, bottomLeft.y, topRight.y)
return result
-----------------------------------------------------------------------------------------------------------
So the basic idea is to isolate single points as rectangles and count the number of such points that host a ship.
The brute force way to do this would be to simply iterate over all the points within and on the boundary, but that would clearly take well over 400 calls for a moderately large input.
This can be easily addressed by splitting the rectangle into two NON-OVERLAPPING parts at each step. First making horizontal splits, then making the vertical ones.
Here is the commented code,
# """
# This is Sea's API interface.
# You should not implement it, or speculate about its implementation
# """
#class Sea(object):
# def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool:
#
#class Point(object):
# def __init__(self, x: int, y: int):
# self.x = x
# self.y = y
class Solution(object):
def countShips(self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point') -> int:
res = 0
def sliceRect(tr, bl):
nonlocal res
lx, rx, ly, ry = bl.x, tr.x, bl.y, tr.y
# For the given bounding coordinates, we check if there is at least 1 ship in the rectangle
if not sea.hasShips(tr, bl): return
# If we have reached here, it means that the ractangle has at least 1 ship
# If the rectangle is a single point, we increase the count
if lx == rx and ly == ry:
res += 1
return
# If the bottomLeft and topRight points have are at different heights, we horizontally slice the rectangle
if ry-ly > 0:
sliceRect(Point(rx, ry), Point(lx, (ry+ly+1)//2))
sliceRect(Point(rx, (ry+ly+1)//2-1), Point(lx, ly))
# If the bottomLeft and topRight points have horizontal space between them, we vertically slice the recatngle
elif rx-lx > 0:
sliceRect(Point(rx, ry), Point((rx+lx+1)//2, ly))
sliceRect(Point((rx+lx+1)//2-1, ry), Point(lx, ly))
# In both the above slices, the important point to not is that there is NO OVERLAP
return
sliceRect(topRight, bottomLeft)
return res
------------------------------------------------------------------------------
class Solution(object):
def countShips(self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point') -> int:
filled_xs = []
num_xs_found = 0
result = 0
def recur_x(left_x, right_x):
nonlocal num_xs_found
if num_xs_found == 10:
return
has_ships = sea.hasShips(Point(right_x, topRight.y), Point(left_x, bottomLeft.y))
if has_ships:
if right_x == left_x:
filled_xs.append(left_x)
num_xs_found += 1
else:
mid_x = (left_x + right_x) // 2
recur_x(left_x, mid_x)
recur_x(mid_x + 1, right_x)
def recur_y(x, bottom_y, top_y):
nonlocal result
has_ships = sea.hasShips(Point(x, top_y), Point(x, bottom_y))
if has_ships:
if top_y == bottom_y:
result += 1
else:
mid_y = (bottom_y + top_y) // 2
recur_y(x, bottom_y, mid_y)
recur_y(x, mid_y + 1, top_y)
recur_x(bottomLeft.x, topRight.x)
for x in filled_xs:
recur_y(x, bottomLeft.y, topRight.y)
return result
|
'''
In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.
The value of |x| is defined as:
x if x >= 0
-x if x < 0
'''
For half of side length 1: it has [1] * 4 apples on side edges, [1 * 2] * 4 apples on corners;
For half of side length 2: it has [2,3,3] * 4 apples on side edges, [2 * 2] * 4 apples on corners.
For half of side length 3, it has [3,4,4,5,5] * 4 apples on side edges, [3 * 2] * 4 apples on corners.
...
Therefore, by mathematical induction, for half of side length n, it has [n, (n+1)* 2, ... (2n-1) * 2] * 4 apples on side edges, [n * 2] * 4 apples on corners. Hence, it will have (3 * n^2 - 2 * n) * 4 apples on side edges since it is an arithmetic sequence from (n+1) to (2n-1), then sum it over to get the total of apples, once it's greater than needed apples, simply return its perimeter.
class Solution(object):
def minimumPerimeter(self, neededApples):
"""
:type neededApples: int
:rtype: int
"""
num_apples = 0
for radius in range(1, 1000000):
edge_apples = (3*radius**2 - 2*radius)*4
corner_apples = 2*radius * 4
num_apples += corner_apples + edge_apples
if num_apples >= neededApples:
return 2*radius*4
--------------------------------------------------------------
def minimumPerimeter(self, neededApples: int) -> int:
lo, hi = 1, 100000
while lo < hi:
m = (lo+hi)//2
n = 2*m*(m+1)*(2*m+1)
if n < neededApples: lo = m+1
else: hi = m
return 8*lo
-------------------------------------------------------------------------------
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
def apples(r):
return 2 * r * (r + 1) * (2*r + 1)
low, high = 1, neededApples
while low <= high:
mid = (low + high) // 2
total = apples(mid)
if total == neededApples:
return 8*mid
elif total < neededApples:
low = mid + 1
else:
high = mid - 1
return 8 * (mid + (total < neededApples))
|
'''
You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
'''
'''
Intuition
Do this first:
Given pref, find arr that
pref[i] = arr[0] + arr[1] + ... + arr[i]
pref is prefix sum of arr
The solution is simple:
for(int i = A.size() - 1; i > 0; --i)
A[i] -= A[i - 1];
return A;
Now we are doing something similar for this problem.
Explanation
Since pref is the prefix array,
it's calculated from arr one by one,
we can doing this process reverssely to recover the original array.
Since
pref[i] = pref[i-1] ^ A[i]
so we have
pref[i] ^ pref[i-1] = A[i]
So we simply change - to ^ in the intuition solution
The reverse operation of + is -
The reverse operation of ^ is still ^
More general, we can apply this solution to prefix of any operation.
'''
def findArray(self, A):
for i in range(len(A) - 1, 0, -1):
A[i] ^= A[i - 1]
return A
----------------------------------------------------------------------------
class Solution:
def findArray(self, pref: List[int]) -> List[int]:
for i in range(len(pref)-1,0,-1):
pref[i] = pref[i]^pref[i-1]
return pref
|
'''
You are given a 0-indexed integer array nums of size n and a positive integer k.
We call an index i in the range k <= i < n - k good if the following conditions are satisfied:
The k elements that are just before the index i are in non-increasing order.
The k elements that are just after the index i are in non-decreasing order.
Return an array of all good indices sorted in increasing order.
'''
class Solution:
def goodIndices(self, nums: List[int], k: int) -> List[int]:
if len(nums) <= 2 * k:
return []
pref = [0] * len(nums)
suff = [0] * len(nums)
count = 0
# descending order
for i in range(len(nums)):
pref[i] = count
if i != 0 and nums[i] <= nums[i - 1]:
count += 1
else:
count = 1
count = 0
# ascending order
for j in range(len(nums) - 1, -1, -1):
suff[j] = count
if j != len(nums) - 1 and nums[j] <= nums[j + 1]:
count += 1
else:
count = 1
ans = []
for i in range(len(suff)):
if pref[i] >= k and suff[i] >= k:
ans.append(i)
return ans
-------------------------------------------------------------------------------------------------
def goodIndices(self, nums, k):
n = len(nums)
if k*2+1 > n : return []
else :
ans = []
nonde = [0 for _ in range(n)]
nonin = [0 for _ in range(n)]
cur = nums[0]
nonde[0] = 1
for i in range(1,n-k) :
if cur >= nums[i] :
nonde[i] = nonde[i-1]+1
else :
nonde[i] = 1
cur = nums[i]
cur = nums[n-1]
nonin[n-1] = 1
for i in range(n-2,k,-1) :
if cur >= nums[i] :
nonin[i] = nonin[i+1]+1
else :
nonin[i] = 1
cur = nums[i]
for i in range(k,n-k) :
if nonde[i-1] >= k and nonin[i+1] >= k :
ans += [i]
return ans
|
You are given a positive integer n representing the number of nodes in a connected undirected graph containing exactly one cycle. The nodes are numbered from 0 to n - 1 (inclusive).
You are also given a 2D integer array edges, where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting node1i and node2i in the graph.
The distance between two nodes a and b is defined to be the minimum number of edges that are needed to go from a to b.
Return an integer array answer of size n, where answer[i] is the minimum distance between the ith node and any node in the cycle.
class Solution:
def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]:
g = defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
# step 1: backtracking DFS to find the cycle
circle = []
vis = set()
def find_circle(node, par):
if node in vis:
return (True, node)
for nei in g[node]:
if nei == par: continue
vis.add(node)
circle.append(node)
status, res = find_circle(nei, node)
if status: return status, res
circle.pop()
vis.remove(node)
return False, None
_, node = find_circle(0, None)
# get the circle from start "node"
circle = circle[circle.index(node):]
# step 2: BFS to get rest of the nodes from each node in the cycle
ans = [0] * n
vis = set(circle)
steps = 0
while circle:
new_q = []
steps += 1
for x in circle:
for nei in g[x]:
if nei in vis: continue
ans[nei] = steps
vis.add(nei)
new_q.append(nei)
circle = new_q
return ans
----------------------------------------------------------------
This algorithm consists of two parts:
Find nodes in cycle with topological sorting
Find distances from the nodes in cycle using BFS
We can use topological sorting to find nodes that are not in cycle. Based on this information, we know the other nodes are in cycle for sure.
Then we can use BFS to measure the distance from the nodes that are in cycle.
class Solution:
def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]:
# part 0, build graph
graph = [[] for _ in range(n)]
indegree = [0] * n
for u, v in edges:
graph[u].append(v)
indegree[u] += 1
graph[v].append(u)
indegree[v] += 1
# part 1 topological sorting
stack = [node for node in range(n) if indegree[node] == 1]
out_of_cycle = set()
while stack:
node = stack.pop()
out_of_cycle.add(node)
for neighbour in graph[node]:
if neighbour not in out_of_cycle:
indegree[neighbour] -= 1
if indegree[neighbour] == 1:
stack.append(neighbour)
# part 2 bfs
from collections import deque
queue = deque(node for node in range(n) if node not in out_of_cycle)
ans = [0] * n
steps = 0
visited = set(queue)
while queue:
for _ in range(len(queue)):
node = queue.popleft()
ans[node] = steps
for neighbour in graph[node]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
steps += 1
return ans
|
'''
Given three integer arrays nums1, nums2, and nums3, return a
distinct array containing all the values that are present in at
least two out of the three arrays. You may return the values in any order.
'''
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
n1 = nums1
n2 = nums2
n3 = nums3
main = set()
for i in range(len(n1)):
if n1[i] in n2:
main.add(n1[i])
for i in range(len(n2)):
if n2[i] in n3:
main.add(n2[i])
for i in range(len(n3)):
if n3[i] in n1:
main.add(n3[i])
main = list(main)
print(main)
return main
|
'''
A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators. In this problem, we only consider the '+' operator (i.e. addition).
You are given the roots of two binary expression trees, root1 and root2. Return true if the two binary expression trees are equivalent. Otherwise, return false.
Two binary expression trees are equivalent if they evaluate to the same value regardless of what the variables are set to.
'''
class Solution:
def parse(self, node, counter):
if node.val != '+':
counter[node.val] += 1
else:
self.parse(node.left, counter)
self.parse(node.right, counter)
return counter
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
return self.parse(root1, Counter()) == self.parse(root2, Counter())
-----------------------------------------
class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
freq = defaultdict(int)
def fn(x, k):
if not x: return
freq[x.val] += k
if freq[x.val] == 0: freq.pop(x.val)
fn(x.left, k)
fn(x.right, k)
fn(root1, 1)
fn(root2, -1)
return not freq
-----------------------------------------------------
Explanation
Since + is the only sign, no need to worries about the order of addition
a + b + c == c + a + b
Simply count how many times a number appeared in the tree
In order traversal a tree
Use a dictionary to count node value freqeuncy for the first tree root1
Dis-count node value from the dictionary when doing in-order for the second tree root2
Return true if frequency for each node was back to 0, other wise return False
Meaning for any node n, the frequency of it in tree 1 == the frequency of it in tree 2
Time Complexity: O(2N) -> O(N)
Space Complexity: O(K), K is number of unique values len(set(N))
Implementation
class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
c = collections.defaultdict(int) # dictionary to count frequency
def in_order(node, count=True): # very standard iterative in-order traversal, with count/dis-count frequency toggled
stack = []
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if node.val != '+': c[node.val] = c[node.val] + (1 if count else -1)
node = node.right
in_order(root1, True) # count frequency (increase)
in_order(root2, False) # dis-count frequency (decrease)
return all(val == 0 for _, val in c.items()) # check whether all values are 0
---------------------------------------
Idea
We can use a dictionary to keep track of each value.
When traverse the first tree, we do dic[node.val] += 1. And when traverse the second tree, we do dic[node.val] -= 1. If two trees are equivalent, all dic values should be 0 at the end.
This method extends nicely to the follow-up question. If there's a minus sign, we simply revert the increment value (sign) of the right child.
Complexity
Time complexity: O(N)
Space complexity: O(logN)
Python
class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
dic = collections.Counter()
def dfs(node, sign):
if not node:
return
if node.val == '+':
dfs(node.left, sign)
dfs(node.right, sign)
elif node.val == '-': # for follow-up
dfs(node.left, sign)
dfs(node.right, -sign)
else:
dic[node.val] += sign
dfs(root1, 1)
dfs(root2, -1)
return all(x == 0 for x in dic.values())
-----------------------------------------------------------------------------------
class Solution:
def evaluate(self, n: 'Node') -> int:
if n.val == '+':
return self.evaluate(n.left) + self.evaluate(n.right)
else:
return hash(n.val)
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
r1_val = self.evaluate(root1)
r2_val = self.evaluate(root2)
return r1_val == r2_val
|
'''
A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
It can jump exactly a positions forward (to the right).
It can jump exactly b positions backward (to the left).
It cannot jump backward twice in a row.
It cannot jump to any forbidden positions.
The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.
Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.
'''
class Solution:
def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:
forbidden = set(forbidden)
limit = max(x,max(forbidden))+a+b
seen = set()
q = [(0,0,False)]
while q:
p,s,isb = q.pop(0)
if p>limit or p<0 or p in forbidden or (p,isb) in seen:
continue
if p==x:
return s
q.append((p+a,s+1,False))
if not isb:
q.append((p-b,s+1,True))
seen.add((p,isb))
return -1
-----------------------------------------------------------------------------------------------------------------------------
class Solution:
def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:
forbidden = set(forbidden)
visited = set()
limit = max(x, max(forbidden)) + a + b
queue = [(0, 0, False)]
while queue:
pos, step, back = queue.pop(0)
if pos > limit or pos < 0 or pos in forbidden or (pos, back) in visited:
continue
if pos == x:
return step
queue.append((pos+a, step+1, False))
if not back: queue.append((pos-b, step+1, True))
visited.add((pos, back))
return -1
A traditional BFS solution by using queue. Each element in the queue contains:
pos: The current position of the bug;
step: The total step;
back: Check if the previous step is jumping backward.
The terminal conditions is declared in the question:
pos < 0: The bug cannot jump to the negative position;
pos in forbidden: The bug cannot jump to the forbidden position;
(pos, back) in visited: To prevent the bug repeatly jumps between the previous and current position, it is noticeable that jump forward or backward to the position is totally different;
pos > limit: As 0 <= x <= 2000, the maximum index of position will not beyond limit, which limit = max(x, max(forbidden)) + a + b.
|
'''
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference
between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Return the maximum such product difference.
'''
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums = sorted(nums)
a, b = nums[-1], nums[-2]
c, d = nums[0], nums[1]
res = a*b - c*d
print(res)
return res
|
'''
Напишите функцию fizzbuzztest, которая возвращает массив, который формируется по следующим правилам:
Обрабатываются числа от 1 до 100
Если число кратно трем, то в массив заносим слово Fizz
Если число кратно пяти, то в массив заносим слово Buzz
Если число кратно и трем, и пяти, то в массив заносим слово FizzBuzz
Если число не кратно ни одному их этих чисел, то в массив нужно поместить просто само число
'''
class Answer:
def fizzbuzztest(self):
res = list()
for i in range(1, 101):
if i %3 ==0 and i %5 == 0:
res.append('FizzBuzz')
elif i %3 ==0 :
res.append('Fizz')
elif i %5 ==0:
res.append('Buzz')
else:
res.append(i)
return res
|
'''
Given a string s, find the length of the longest substring without repeating characters.
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = 0
r = 0
res = 0
seen = set()
while l < len(s):
seen.clear()
r = l
while r < len(s):
if s[r] in seen:
break
seen.add(s[r])
r += 1
res = max(res, r-l)
l += 1
print(res)
return res
|
'''
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.
The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed).
Find the kth largest value (1-indexed) of all the coordinates of matrix.
'''
class Solution:
def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:
q = [matrix[0][0]]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i == j == 0:
continue
elif i == 0:
matrix[i][j] ^= matrix[i][j-1]
elif j == 0:
matrix[i][j] ^= matrix[i-1][j]
else:
matrix[i][j] ^= matrix[i-1][j] ^ matrix[i][j-1] ^ matrix[i-1][j-1]
if len(q) < k:
heapq.heappush(q, matrix[i][j])
else:
heapq.heappushpop(q, matrix[i][j])
return q[0]
-------------------------------------------------------------------------------------------------
class Solution:
def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:
temp=0
pq= []
n = len(matrix)
m = len(matrix[0])
prefix= [ [0]*m for i in range(n) ]
for i in range(n):
for j in range(m):
if i==0 or j==0:
if i==0 and j==0:
prefix[i][j] = matrix[i][j]
elif i==0 and j!=0:
prefix[i][j] ^= prefix[i][j-1]^ matrix[i][j]
else:
prefix[i][j]^=prefix[i-1][j]^ matrix[i][j]
else:
prefix[i][j] ^= prefix[i-1][j] ^ prefix[i][j-1]^matrix[i][j]^prefix[i-1][j-1]
if len(pq)<k:
heappush(pq,prefix[i][j])
else:
heappush(pq, prefix[i][j])
heappop(pq)
return heappop(pq)
|
'''
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one
stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
'''
#my own TLE solution
def f(nums):
cur_profit = 0
m = 1e9
for i in range(len(nums)-1):
local_min = nums[i]
if local_min < m:
m = local_min
for j in range( i+1, len(nums)):
if nums[j] - nums[i] > cur_profit:
cur_profit = nums[j]-nums[i]
print(cur_profit)
r = [7,1,5,3,6,4]
f(r)
#все равно сам нашел хотя бы тле решение!
# solution optimal
import sys
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxpro = 0
nums = prices
m = sys.maxsize
for i in range(len(nums)):
if nums[i] < m:
m = nums[i]
elif nums[i] - m > maxpro:
maxpro = nums[i] - m
return maxpro
#solution from leetcode discussions:
def maxProfit(nums):
l = 0
r = 1
maxp = 0
while r < len(nums):
curprofit = nums[r] - nums[l]
if nums[l] < nums[r]:
maxp = max(curprofit, maxp)
else:
l = r
r+=1
print(maxp)
|
'''
You are given the head of a linked list.
Remove every node which has a node with a strictly greater value anywhere to the right side of it.
Return the head of the modified linked list.
'''
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse(n: ListNode) -> ListNode:
tail = None
while n:
nxt = n.next
n.next = tail
tail = n
n = nxt
return tail
cur = tail = reverse(head)
mx = cur.val
while cur.next:
if cur.next.val < mx:
cur.next = cur.next.next
else:
cur = cur.next
mx = cur.val
return reverse(tail)
----------------------------------------------------------------------
def removeNodes(self, head):
if not head: return None
head.next = self.removeNodes(head.next)
if head.next and head.val < head.next.val:
return head.next
return head
----------------------------------------------------------------------------------------
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(inf)
stack = [dummy]
while head:
while stack and head.val > stack[-1].val:
stack.pop()
stack[-1].next = head
stack.append(head)
head = head.next
return dummy.next
|
'''
На вход подается массив arr состоящий из
произвольного количества кортежей, в каждом из которых
также содержится произвольное количество элементов. Необходимо написать фукнцию flat, которая будет возвращать список из всех элементов, входящих в состав каждого кортежа.
'''
import itertools
class Answer:
def flat(self, arr):
return list(itertools.chain(*arr))
---------------------------------
class Answer:
def flat(self, arr):
new_foods = []
for sublist in arr:
for food in sublist:
new_foods.append(food)
return (new_foods)
--------------------------------------------
class Answer:
def flat(self, arr):
new_foods = [food for sublist in arr for food in sublist]
return (new_foods)
|
'''
You are given an integer n. A perfectly straight street is represented by a number line ranging from 0 to n - 1. You are given a 2D integer array lights representing the street lamp(s) on the street. Each lights[i] = [positioni, rangei] indicates that there is a street lamp at position positioni that lights up the area from [max(0, positioni - rangei), min(n - 1, positioni + rangei)] (inclusive).
The brightness of a position p is defined as the number of street lamps that light up the position p. You are given a 0-indexed integer array requirement of size n where requirement[i] is the minimum brightness of the ith position on the street.
Return the number of positions i on the street between 0 and n - 1 that have a brightness of at least requirement[i].
'''
'''
Instead of thinking about it as "the light is at index i and has a radius of r" -- once you calculate where the light starts and ends from those positions -- you can reframe it as "the light starts at position start and ends at position end.
Therefore, you can just create an array that keeps track of where the intensity increases (+1) and decreases (-1), and then do a prefix sum over that array and crossreference it with the requirements array after.
'''
class Solution:
def meetRequirement(self, n: int, lights: List[List[int]], requirement: List[int]) -> int:
helper = [0] * (n + 1)
for pos, _range in lights:
helper[max(0, pos - _range)] += 1
helper[min(n, pos + 1 + _range)] -= 1
counter = 0
res = 0
for i in range(n):
counter += helper[i]
if counter >= requirement[i]:
res += 1
return res
-----------------
class Solution:
def meetRequirement(self, n: int, lights: List[List[int]], requirement: List[int]) -> int:
lightsRange = [0] * (n + 1)
res = 0
for pos, ran in lights:
lightsRange[max(0, pos - ran)] += 1
lightsRange[min(n - 1, pos + ran) + 1] -= 1
for i in range(n):
lightsRange[i + 1] += lightsRange[i]
if lightsRange[i] >= requirement[i]:
res += 1
return res
|
'''
The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
'''
class Solution:
#example 1
#result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]
\ / \ / \ /
# (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5))
\ | /
\ | /
\ | /
\ | /
# ((1^2^3) & (6^5))
def getXORSum(self, a, b):
x = 0
for i in range(len(a)):
x = x ^ a[i]
y = 0
for j in range(len(b)):
y = y ^ b[j]
return x & y
|
'''
Given a positive integer n, find the sum of all integers in the range [1, n] inclusive that are divisible by 3, 5, or 7.
Return an integer denoting the sum of all numbers in the given range satisfying the constraint.
'''
class Solution:
def sumOfMultiples(self, n: int) -> int:
res = 0
for i in range(1, n+1):
if i%3 == 0 or i%5==0 or i%7==0:
res+= i
return res
|
'''
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.
When writing such an expression, we adhere to the following conventions:
The division operator (/) returns rational numbers.
There are no parentheses placed anywhere.
We use the usual order of operations: multiplication and division happen before addition and subtraction.
It is not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.
'''
class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
@cache
def fn(val):
"""Return min ops to express val."""
if val < x: return min(2*val-1, 2*(x-val))
k = int(log(val)//log(x))
ans = k + fn(val - x**k)
if x**(k+1) < 2*val:
ans = min(ans, k + 1 + fn(x**(k+1) - val))
return ans
return fn(target)
-----------------------------------------------------------------------
# written by : Dhruv vavliya
x = 5
target = 501
from functools import lru_cache
@lru_cache(None)
def go(x,target):
if target == 1:
return 1 # 5/5 (only 1 possible soln)
op =0
current=x
while current < target:
current*=x # 5*5*5*5
op+=1
if current == target: # if target achieve
return op
# almost nearest target ,then increase
if op == 0: # 5/5 + .... (2 operations)
ans = 2 + go(x,target-1)
else:
ans = op + go(x,target-current//x) # (target-current) but current*5 extra multiplied
# increase than target, then decrease
if current-target < target: # if (current - target) lies outside of target then,only consider one case
ans = min(ans ,op+1 + go(x,current-target)) # op+1 for additionally *x then decrease
return ans
def express_number(x ,target):
return go(x,target)
print(express_number(x,target))
-----------------------------------------------------------------------------------------------------------------------------------
class Solution:
def solve(self,x,target):
if target in self.dp : return self.dp[target]
# when target == 1 we can solve just by doing x/x
if target == 1: return 1
# current value = x and operations performed = 0
cur = x
op = 0
# if cur < target : the best decision is to multiply
while cur < target:
cur *= x
op += 1
# if cur == target : we reached using minimum possible operations
if cur == target :
return op
if op == 0:
# cur is already larger than target
# x/x + make(target-1) : make 2 operations + solve(target-1)
ans = 2 + self.solve(x,target - 1)
else:
# we try to reach nearest val via multiply less than target
# and find ans for remaining i.e. target - cur/x
# here op becomes op - 1 so op - 1 + 1 becomes op
ans = op + self.solve(x,target-(cur//x))
if cur - target < target :
# diff between cur and target is less than target
# i.e. we can make cur and remove cur - target
tmp = op + 1 + self.solve(x,cur - target)
if tmp < ans : ans = tmp
# finally use dp for memoization
self.dp[target] = ans
return ans
|
'''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo 109 + 7.
'''
class Solution:
mod = 1000000007
def solve(self,dp,s,i):
if i==len(s):
return 1
if i> len(s):
return 0
if dp[i] != -1:
return dp[i]
if s[i] == "0":
dp[i] =0
return dp[i]
one = 0
if s[i] == '*':
one += (9*self.solve(dp,s,i+1))% self.mod
else:
one += self.solve(dp,s,i+1)
two = 0
if i+1 < len(s):
if s[i+1]=='*':
if s[i]=='*':
two += (15*self.solve(dp,s,i+2))% self.mod
elif s[i] <'2':
two += (9*self.solve(dp,s,i+2))% self.mod
elif s[i] == '2':
two += (6*self.solve(dp,s,i+2))% self.mod
else:
if s[i] == "*" and s[i+1]<'7':
two += (2*self.solve(dp,s,i+2))% self.mod
elif s[i] <'2' or (s[i] == '2' and s[i+1] <'7'):
two += self.solve(dp,s,i+2)
dp[i] = ((one % self.mod + two % self.mod)%self.mod)
return dp[i]
def numDecodings(self, s: str) -> int:
n = len(s)
dp = [-1]*(n+1)
return self.solve(dp,s,0)
|
'''
Given a non-negative integer num, Return its encoding string.
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:
'''
class Solution:
def encode(self, num: int) -> str:
return str(bin(num+1))[3:]
---------------------
class Solution:
def encode(self, n: int) -> str:
def addbin(a,b):
if len(a) > len(b):
return addbin(b,a)
diff=len(b)-len(a)
j = ''.join(['0' for _ in range(diff)])
a=j+a
carry='0'
res = []
for i in range(len(b)-1,-1,-1):
if a[i]=='1' and b[i]=='1' :
if carry=='0' :
res.append('0')
carry='1'
else :
res.append('1')
carry='1'
if a[i]=='0' and b[i]=='0' :
if carry=='0' :
res.append('0')
carry='0'
else :
res.append('1')
carry='0'
if a[i]!=b[i] :
if carry=='1' :
res.append('0')
carry='1'
else :
res.append('1')
carry='0'
if carry=='1' :
res.append('1')
res.reverse()
return ''.join(res)
if (n&(n+1))==0 :
return "0"*(int(log(n+1,2)))
i=0
while (1<<i) < n :
i+=1
if (1<<i) > n : i-=1
B="0"*(i)
return addbin(bin(n-(1<<i)+1)[2:],B)
They key in this approach is :
If n is of the form (2^x)-1 { n&(n+1) = 0 } then we simply return 'x' zeroes
We take the biggest power of 2 <= n and add number of zeroes (example in 23 biggest power is 16 so we take 4 zeroes)
Now take difference of biggest power and n+1
Perform binary addition of this difference with the initial x '0' string
Example :
n = 23
biggest power of 2 = 16
so base string = 0000
difference = 24-16 = 8 = 1000
binary addition of 0000 and 1000 = 1000
Answer = 1000
Do Upvote if you understood and found this approach better
|
'''
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree
nodes with value val as cur's left subtree root and right subtree root.
cur's original left subtree should be the left subtree of the new left subtree root.
cur's original right subtree should be the right subtree of the new right subtree root.
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with
value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
'''
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
if d == 1: return TreeNode(v, root, None)
elif d == 2:
root.left = TreeNode(v, root.left, None)
root.right = TreeNode(v, None, root.right)
else:
if root.left: self.addOneRow(root.left, v, d-1)
if root.right: self.addOneRow(root.right, v, d-1)
return root
----------------------------------------------------------------------------
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int, side = "left") -> TreeNode:
if d == 1:
res = TreeNode(v)
setattr(res, side, root)
return res
if root:
root.left = self.addOneRow(root.left, v, d - 1)
root.right = self.addOneRow(root.right, v, d - 1, 'right')
return root
|
'''
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
'''
def pruneTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.val == 0 and not root.left and not root.right:
return None
return root
|
'''
Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character
otherwise it is denoted by a '.' character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot
see the answers of the student sitting directly in front or behind him. Return the maximum number of
students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
'''
class Solution:
def maxStudents(self, seats: List[List[str]]) -> int:
m, n = len(seats), len(seats[0]) # dimensions
valid = []
for i in range(m):
val = 0
for j in range(n):
if seats[i][j] == ".": val |= 1 << j
valid.append(val)
@cache
def fn(i, mask):
"""Return max students taking seats[i:] given previous row as mask."""
if i == len(seats): return 0
ans = fn(i+1, 0)
for x in range(1 << n):
if x & valid[i] == x and (x >> 1) & x == 0 and (mask >> 1) & x == 0 and (mask << 1) & x == 0:
ans = max(ans, bin(x).count("1") + fn(i+1, x))
return ans
return fn(0, 0)
-----------------------------------------------------------------------------------------------------------------
# bitmask dp
# dp[i][mask]: maximum students in seats[:i+1] with valid mask in seats[i]
# dp[i][mask] = max(dp[i-1][mask'] + valid bit(mask))
# no adjacent students: x&(x>>1) == 0
# student on good seat: x&y == x (y = bit(seats[i]))
# can't see front guys: x&(y>>1) == 0 and (x>>1)&y == 0 (y = pre_mask)
class Solution:
def maxStudents(self, seats: List[List[str]]) -> int:
m, n = len(seats), len(seats[0])
dp = [collections.defaultdict(int) for _ in range(m+1)]
dp[-1][0] = 0
bits = []
for row in seats:
num = 0
for i in range(n):
num += (row[i]=='.')<<n-1-i
bits.append(num)
# print(bits)
for i in range(m):
for x in range(2**n):
for y in dp[i-1]:
if x&(x>>1) == 0 and x&bits[i] == x and x&(y>>1) == 0 and (x>>1)&y == 0:
dp[i][x] = max(dp[i][x], dp[i-1][y] + bin(x).count('1'))
return max(dp[m-1][x] for x in dp[m-1])
|
'''
Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
'''
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
# keep track of longest univalue path
longest_uni_path = 0
def helper( node):
if not node:
return 0
else:
path_of_left = helper( node.left )
path_of_right = helper( node.right )
# if left node has the same value, extend uni path
left_uni = path_of_left+1 if node.left and node.left.val == node.val else 0
# if right node has the same value, extend uni path
right_uni = path_of_right+1 if node.right and node.right.val == node.val else 0
nonlocal longest_uni_path
# use node as bridge to make uni_path as long as possible
longest_uni_path = max( longest_uni_path, left_uni + right_uni )
return max(left_uni, right_uni)
#------------------------------------------------
helper( root )
return longest_uni_path
|
'''
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the FreqStack class:
FreqStack() constructs an empty frequency stack.
void push(int val) pushes an integer val onto the top of the stack.
int pop() removes and returns the most frequent element in the stack.
If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
'''
class FreqStack:
def __init__(self):
self.stacks = dict()
self.d = dict()
self.maxc = 0
def push(self, val: int) -> None:
if val not in self.d:
self.d[val] = 1
else:
self.d[val] +=1
valc = self.d[val]
if valc > self.maxc:
self.maxc = valc
self.stacks[valc] = []
self.stacks[valc].append(val)
def pop(self) -> int:
res = self.stacks[self.maxc].pop()
self.d[res] -=1
if not self.stacks[self.maxc]:
self.maxc -=1
return res
------------------------------------------------------------
#with heap and defaultdict
class FreqStack:
def __init__(self):
self.cnt = defaultdict(lambda:0)
self.heap = []
self.idx=0
def push(self, val: int) -> None:
self.cnt[val]+=1
self.idx+=1
heappush(self.heap, (-self.cnt[val], -self.idx,val))
def pop(self) -> int:
_, _, val = heappop(self.heap)
self.cnt[val] -=1
return val
------------------------------------------------------------------------
class FreqStack:
def __init__(self):
self.stks = []
self.freq = defaultdict(int)
def push(self, val: int) -> None:
self.freq[val] += 1
if self.freq[val] > len(self.stks):
self.stks.append([val])
else:
self.stks[self.freq[val]-1].append(val)
def pop(self) -> int:
val = self.stks[-1].pop()
if not self.stks[-1]:
self.stks.pop()
self.freq[val] -= 1
return val
|
'''
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.
In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).
Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.
'''
class Solution:
def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:
n = len(passingFees)
mat = {}
for x, y, time in edges:
if x not in mat: mat[x] = set()
if y not in mat: mat[y] = set()
mat[x].add((y, time))
mat[y].add((x, time))
h = [(passingFees[0], 0, 0)]
visited = set()
while h:
fees, time_so_far, city = heappop(h)
if time_so_far > maxTime: continue
if city == n - 1: return fees
if (city, time_so_far) in visited: continue
visited.add((city, time_so_far))
for nxt, time_to_travel in mat[city]:
# Check if we are retracing a visited path
if (nxt, time_so_far - time_to_travel) in visited: continue
heappush(h, (fees + passingFees[nxt], time_so_far + time_to_travel, nxt))
return -1
-------------------------------------------------------------------------------------------------
class Solution:
def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:
n = len(passingFees)
fee = [float("inf") for i in range(n)]# the final fee
heap, graph = [(0, passingFees[0], 0)], collections.defaultdict(list)
for start, end, time in edges:
graph[start].append((end, time))
graph[end].append((start, time))
while heap:
curTime, curFee, curNode = heappop(heap)
if fee[curNode] <= curFee:
continue
fee[curNode] = curFee
for neighbor, time in graph[curNode]:
if time + curTime <= maxTime:
heappush(heap, (time + curTime, curFee + passingFees[neighbor], neighbor))
return fee[-1] if fee[-1] != float("inf") else -1
|
'''
Given a binary string s, return the number of substrings
with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.
'''
def numSub(self, s: str) -> int:
ans = cum = 0
for x in s:
if x == "1":
cum+=1
ans+=cum
else:
cum = 0
return ans%(10**9+7)
-----------------------------------------------------------------------------------------------
class Solution:
def numSub(self, s: str) -> int:
cnt, ans = 0, 0
for i in range(len(s)):
if s[i] == '0':
cnt = 0
else:
cnt += 1
ans += cnt
return ans % ((10**9)+7)
--------------------------------------------------------------
The example would be self explanatoy:
"0110111" can be evaluated to -->
0120123
Now if we sum up all these digits:
1+2+1+2+3 = 9 is the result!
class Solution(object):
def numSub(self, s):
res, currsum = 0,0
for digit in s:
if digit == '0':
currsum = 0
else:
currsum += 1
res+=currsum
return res % (10**9+7)
|
'''
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.
In one move, you can either:
Increment the current integer by one (i.e., x = x + 1).
Double the current integer (i.e., x = 2 * x).
You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.
Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.
'''
class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
moves = 0
while maxDoubles > 0 and target > 1:
if target % 2 == 1:
target -= 1
else:
target //= 2
maxDoubles -= 1
moves += 1
moves += target - 1
return moves
--------------------------------------------------------------------------------------------
class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
moves = 0
while target != 1:
if target %2 == 0 and maxDoubles!= 0:
target =target//2
maxDoubles -=1
moves+=1
else:
if maxDoubles == 0:
moves += target-1
target = 1
else:
target -=1
moves += 1
return moves
|
'''
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
'''
class Solution:
def peakIndexInMountainArray(self, A: List[int]) -> int:
m = max(A)
return A.index(m)
|
'''
You are given two string arrays words1 and words2.
A string b is a subset of string a if every letter in b occurs in a including multiplicity.
For example, "wrr" is a subset of "warrior" but is not a subset of "world".
A string a from words1 is universal if for every string b in words2, b is a subset of a.
Return an array of all the universal strings in words1. You may return the answer in any order.
'''
#bad code
class Solution:
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
w1 = Counter(words1)
w2 = Counter(words2)
res = []
for i in range(len(words1)):
curw1 = words1[i]
curw1_counter = Counter(curw1)
flag = True
word_to_check = None
for j in range(len(words2)):
curw2 = words2[j]
curw2_counter = Counter(curw2)
word_to_check = curw2
if list(curw2_counter.values()) != list(curw1_counter.values()):
flag = False
if flag:
res.append(word_to_check)
return res
--------------------------------------------------------------------------------------------------
class Solution:
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
ans = set(words1)
letters = {}
for i in words2:
for j in i:
count = i.count(j)
if j not in letters or count > letters[j]:
letters[j] = count
for i in words1:
for j in letters:
if i.count(j) < letters[j]:
ans.remove(i)
break
return list(ans)
-----------------------------------------------------------------------------------------
Now, that we understand the concepts involved and have better understanding of the solution. Let's look at ways to solve that,
Brute force [Time Limit Exceeded]
The trivial way to solve the problem can be described with following steps,
result = []
for every word a in A
for every word b in B check if that's subset of B
if true, then a is universal word
Add a to result
return result
Below is the simple python implementation for above algorithm,
class Solution:
def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
counters = defaultdict(dict)
# put all word feq maps in counters
for word_a in A:
counters[word_a] = Counter(word_a)
for word_b in B:
counters[word_b] = Counter(word_b)
def isSubset(a, b) -> bool: # check if b is subset of a
counter_a = counters[a]
counter_b = counters[b]
# if counter_b has more keys then it can't be subset of a
if len(counter_b.keys()) > len(counter_a.keys()):
return False
# can't be subset if any key in counter_b is not present in counter_a
# or if the freq doesn't match
for key in counter_b.keys():
if (key not in counter_a.keys()) or (counter_a[key] < counter_b[key]):
return False
# that means word b is subset of word a
return True
result = []
for word_a in A:
universal = True
for word_b in B:
if not isSubset(word_a,word_b):
universal = False
break
if universal:
result.append(word_a)
return result
|
'''
Given an integer n, return a list
of integers from 1 to n as strings except
for multiples of 3 use “Fizz” instead of the
integer and for the multiples of 5 use “Buzz”. For integers
which are multiples of both 3 and 5 use “FizzBuzz”.
'''
class Solution:
def solve(self, n):
res = list()
for i in range(1, n+1):
if i %3 == 0 and i %5 != 0:
res.append('Fizz')
elif i %5 == 0 and i %3 != 0:
res.append('Buzz')
elif i %3 == 0 and i % 5 ==0:
res.append('FizzBuzz')
else:
res.append(str(i))
return res
|
'''
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
'''
#my own solution - O(nlogn)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
res = nums[-k]
return res
#many other follow ups possible?!
# O(k+(n-k)lgk) time, min-heap
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1]
# max - heap - #1
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
ans = heapq.nlargest(k, nums) # run time O(n+klgn)
return ans[-1]
|
'''
Толя-Карп запросил для себя n посылок с «Аллигатор-экспресс».
Посылка представляет из себя ящик. Внутри ящика лежит целое число ai. Номер на ящике di указывает на цвет числа, лежащего внутри.
Толю-Карпа интересует, чему будут равны значения чисел, если сложить между собой все те, что имеют одинаковый цвет. Напишите, пожалуйста, программу, которая выводит результат.
'''
if __name__ == "__main__":
n = int(input())
d = dict()
for _ in range(n):
current = list(map(int, input().split()))
color_num = current[0]
cur = current[1]
if color_num not in d.keys():
d[color_num] = cur
else:
d[color_num] += cur
d = d.items()
sorted_d = list(sorted(d))
for item in sorted_d:
for j in item:
print(j, end=' ')
print()
|
'''
Given the root of a binary tree, return the length of the longest consecutive path in the tree.
A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.
For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid.
On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
'''
def longestConsecutive(self, root):
return max(self.get_max(root))
def get_max(self, root):
"""Return max increasing and max decreasing ending at root, and max overall."""
if not root:
return 0, 0, 0
inc, dec = 1, 1
li, ld, lt = self.get_max(root.left)
ri, rd, rt = self.get_max(root.right)
if root.left:
if li and root.left.val - root.val == 1:
inc = li + 1
if ld and root.left.val - root.val == -1:
dec = ld + 1
if root.right:
if ri and root.right.val - root.val == 1:
inc = max(inc, ri + 1)
if rd and root.right.val - root.val == -1:
dec = max(dec, rd + 1)
return inc, dec, max(inc + dec - 1, lt, rt)
----------------------------------------------------------------
inc: the longest increasing consecutive sequence started at root.
dec: the longest decreasing consecutive sequence started at root.
out: the longest consecutive sequence 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 longestConsecutive(self, root: Optional[TreeNode]) -> int:
inc, dec, out = self.helper(root)
return out
def helper(self, root):
if root:
l_inc, l_dec, l_out = self.helper(root.left)
r_inc, r_dec, r_out = self.helper(root.right)
inc = 1; dec = 1; out = 1
if l_inc and root.left.val + 1 == root.val:
inc = max(inc, l_inc + 1)
if r_inc and root.right.val + 1 == root.val:
inc = max(inc, r_inc + 1)
if l_dec and root.left.val - 1 == root.val:
dec = max(dec, l_dec + 1)
if r_dec and root.right.val - 1 == root.val:
dec = max(dec, r_dec + 1)
out = max(l_out, r_out, inc, dec)
if inc == l_inc + 1 and dec == r_dec + 1:
out = max(out, l_inc + 1 + r_dec)
if dec == l_dec + 1 and inc == r_inc + 1:
out = max(out, l_dec + 1 + r_inc)
return inc, dec, out
return 0, 0 , 0
-------------------------------------------
# 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 longestConsecutive(self, root: Optional[TreeNode]) -> int:
##longest seq
##every node can have asc and desc on 2 branches
##answer = (asc-chain) + (desc-chain)
ans = 0
@lru_cache(None)
def asc(root,prev_val):##finding the maximum length ascending sequence for the current node
if root is None:
return 0
elif root.val != prev_val+1:
return 0
elif root.val == prev_val + 1:
return 1 + max(asc(root.left,root.val), asc(root.right,root.val))
@lru_cache(None)
def desc(root,prev_val):##finding the maximum length descdending sequence for the current node
if root is None:
return 0
elif root.val!=prev_val-1:
return 0
elif root.val == prev_val -1:
return 1 + max(desc(root.left,root.val),desc(root.right,root.val))
q = [root]
while q:
for x in range(len(q)):
node = q.pop(0)
##-1 as root node will be counted twice
ans = max(ans, asc(node,node.val-1) + desc(node,node.val+1) - 1)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return ans
--------------------------------------------------
def longestConsecutive(self, root: TreeNode) -> int:
def longest_path(root):
if not root:
return 0, 0
inc, dec = 1, 1
l_inc, l_dec = longest_path(root.left)
r_inc, r_dec = longest_path(root.right)
if root.left:
if root.left.val == root.val + 1:
inc = max(inc, 1 + l_inc)
if root.left.val == root.val - 1:
dec = max(dec, 1 + l_dec)
if root.right:
if root.right.val == root.val + 1:
inc = max(inc, 1 + r_inc)
if root.right.val == root.val - 1:
dec = max(dec, 1 + r_dec)
res[0] = max(res[0], inc + dec - 1)
return (inc, dec)
res = [0]
longest_path(root)
return res[0]
----------------------------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
longest = 0
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.dfs(root)
return self.longest
def dfs(self, node):
if node is None:
return (0, 0)
left, right = node.left, node.right
l_inc, l_dec = self.dfs(left)
r_inc, r_dec = self.dfs(right)
n_inc = n_dec = 1
if left and left.val + 1 == node.val:
n_inc = l_inc + 1
if right and right.val + 1 == node.val:
n_inc = max(n_inc, r_inc + 1)
if left and left.val - 1 == node.val:
n_dec = l_dec + 1
if right and right.val - 1 == node.val:
n_dec = max(n_dec, r_dec + 1)
self.longest = max(self.longest, n_inc + n_dec - 1)
return(n_inc, n_dec)
|
# Given a sorted array, A, with possibly duplicated elements,
# find the indices of the first and last occurrences of a
# target element, x. Return -1 if the target is not found.
def first_last(l, target):
res = list()
for i in range(len(l)):
if l[i] == target:
if len(res) == 0:
res.append(i)
elif len(res) == 1:
res.append(i)
else:
res = res[:-1]
res.append(i)
if len(res) == 0:
print([-1,-1])
elif len(res) == 1:
print(res*2)
else:
print(res)
r = []
t = 2
first_last(r,t)
#ugly solution - first
def first_last(l, target):
first_found = False
second_found = False
res = list()
for i in range(len(l)):
if l[i] == target:
if first_found == False:
first_found = True
res.append(i)
elif second_found == False:
second_found = True
res.append(i)
elif second_found:
res.append(i)
if first_found == False:
print([-1,-1])
else:
if len(res) > 2:
print(res[0], res[-1])
else:
print(res)
r = [2,2,3,4,5,2]
t = 2
first_last(r,t)
|
'''
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
'''
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
freqDict = defaultdict(int)
maxFreq = 0
maxLength = 0
start = end = 0
while end < len(s):
freqDict[s[end]] += 1
# maxFreq may be invalid at some points, but this doesn't matter
# maxFreq will only store the maxFreq reached till now
maxFreq = max(maxFreq, freqDict[s[end]])
# maintain the substring length and slide the window if the substring is invalid
if ((end-start+1) - maxFreq) > k:
freqDict[s[start]] -= 1
start += 1
else:
maxLength = max(maxLength, end-start+1)
end += 1
return maxLength
|
'''
A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10
as shown in the figure above.
Given the array reservedSeats containing the numbers of seats already
reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.
Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group
occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not
considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in
that case, the aisle split a four-person group in the middle, which means to have two people on each side.
'''
class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
s = {}
for x in reservedSeats:
if x[0] not in s.keys():
s[x[0]] = [0,0,0]
if x[1] in [2,3,4,5]:
s[x[0]][0] = 1
if x[1] in [6,7,8,9]:
s[x[0]][2] = 1
if x[1] in [4,5,6,7]:
s[x[0]][1] = 1
ans = 0
for k in s.keys():
ans += 2 if s[k][0] == 0 and s[k][2] == 0 else 1 if s[k].count(0) > 0 else 0
return ans + (n - len(s.keys())) * 2
---------------------------------------------------------
class Solution(object):
def maxNumberOfFamilies(self, n, reservedSeats):
"""
:type n: int
:type reservedSeats: List[List[int]]
:rtype: int
"""
d = collections.defaultdict(list)
# possible seats for family
f1 = [2,3,4,5]
f2 = [4,5,6,7]
f3 = [6,7,8,9]
res = 0
# fill the dictionary, row as a key and reserved seats as a list
for i in range(len(reservedSeats)):
d[reservedSeats[i][0]].append(reservedSeats[i][1])
# f as a flag to check how many families in a row
for v in d.values():
f = [1,1,1]
for seat in v:
# if reserved seat related to f1 or f2 or f3, set flag 0
if seat in f1:
f[0] = 0
if seat in f2:
f[1] = 0
if seat in f3:
f[2] = 0
# it is not possible 2 more families in a row
if f[0] == 1 or f[2] == 1:
f[1] = 0
# cumulate the number of families in the current row
res += sum(f)
# calculate the number of row that not including reserved seats
# we can skip these rows and just calculate numbers
remain = (n - len(d)) * 2
return res + remain
|
'''
You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree.
A binary search tree is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
order[0] will be the root of the binary search tree.
All subsequent elements are inserted as the child of any existing node such that the binary search tree properties hold.
Return the depth of the binary search tree.
A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
'''
from sortedcontainers import SortedList
class Solution:
def maxDepthBST(self, order: List[int]) -> int:
ans = 0
mp, sl = {}, SortedList()
for x in order:
k = sl.bisect_left(x)
val = 1
if k: val = 1 + mp[sl[k-1]]
if k < len(sl): val = max(val, 1 + mp[sl[k]])
ans = max(ans, val)
sl.add(x)
mp[x] = val
return ans
from sortedcontainers import SortedDict
class Solution:
def maxDepthBST(self, order: List[int]) -> int:
sd = SortedDict()
for x in order:
k = sd.bisect_left(x)
val = 1
if k: val = 1 + sd.values()[k-1]
if k < len(sd): val = max(val, 1 + sd.values()[k])
sd[x] = val
return max(sd.values())
---------------------------------------------------------------------------------------------
Since all elements are unique and within [1..n], we can represent our tree as intervals.
We start with [1..n] interval, and the depth of that interval is 0. When we insert, say, 3, we split that interval into two: [1..2] and [4..n], and increment their depth. For any value, we can quickly find it's interval using binary search.
The picture below demonstrates how we split intervals for this test case: [3,5,1,2,6,7,4]
image
To model this logic, we can use a map to store numbers and their depth. When we insert a new number, we first find the insert position (O(n log )). Then, we get the depth of numbers on the left and right (our interval). Finally, we insert a new value, and its depth is the maximum depth of the neighbours, plus 1.
C++
int maxDepthBST(vector<int>& order) {
map<int, int> m{{0, 0}, {100001, 0}};
for (int i : order) {
auto it = m.upper_bound(i);
m[i] = 1 + max(it->second, prev(it)->second);
}
return max_element(begin(m), end(m), [](const auto& a, const auto &b){ return a.second < b.second; })->second;
}
Java
public int maxDepthBST(int[] order) {
TreeMap<Integer, Integer> m = new TreeMap<>();
for (int i : order) {
Map.Entry<Integer, Integer> l = m.floorEntry(i), r = m.ceilingEntry(i);
m.put(i, 1 + Math.max(l == null ? 0 : l.getValue(), r == null ? 0 : r.getValue()));
}
return m.entrySet().stream().max((a, b) -> a.getValue().compareTo(b.getValue())).get().getValue();
}
Python 3
This also works with standard bisect_left; it's just faster with sortedcontainers.
class Solution:
def maxDepthBST(self, order: List[int]) -> int:
from sortedcontainers import SortedList
sl, d = SortedList([0, 100001]), { 0 : 0, 100001 : 0 }
for i in order:
j = sl.bisect_left(i)
d[i] = 1 + max(d[sl[j - 1]], d[sl[j]])
sl.add(i)
return max(d.values())
--------------------------------------------------------------------------------------------------------------
Each value will be below its existing upper bould and lower bound, which even is lower in the tree
from sortedcontainers import SortedDict
class Solution:
def maxDepthBST(self, order: List[int]) -> int:
# python way for binary treemap
depths = SortedDict()
# add dummy bounds to avoid extra ifs
depths[-math.inf] = 0
depths[math.inf] = 0
# for every value find bounds and take the lowest depth + 1
# put the value back to depths
for x in order:
i = depths.bisect_left(x)
depths[x] = 1 + max(depths.values()[i - 1:i + 1])
# return the maximum value so far
return max(depths.values())
--------------------------------------------------------------------
class Solution:
def maxDepthBST(self, order: List[int]) -> int:
que = []
depths = {}
for val in order:
res = 0
idx = bisect.bisect(que, val)
if idx != 0:
res = max(res, depths[que[idx - 1]])
if idx != len(que):
res = max(res, depths[que[idx]])
que.insert(idx, val)
depths[val] = res + 1
return max(depths.values())
|
#An array is monotonic if it is either monotone increasing or monotone decreasing.
#An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
#Return true if and only if the given array A is monotonic.
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
inc = False
dec = False
for i in range(len(A)-1):
if inc:
if A[i] > A[i+1]:
#print('found decreasing! wrong!')
return False
if dec:
if A[i] < A[i+1]:
#print('found increasing! wrong!')
return False
if A[i] == A[i+1]:
continue
elif A[i] > A[i+1]:
dec=True
elif A[i] < A[i+1]:
inc = True
if inc == False and dec == False:
#print('same values')
return True
if inc:
#print('increasing arr - ok')
return True
if dec:
#print('decreasing arr - ok')
return True
|
'''
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases are generated so that the answer fits in a 32-bit integer.
'''
Why does this work?
First, we need to add the first element of the array. There are no prior elements to leech off of.
Then consider any successive element. We can "reuse" up to the value
of the previous element by simply extending the subarray we're adding to by one. Anything more than that, we need to increment.
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
return sum(max(target[i - 1] - target[i], 0) for i in range(1, len(target))) + target[-1]
|
'''
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
'''
class Solution:
def preorder(self, root: 'Node') -> List[int]:
def rec(root):
if root:
out.append(root.val)
for c in root.children:
rec(c)
#out.append(root.val)
out = []
rec(root)
return out
pakilamak's avatar
pakilamak
474
Last Edit: August 11, 2020 11:59 PM
2.8K VIEWS
Recursive Solution: Runtime: 36 ms, faster than 97.16%
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
output =[]
# perform dfs on the root and get the output stack
self.dfs(root, output)
# return the output of all the nodes.
return output
def dfs(self, root, output):
# If root is none return
if root is None:
return
# for preorder we first add the root val
output.append(root.val)
# Then add all the children to the output
for child in root.children:
self.dfs(child, output)
Iterative Solution- Runtime: 40 ms, faster than 91.86%
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root is None:
return []
stack = [root]
output = []
# Till there is element in stack the loop runs.
while stack:
#pop the last element from the stack and store it into temp.
temp = stack.pop()
# append. the value of temp to output
output.append(temp.val)
#add the children of the temp into the stack in reverse order.
# children of 1 = [3,2,4], if not reveresed then 4 will be popped out first from the stack.
# if reversed then stack = [4,2,3]. Here 3 will pop out first.
# This continues till the stack is empty.
stack.extend(temp.children[::-1])
#return the output
return output
|
#my annoying solution
'''
Your code needs to read the
current time from the standard input stream (console). The input
format is such as hh:mm:ss, which represents hour, minute, and second respectively, and
then a positive integer x is given to find the elapsed time. The time after x seconds is
expressed, and the result is calculated and printed to the standard output stream (console).
'''
s = input()
x = int(input())
s = s.strip('\r')
s = s.split(':')
s = list(map(int, s))
totalsec = s[0]*60*60 + s[1] * 60 + s[2]
#print('before, just the original time in sec', totalsec)
totalsec +=x
#print('after , with x time', totalsec)
#back to h:m:s
h, rest = divmod(totalsec,3600)
if h > 23:
h = h%24
#print(h,rest)
m, rest = divmod(rest, 60)
#print(m,rest)
sec = rest
# print('seconds')
# print(sec)
if len(str(h)) < 2:
h = '0'+str(h)
if len(str(m)) <2:
m = '0' + str(m)
if len(str(sec))<2:
sec = '0' + str(sec)
res = str(h) + ':' + str(m)+':' + str(sec)
print(res)
-------------------------------------------------
time = input()
x = int(input())
h = int(time.split(":")[0])
m = int(time.split(":")[1])
s = int(time.split(":")[2])
ss = ((h*3600+m*60+s+x) % 3600) % 60 # 秒,60进制。总秒数对小时取余剩分,再对分取余剩秒。因为取余了,所以秒位不会溢出
mm = int(((h*3600+m*60+s+x-ss) % 3600) / 60) # 分,60进制。先去除秒位上的秒数,剩下的秒数对小时取余,剩下的都是分位上的整秒数,再除就是分。因为取余了,所以分位不会溢出
hh = int(((h*3600+m*60+s+x-ss-mm*60) / 3600) % 24) # 时,24进制。先去除秒位和分位上的秒数,剩下的都是时位上的整秒数,再除就是时,用它的进制取余就是时。因为是第一个位数,所以会溢出,要取余
print("{:0>2d}:{:0>2d}:{:0>2d}".format(hh, mm, ss))
---------------------------------------
s = input().replace('\r', '').split(':')
x = int(input())
a = []
for i in s:
a.append(int(i))
b = a[0]*60*60+a[1]*60+a[2]+x
e=b//3600
if e > 24:
e = e%24
c = b%3600//60
d = b%3600%60
print("%02d:%02d:%02d"%(e,c,d))
|
'''
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.
During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
If ever the Cat occupies the same node as the Mouse, the Cat wins.
If ever the Mouse reaches the Hole, the Mouse wins.
If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a graph, and assuming both players play optimally, return
1 if the mouse wins the game,
2 if the cat wins the game, or
0 if the game is a draw.
'''
class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
@functools.lru_cache(maxsize=None)
def move(mouse, cat, turn):
if turn >= len(graph)*2: return 0
if turn % 2:
ans = 2
for position in graph[mouse]:
if position == cat: continue
if position == 0: return 1
result = move(position, cat, turn+1)
if result == 1: return 1
if result == 0: ans=0
return ans
else:
ans = 1
for position in graph[cat]:
if position == 0: continue
if position == mouse: return 2
result = move(mouse, position, turn+1)
if result == 2: return 2
if result == 0: ans = 0
return ans
return move(1,2,1)
---------------------------------------------------------------------------
from functools import lru_cache
class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
n = len(graph)
degree = [[[0 for k in range(3)] for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
degree[i][j][1] += len(graph[i])
degree[i][j][2] += len(graph[j])
if 0 in graph[j]:
degree[i][j][2] -= 1 # cat cannot go to the hole 0!
# Push the winning state into the queue, and look for their parents
dq = deque()
win = [[[0 for k in range(3)] for j in range(n)] for i in range(n)]
for i in range(1, n):
for k in range(1,3):
win[0][i][k] = 1
dq.append([0,i,k,1])
win[i][i][k] = 2
dq.append([i,i,k,2])
while dq:
m, c, t, w = dq.popleft()
parents = []
if t == 1:
for parent in graph[c]:
if parent != 0:
parents.append([m, parent, 2]) # cat cannot come from the hole 0!
else:
for parent in graph[m]:
parents.append([parent, c, 1])
for mp, cp, tp in parents:
# we are only interested in dealing with the potential draws
if win[mp][cp][tp] == 0:
# it's mouse turn and mouse would win if it makes the move; same for cat
if tp == w:
win[mp][cp][tp] = w
dq.append([mp, cp, tp, w])
else:
degree[mp][cp][tp] -= 1
if degree[mp][cp][tp] == 0:
win[mp][cp][tp] = w
dq.append([mp, cp, tp, w])
#print(win)
return win[1][2][1]
|
'''
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
'''
class Solution:
def validPalindrome(self, s: str) -> bool:
l = 0
r = len(s)-1
while l <= r:
if s[l] != s[r]:
s1 = s[:l] + s[(l+1):]
s2 = s[:r] + s[(r+1):]
return s1 == s1[::-1] or s2 == s2[::-1]
l += 1
r -= 1
return True
|
'''
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".
'''
class Solution:
def longestDupSubstring(self, s: str) -> str:
"""
This problem can be solved using Sliding Window Technique.
Logic:
1. Iterate over the string from 0th index
2. For each index, define a window of 1 initially.
3. Check for the existence of the window in the remaining string:
a. If found, increase the size of window by 1 and repeat.
b. Else Goto next index. For next index, the size window will not start by 1 again as we have already found for 1. So for every next index, size of window will start from the size at previous index to avoid checking for repeating size.
"""
ans = ""
j = 1
for i in range(len(s)):
window = s[i:i+j]
heystack = s[i+1:]
while window in heystack:
ans = window
j += 1
window = s[i:i+j]
return ans
-----------------------------------------------------------------------------------------------
class Solution:
def longestDupSubstring(self, s: str) -> str:
ans = ''
j = 1
for i in range(len(s)):
longest = s[i:i+j]
temp = s[i+1:]
while longest in temp:
ans = longest
j += 1
longest = s[i:i+j]
return ans
|
'''
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.
If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.
'''
class Solution(object):
def canCross(self, stones):
n = len(stones)
stoneSet = set(stones)
visited = set()
def goFurther(value,units):
if (value+units not in stoneSet) or ((value,units) in visited):
return False
if value+units == stones[n-1]:
return True
visited.add((value,units))
return goFurther(value+units,units) or goFurther(value+units,units-1) or goFurther(value+units,units+1)
return goFurther(stones[0],1)
|
'''
You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.
To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.
Return the maximum money you can earn after cutting an m x n piece of wood.
Note that you can cut the piece of wood as many times as you want.
'''
class Solution:
def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
dp = [[0]*(n+1) for _ in range(m+1)]
for h, w, p in prices:
dp[h][w] = p
for i in range(1, m+1):
for j in range(1, n+1):
v = max(dp[k][j] + dp[i - k][j] for k in range(1, i // 2 + 1)) if i > 1 else 0
h = max(dp[i][k] + dp[i][j - k] for k in range(1, j // 2 + 1)) if j > 1 else 0
dp[i][j] = max(dp[i][j], v, h)
return dp[m][n]
------------------------------------------------------------------------------------------------------------------
#bottom up
def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
# use a dictionary to save size and prices
price_dict = {}
for pi, pj, price in prices:
price_dict[(pi, pj)] = price
# use dp to calculate the max sale price
# dp[1][1] represents [1,1,price] in prices
# therefore, we need (m+1)*(n+1) to represent the shapes since dp[i][0] and dp[0][j] are not valid shapes
dp = [[0]*(n+1) for i in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if (i,j) in price_dict:
dp[i][j] = price_dict[(i, j)]
# dp[i][j] is the max of all sub shapes
for ii in range(1,i//2+1):
x = dp[ii][j]+dp[i-ii][j]
if x>dp[i][j]:
dp[i][j] = x
for jj in range(1,j//2+1):
x = dp[i][jj]+dp[i][j-jj]
if x>dp[i][j]:
dp[i][j] = x
return dp[m][n]
|
#my code - actually good solution
if __name__ == "__main__":
l = list(map(int, input().split()))
min1 = l[0]
changed = False
for i in range(len(l)):
if l[i] < min1 and l[i] % 2 == 0:
changed = True
min1 = l[i]
if not changed:
print('no existe: -1')
else:
print('min even number in list is: %d' % min1)
#code based on idea from the lecture https://www.youtube.com/watch?v=SKwB41FrGgU&t=2s
if __name__ == "__main__":
l = list(map(int, input().split()))
ans = -1
for i in range(len(l)):
if l[i] %2 == 0 and (ans == -1 or ans > l[i]):
#we have not seen yet and changing it for the first time
ans = l[i]
print(ans)
|
'''
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choose one of the actions per day.
Given the integer n, return the minimum number of days to eat n oranges.
'''
class Solution:
def minDays(self, n):
@lru_cache(None)
def dfs(n):
if n<=1:
return n
opt1, opt2, opt3 = float("inf"), float("inf"), float("inf")
if n%3 == 0:
opt3 = dfs(n//3)
if n%2 == 0:
opt2 = dfs(n//2)
if n%2 or n%3:
opt1 = dfs(n-1)
return min(opt1,opt2,opt3) + 1
return dfs(n)
---------------------------------------------------------------------------------------------------------
class Solution:
def minDays(self, n: int) -> int:
ans = 0
q = [n]
visit = set()
visit.add(n)
while q:
for i in range(len(q)):
num = q.pop(0)
if num == 0:
return ans
if num and (num-1) not in visit:
visit.add(num-1)
q.append(num-1)
if num % 2 == 0 and num-(num//2) not in visit:
visit.add(num-(num//2))
q.append(num-(num//2))
if num % 3 == 0 and num-2*(num//3) not in visit:
visit.add(num-2*(num//3))
q.append(num-2*(num//3))
ans += 1
|
'''
You are given a list of integers cells, representing sizes of different cells. In each iteration, the two largest cells a and b interact according to these rules:
If a = b, they both die.
Otherwise, the two cells merge and their size becomes floor((a + b) / 3).
Return the size of the last cell or return -1 if there's no cell is remaining.
'''
import heapq
class Solution:
def solve(self, cells):
heap = []
heapq.heapify(heap)
for c in cells:
heapq.heappush(heap, -1*c)
while heap and len(heap) > 1:
a = -heapq.heappop(heap)
b = -heapq.heappop(heap)
if a != b:
q = math.floor((a+b)/3)
heapq.heappush(heap, -1*q)
#else:
#print('a = b so die!')
if len(heap) == 0:
return -1
return -heap[0]
---------------------------------------------------------------------
class Solution:
def solve(self, cells):
pq = [-cell for cell in cells]
heapq.heapify(pq)
while len(pq) > 1:
a, b = heapq.heappop(pq), heapq.heappop(pq)
if a != b:
heapq.heappush(pq, (-a - b) // 3 * -1)
return -1 if not pq else -pq[0]
|
'''
You are given a stream of points on the X-Y plane. Design an algorithm that:
Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.
Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.
An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.
Implement the DetectSquares class:
DetectSquares() Initializes the object with an empty data structure.
void add(int[] point) Adds a new point point = [x, y] to the data structure.
int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.
'''
class DetectSquares:
def __init__(self):
self.mapp = {}
def add(self, point: List[int]) -> None:
if tuple(point) not in self.mapp:
self.mapp[tuple(point)] = 0
self.mapp[tuple(point)] += 1
def count(self, point: List[int]) -> int:
res = 0
px,py = point
for x,y in self.mapp.keys():
if abs(px - x) != abs(py - y) or px == x or py == y:
continue
if (x,py) in self.mapp and (px,y) in self.mapp:
res += self.mapp[(x,py)] * self.mapp[(px,y)] * self.mapp[(x,y)]
return res
|
'''
You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
'''
class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
s = list(s)
stack = []
countAll = s.count(letter)
count = 0
for ind, i in enumerate(s):
while stack and stack[-1] > i:
if stack[-1] == letter and i != letter:
if countAll+count-1 < repetition:
break
if len(stack)+len(s)-ind-1 < k:
break
if stack[-1] == letter:
count-=1
stack.pop()
stack.append(i)
if i == letter:
count+=1
countAll-=1
temp = 0
while len(stack)+temp > k:
if stack[-1] == letter and count <= repetition:
temp+=1
if stack[-1] == letter:
count-=1
stack.pop()
return "".join(stack)+temp*letter
-------------------------------------------------------------------------------------------------------------
class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
rest = sum(x == letter for x in s)
stack = []
for i, x in enumerate(s):
while stack and stack[-1] > x and len(stack) + len(s) - i > k and (stack[-1] != letter or repetition < rest):
if stack.pop() == letter: repetition += 1
if len(stack) < k and (x == letter or len(stack) + repetition < k):
stack.append(x)
if x == letter: repetition -= 1
if x == letter: rest -= 1
return "".join(stack)
|
'''
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
'''
# Set + Recursion Solution
# Time: O(n * m), Iterates through grid once.
# Space: O(n * m), Uses set to keep track of visited indices.
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0]) # Gets size of grid.
visited = set() # Set containing a tuple if indices visited in grid.
def isValidIndice(row: int, column: int) -> bool: # Chekcs if a row and column are in the grid.
if row < 0 or M <= row: return False # Checks for out of bounds row.
if column < 0 or N <= column: return False # Checks for out of bounds column.
return True # Returns True if all checks are passed.
def islandArea(row, column) -> int: # Gets the area of a 4-connected island on the grid.
if (row, column) in visited: return 0 # Checks if indices have been visited already.
if not isValidIndice(row, column): return 0 # Checks if the indice is in bounds.
if grid[row][column] == 0: return 0 # Checks if cell is water.
visited.add((row, column)) # Adds cell to visited set.
up, down = islandArea(row-1, column), islandArea(row+1, column) # Recursive call to cells above and below to get area.
left, right = islandArea(row, column-1), islandArea(row, column+1) # Recursive call to cells left and right to get area.
return 1 + up + down + left + right # returns the area of the island.
area, maxArea = 0, 0
for row in range(M): # Iterates through grid rows.
for column in range(N): # Iterates through grid columns.
area = islandArea(row, column) # Gets area of island if cell is 1.
maxArea = max(maxArea, area) # Sets max island area found.
return maxArea
--------------------------------------------------------------------------------------------------------------------------
# Recursion Solution
# Time: O(n * m), Iterates through grid once.
# Space: O(1), Constant space used by mutating the input list to track visited cells.
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0]) # Gets size of grid.
def isValidIndice(row: int, column: int) -> bool: # Chekcs if a row and column are in the grid.
if row < 0 or M <= row: return False # Checks for out of bounds row.
if column < 0 or N <= column: return False # Checks for out of bounds column.
return True # Returns True if all checks are passed.
def islandArea(row, column) -> int: # Gets the area of a 4-connected island on the grid.
if not isValidIndice(row, column): return 0 # Checks if the indice is in bounds.
if grid[row][column] == 0: return 0 # Checks if cell is water or has been visited.
grid[row][column] = 0 # Sets cell value to 0 to indicate its been visited.
up, down = islandArea(row-1, column), islandArea(row+1, column) # Recursive call to cells above and below to get area.
left, right = islandArea(row, column-1), islandArea(row, column+1) # Recursive call to cells left and right to get area.
return 1 + up + down + left + right # returns the area of the island.
area, maxArea = 0, 0
for row in range(M): # Iterates through grid rows.
for column in range(N): # Iterates through grid columns.
area = islandArea(row, column) # Gets area of island if cell is 1.
maxArea = max(maxArea, area) # Sets max island area found.
return maxArea
-------------------------------------------------------------------------------------------------------------------------------------------
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid: return 0
rows = len(grid)
cols = len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
max_area = 0
# Search our grid looking for islands.
for row in range(rows):
for col in range(cols):
# If we find and island, continue searching it.
if grid[row][col] == 1:
area = 1
# Mark the locations we've searched so we don't recount them.
grid[row][col] = '#'
q = collections.deque([])
q.append((row, col))
while q:
r, c = q.popleft()
# Search all of the possible next locations based on our move directions.
for y, x in directions:
# new row and col = current + the new movement direction.
nr = r + y
nc = c + x
# If the new location is valid: within the grid and contains more island (1)
if nr < rows and nr >= 0 and nc < cols and nc >= 0 and grid[nr][nc] == 1:
# Update the current islands area, mark as searched and add to the deque.
area += 1
grid[nr][nc] = '#'
q.append((nr, nc))
# Once we finish exploring the island, check if it's area is the largest we've seen thus far.
max_area = max(max_area, area)
return max_area
|
'''
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
'''
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> list:
self.res = 0
def dfs(node) -> list:
if not node: return []
if not node.left and not node.right: return [1]
left_list = dfs(node.left)
right_list = dfs(node.right)
self.res += sum(l+r <= distance for l in left_list for r in right_list)
return [1+item for item in left_list+right_list]
dfs(root)
return self.res
------------------------------------------------------------------------------------------------
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
res = [0]
def dfs(node):
if not node:return []
if not node.left and not node.right:return [0]
left,right = dfs(node.left),dfs(node.right)
m,n = len(left),len(right)
for i in range(m):
left[i]+=1
for j in range(n):
right[j]+=1
for l in left:
for r in right:
if l + r <= distance:
res[0] += 1
return left+right
dfs(root)
return res[0]
|
'''
Given a m x n grid filled
with non-negative numbers, find a path
from top left to bottom right which minimizes
the sum of all numbers along its path.
Note: You can only move either down or right at any point in time
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
s = 0
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if n == 0:
return 0
for i in range(m):
for j in range(n):
if i-1 >=0 and j-1 >=0:
grid[i][j] += min(grid[i-1][j],
grid[i][j-1])
else:
if i-1 >=0:
grid[i][j] += grid[i-1][j]
if j -1 >=0:
grid[i][j] += grid[i][j-1]
return grid[m-1][n-1]
|
'''
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson.
Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa.
The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame.
Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
'''
from collections import defaultdict
class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
meetMap = {}
for a, b, t in meetings:
if not t in meetMap:
meetMap[t] = defaultdict(set)
meetMap[t][a].add(b)
meetMap[t][b].add(a)
withSecret = set([0, firstPerson])
def dfs(graph, node, visited):
if node in visited:
return
visited.add(node)
for v in graph[node]:
if v in visited:
continue
dfs(graph, v, visited)
for t in sorted(meetMap.keys()):
graph = meetMap[t]
visited = set()
for p in set(graph.keys()).intersection(withSecret):
if p in visited:
continue
dfs(graph, p, visited)
withSecret.update(visited)
return list(withSecret)
|
'''
This is an interactive problem.
There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.
You want to find the minimum distance to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.
Thr GridMaster class has the following functions:
boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
void move(char direction) Moves the robot in that direction. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, and the robot will remain in the same position.
boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.
Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.
Return the minimum distance between the robot's initial starting cell and the target cell. If there is no valid path between the cells, return -1.
Custom testing:
The test input is read as a 2D matrix grid of size m x n where:
grid[i][j] == -1 indicates that the robot is in cell (i, j) (the starting cell).
grid[i][j] == 0 indicates that the cell (i, j) is blocked.
grid[i][j] == 1 indicates that the cell (i, j) is empty.
grid[i][j] == 2 indicates that the cell (i, j) is the target cell.
There is exactly one -1 and 2 in grid. Remember that you will not have this information in your code.
'''
Expalantion
Similar question: 1810. Minimum Path Cost in a Hidden Grid
Based on hint section, do a DFS to explore the grid, then use BFS to find the shortest path
DFS: Assuming that we are starting from (0, 0), explore the grid, save the relative offset of other reachable positions (including target)
BFS: Find the shortest path by visiting reachable locations stored by DFS
Implementation
class Solution(object):
def findShortestPath(self, master: 'GridMaster') -> int:
opposite = {'U': 'D', 'D': 'U', 'L': 'R', 'R': 'L'}
reachable = set([(0, 0)])
target = None
def dfs(cur, x, y): # dfs to explore the grid
nonlocal target
if cur.isTarget():
target = x, y # save `target` position
return True
ans = False
for di, (i, j) in zip(['D', 'U', 'L', 'R'], [(-1, 0), (1, 0), (0, -1), (0, 1)]):
_x, _y = x+i, y+j
if (_x, _y) not in reachable and cur.canMove(di): # if not reachable and can move
cur.move(di)
reachable.add((_x, _y)) # save position to `reachable`
ans |= dfs(cur, _x, _y) # dfs on next position
cur.move(opposite[di]) # move back to position before dfs
return ans
if not dfs(master, 0, 0): return -1
dq = collections.deque([(0, 0, 0)]) # starting BFS here
while dq:
step, x, y = dq.popleft()
if (x, y) == target: return step
for i, j in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
_x, _y = x+i, y+j
if (_x, _y) not in reachable: continue # only continue BFS on reachable neighbors
dq.append((step+1, _x, _y)) # BFS at neighbor positions
reachable.remove((_x, _y)) # remove from `reachable` once used to avoid repeats
return -1
-----------------------------------------
class Solution(object):
DIRECTIONS = (('U', -1, 0, 'D'), ('D', 1, 0, 'U'), ('L', 0, -1, 'R'), ('R', 0, 1, 'L'))
def findShortestPath(self, master: 'GridMaster') -> int:
start = 0, 0
target, visited = dfs(start, master)
if target is None:
return -1
return dijkstras(start, visited, target)
def dfs(start, master):
seen = {start}
target = None
stack = [(start, None)]
visited = set()
while stack:
node, direction = stack.pop()
if direction is not None:
master.move(direction)
if node in visited:
continue
visited.add(node)
if target is None and master.isTarget():
target = node
r, c = node
for direction, rd, cd, inverted in Solution.DIRECTIONS:
next_node = (r + rd, c + cd)
if next_node not in seen:
seen.add(next_node)
if master.canMove(direction):
stack.append((node, inverted))
stack.append((next_node, direction))
return target, visited
def dijkstras(start, visited, target):
distances = dict.fromkeys(visited, math.inf)
distances[start] = 0
pq = [(0, start)]
while pq:
distance, (r, c) = heappop(pq)
if (r, c) == target:
return distance
for next_node in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]:
if next_node not in distances:
continue
next_distance = distance + 1
if next_distance < distances[next_node]:
distances[next_node] = next_distance
heappush(pq, (next_distance, next_node))
return -1
-----------------------------------------------------------------------------
class Solution(object):
def findShortestPath(self, master: 'gridMaster') -> int:
res = [float('inf')]
target = [(float('-inf'), float('-inf'))]
seen = set()
def dfs(i, j):
if (i, j) not in seen:
seen.add((i, j))
else:
return
if master.isTarget():
target[0] = (i, j)
if master.canMove('U'):
master.move('U')
dfs(i - 1, j)
master.move('D')
if master.canMove('D'):
master.move('D')
dfs(i + 1, j)
master.move('U')
if master.canMove('L'):
master.move('L')
dfs(i, j - 1)
master.move('R')
if master.canMove('R'):
master.move('R')
dfs(i, j + 1)
master.move('L')
dfs(0, 0)
if target[0] == (float('-inf'), float('-inf')):
return -1
seen2 = set()
qu = deque()
dirs = [(0, -1), (0, 1), (-1, 0), (1, 0)]
qu.append((0, 0, 0))
seen2.add((0, 0))
while qu:
cx, cy, steps = qu.popleft()
if (cx, cy) == target[0]:
print(target[0])
return steps
for x, y in dirs:
nx = cx + x
ny = cy + y
if (nx, ny) in seen2:
continue
if (nx, ny) in seen:
seen2.add((nx, ny))
qu.append((nx, ny, steps + 1))
return -1
--------------------------------------------------------------------------------------
class Solution(object):
def findShortestPath(self, master: 'GridMaster') -> int:
# Time O(MN), or 4MN, since we need to check the neighbors for each cell.
# Space O(MN)
# For all cells in the grid
# DFS for finding the target, also stored the valid cells to be moved
# It needs to explore the entire map
# BFS for calculating the distances
can_move = {}
queue = collections.deque([(0, 0, 0)])
direction = {'U': (0, 1), 'D': (0, -1), 'L': (-1, 0), 'R': (1, 0)}
back_dir = {'U': 'D', 'D': 'U', 'L': 'R', 'R': 'L'}
def dfs(x, y):
nonlocal master
nonlocal direction
nonlocal can_move
nonlocal back_dir
can_move[(x, y)] = master.isTarget()
for d, (dx, dy) in direction.items():
if (x + dx, y + dy) not in can_move and master.canMove(d):
master.move(d)
dfs(x + dx, y + dy)
master.move(back_dir[d])
dfs(0, 0)
queue = collections.deque([(0, 0, 0)])
visited = set()
while queue:
x, y, d = queue.popleft()
if can_move[(x, y)] is True:
return d
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
xx = x + dx
yy = y + dy
if (xx, yy) in can_move and (xx, yy) not in visited:
visited.add((xx, yy))
queue.append((xx, yy, d + 1))
return -1
|
'''
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
'''
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
count= 0
for i in range(len(words)):
word = words[i]
len_pref = len(pref)
possible_pref = word[:len_pref]
if possible_pref == pref:
count+=1
return count
|
'''
You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.
Your goal is to satisfy one of the following three conditions:
Every letter in a is strictly less than every letter in b in the alphabet.
Every letter in b is strictly less than every letter in a in the alphabet.
Both a and b consist of only one distinct letter.
Return the minimum number of operations needed to achieve your goal.
'''
class Solution:
def minCharacters(self, a: str, b: str) -> int:
counter_a = Counter(ord(ch) - ord('a') for ch in a)
counter_b = Counter(ord(ch) - ord('a') for ch in b)
# keys will go from 0 to 25
# condition 3
# min cost to turn a consisting of single character only is len(a) - max_freq_of_character
unique = len(a) - max(counter_a.values()) + len(b) - max(counter_b.values())
a_less_than_b = b_less_than_a = len(a) + len(b)
# counter maintains a prefix sum and it adds up the frequency of all previous letters upto the letter being tried as boundary letter.
for i in range(1,26):
counter_a[i] += counter_a[i-1]
counter_b[i] += counter_b[i-1]
# cost to turn a less than b
a_less_than_b = min(a_less_than_b, len(a) - counter_a[i] + counter_b[i])
b_less_than_a = min(b_less_than_a, len(b) - counter_b[i] + counter_a[i])
return min(a_less_than_b, b_less_than_a, unique)
------------------------------------------------------------------------------------------
class Solution:
def minCharacters(self, a: str, b: str) -> int:
cn1, cn2 = [0] * 26, [0] * 26
for c in a: cn1[ord(c)-97] += 1
for c in b: cn2[ord(c)-97] += 1
ans = len(a) + len(b) - max(x + y for x, y in zip(cn1, cn2)) # condition 3
for i in range(1, 26): # note that letters can't be smaller than 'a' or bigger than 'z'
ans = min(ans, sum(cn1[:i]) + sum(cn2[i:]), sum(cn1[i:]) + sum(cn2[:i]))
return ans
|
'''
You are playing a game that has n levels numbered from 0 to n - 1. You are given a 0-indexed integer array damage where damage[i] is the amount of health you will lose to complete the ith level.
You are also given an integer armor. You may use your armor ability at most once during the game on any level which will protect you from at most armor damage.
You must complete the levels in order and your health must be greater than 0 at all times to beat the game.
Return the minimum health you need to start with to beat the game.
'''
You will only get one shot, so pick the turn that you may lose the most health
Your total loss-avoidable will be min(max(damage), armor)
You will need at least sum(damage) + 1 to pass the game without any armor
class Solution:
def minimumHealth(self, damage: List[int], armor: int) -> int:
return sum(damage) + 1 - min(max(damage), armor)
---------------------------------------------
def minimumHealth(self, damage: List[int], armor: int) -> int:
return sum(damage) - min(armor, max(damage)) + 1
---------------------------------------------------------
Explaination:
If you have 0 armor, you need sum(damage) + 1 health to survive against the damage.
Eg:
Sum of [12, 5, 6, 1, 4] = 28. So you need 28 + 1 = 29 health.
Armor can reduce upto "armor" damage.
Naturally you want to use your armor against the enemy's strongest attack.
There can be two scenarios here:
armor > max(damage) [eg: armor = 14]
armor <= max(damage) [eg: armor = 10]
If armor is greater, it will soak upto the amount of that damage (ie: 12) and the remaining discarded from further calculations. [reduction = 12]
If the damage is greater, net damage will be reduced by amount of armor (ie: 12 - 10 = 2). [reduction = 10]
class Solution:
def minimumHealth(self, damage: List[int], armor: int) -> int:
top = max(damage)
reduction = armor if top > armor else top
return sum(damage) - reduction + 1
-----------------------------------------------------------------------
The main idea is to find the index of the maximum damage, then use the armor once to block this damage.
If the maximum damage is above the armor can resist, then at the stage, we need at least damage_i - armor + 1 health to survive, otherwise, just use the armor to completely block it.
The overall time complexity is O(n) and space complexity is O(1).
class Solution(object):
def minimumHealth(self, damage, armor):
"""
:type damage: List[int]
:type armor: int
:rtype: int
"""
max_damage = max(damage)
target_index = 0
for index, d in enumerate(damage):
if d == max_damage:
target_index = index
break
ans = 1
for index, d in enumerate(damage):
if index == target_index:
if armor >= d:
pass
else:
ans += d - armor
else:
ans += d
return ans
-------------------------------------------------------------------------------
class Solution:
def minimumHealth(self, damage: List[int], armor: int) -> int:
if not armor: return sum(damage) + 1
def bs(health):
used = 0
stack = [] # keep maximum heap
for d in damage:
if not used:
heappush(stack, -d)
if d >= health:
# use the armor to maximize its effect (to counter previous maximum damage)
if not used and health - d + min(armor, -stack[0]) > 0:
health = health - d + min(armor, -stack[0])
used = 1
else:
return False
else:
health -= d
return True
l, h = 1, sum(damage) + 1
while l < h:
mid = l + (h - l) // 2
if bs(mid):
h = mid
else:
l = mid + 1
return l
-------------------------------------------------------------
class Solution:
def minimumHealth(self, damage: List[int], armor: int) -> int:
max_val=max(damage)
damage[damage.index(max_val)]-=min(armor, max_val)
return sum(damage)+1
|
'''
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
'''
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(nums2) < len(nums1): nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
left, right = 0, m-1
while True:
pointer1 = left + (right-left) // 2
pointer2 = (m+n)//2 - pointer1 - 2
left1 = nums1[pointer1] if pointer1 in range(m) else -math.inf
left2 = nums2[pointer2] if pointer2 in range(n) else -math.inf
right1 = nums1[pointer1+1] if pointer1+1 in range(m) else math.inf
right2 = nums2[pointer2+1] if pointer2+1 in range(n) else math.inf
if left1 <= right2 and left2 <= right1:
if (m+n) % 2 == 0: return (max(left1, left2) + min(right1, right2)) / 2
else: return min(right1, right2)
elif left1 > right2: right = pointer1 - 1
else: left = pointer1 + 1
|
'''
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
'''
# 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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root:
return self.inorderTraversal(root.left) + [root.val]+ self.inorderTraversal(root.right)
else:
return []
def isValidBST(self, root: Optional[TreeNode]) -> bool:
d = self.inorderTraversal(root)
print(d)
if len(d) == 1:
return True
for i in range(len(d)-1):
if d[i+1] <= d[i]:
return False
return True
# much better solution - originally what i wanted.
import sys
class Solution:
def helper(self, root: Optional[TreeNode], l, r) -> List[int]:
if not root:
return True
if not (l < root.val < r):
return False
return self.helper(root.left, l, root.val) and self.helper(root.right, root.val, r)
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.helper(root, -sys.maxsize, sys.maxsize)
|
'''
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].
Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.
'''
class Solution(object):
def kInversePairs(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
dp = [[0] * (k+1) for _ in range(n+1)]
dp[0][0] = 1
for i in range(1, n+1):
cumsum = 0
for j in range(k+1):
if j == 0:
dp[i][j] = 1
cumsum += 1
else:
cumsum += dp[i-1][j]
if j-i >= 0: # basically sliding window
cumsum -= dp[i-1][j-i]
dp[i][j] = cumsum % 1000000007
return dp[n][k]
|
'''
You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents:
A land cell if grid[r][c] = 0, or
A water cell containing grid[r][c] fish, if grid[r][c] > 0.
A fisher can start at any water cell (r, c) and can do the following operations any number of times:
Catch all the fish at cell (r, c), or
Move to any adjacent water cell.
Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0 if no water cell exists.
An adjacent cell of the cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) or (r - 1, c) if it exists.
'''
class Solution:
def dfs(self,grid,i,j,n,m):
f = grid[i][j]
grid[i][j] = 0 #important!
for dr,dc in (1,0), (-1,0), (0,-1), (0,1):
r = i + dr
c = j + dc
if 0 <= r < m and 0 <= c < n and grid[r][c]>0 :#aka water cell and within limits
f+= self.dfs(grid,r,c,n,m)
return f
def findMaxFish(self, grid: List[List[int]]) -> int:
ans = 0
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] >0:
#dfs
ans = max(ans, self.dfs(grid,i,j,n,m) )
return ans
|
'''
You are given an array nums consisting of positive integers.
Split the array into one or more disjoint subarrays such that:
Each element of the array belongs to exactly one subarray, and
The GCD of the elements of each subarray is strictly greater than 1.
Return the minimum number of subarrays that can be obtained after the split.
Note that:
The GCD of a subarray is the largest positive integer that evenly divides all the elements of the subarray.
A subarray is a contiguous part of the array.
'''
from math import gcd
class Solution:
def minimumSplits(self, nums: List[int]) -> int:
cur = nums[0]
res = 0
for num in nums:
if gcd(cur, num) == 1:
cur = num
res += 1
else:
cur = gcd(cur, num)
return res + 1
-----------------------------------------------------------------------------------------------------------------------------------
class Solution:
def minimumSplits(self, nums: List[int]) -> int:
i = 0
split = 0
while i < len(nums):
j = i
cur_gcd = nums[j]
while j<len(nums):
cur_gcd = gcd(cur_gcd, nums[j])
if cur_gcd == 1:
break
j+=1
i = j
split += 1
return split
------------------------------------------------------------------------------------------------------------------------------------
Explanation
Simple do a prefix gcd and keep track of current gcd c_gcd, if c_gcd == 1, we need to split the subarray
Implementation
class Solution:
def minimumSplits(self, nums: List[int]) -> int:
ans, c_gcd = 1, nums[0]
for i, num in enumerate(nums[1:], 1):
c_gcd = gcd(num, c_gcd)
if c_gcd == 1:
ans += 1
c_gcd = num
return ans
|
'''
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
'''
class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
#the deque keeps track of the set of strings that we want to perform swaps on
#at the start, the deque contains only s1
deque = collections.deque([s1])
#this set wasn't mentioned in the "intuition" part. it helps us avoid doing repeated work by adding the same strings to our deque
seen = set()
answ=0 #counter for the number of "swaps" done so far
while deque:
for _ in range(len(deque)): #loops through each string in the deque
string = deque.popleft() #gets the first string in the deque
if string ==s2: return answ
#finds the first non-matching letter in s1
#this satisfies condition 1 of a "useful" swap
#ex: this would be s1[3] in the above example
i=0
while string[i]==s2[i]:
i+=1
#checks all the other letters for potential swaps
for j in range(i+1, len(string)):
if string[i]==s2[j]!=s1[j]: #checks conditions 2 and 3 of a useful swap
#swaps the letters at positions i and j
new = string[:i] + string[j] + string[i+1:j] + string[i] + string[j+1:]
#adds the "new string" if it was not previously added
if new not in seen:
seen.add(new)
deque.append(new)
#record that one more swap was done for each string in the deque
answ+=1
-------------------------------------------------------------------------------------------------------
class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
n = len(s1)
arr, s2_arr = list(s1), list(s2)
min_steps = float('inf')
def helper(steps,i):
nonlocal min_steps
if steps >= min_steps: return
if i == n:
min_steps = min(min_steps, steps)
return
# if character at index i is already correct
if arr[i] == s2[i]:
helper(steps,i+1)
return
for j in range(i+1,n):
'''
skip if:
1. characters at i and j are the same
2. character at j is not what we need at i
3. character at j is already correctly placed
'''
if arr[i] == arr[j] or arr[j] != s2[i] or arr[j] == s2[j]: continue
arr[i], arr[j] = arr[j], arr[i]
helper(steps+1,i+1)
arr[i], arr[j] = arr[j], arr[i]
helper(0,0)
return min_steps
|
'''
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Return the maximum score you can get by erasing exactly one subarray.
An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).
'''
'''
Create a sliding window: [nums[l], nums[l + 1], ..., num].
For each number in the nums array, we check if this num is already present in the window. We can use a set to lookup in O(1).
If the number is present in the window, we keep shrinking the window from the left until there's no repetition.
We update the set by adding num and repeat the above process.
'''
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
seen = set()
curr_sum, max_sum, l = 0, 0, 0
for num in nums:
while num in seen:
curr_sum -= nums[l]
seen.remove(nums[l])
l += 1
curr_sum += num
seen.add(num)
max_sum = max(max_sum, curr_sum)
return max_sum
--------------------------------------------------------------------
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
prev = [-1] * 10001
curr_sum, max_sum, l = 0, 0, 0
for r, num in enumerate(nums):
if prev[num] >= l:
curr_sum -= sum(nums[l : prev[num] + 1])
l = prev[num] + 1
curr_sum += num
prev[num] = r
max_sum = max(max_sum, curr_sum)
return max_sum
|
'''
The score of an array is defined as the product of its sum and its length.
For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.
Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.
A subarray is a contiguous sequence of elements within an array.
'''
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
# p[i] = nums[:i]
# num[i] + ...+ num[j] = p[j+1] - p[i]
p = [0]
for num in nums :
p.append(p[-1] + num)
left = 0
res = 0
for i in range(1, len(nums)+1):
val = (p[i] - p[left]) * ( i - left)
while val >= k and left < i :
left += 1
val = (p[i] - p[left]) * ( i - left)
res += i - left
return res
---------------------------------------------------------------
class Solution:
def countSubarrays(self, xs: List[int], k: int) -> int:
n = len(xs)
i, j, sub_sum = 0, 0, 0
ans = 0
while j < n:
sub_sum += xs[j]
if sub_sum * (j - i + 1) < k:
ans += j - i + 1
j += 1
elif i == j:
sub_sum = 0
j += 1
i = j
else:
sub_sum -= xs[i] + xs[j]
i += 1
return ans
---------------------------------------------------------------------------------
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
i, start = 0, 0
n = len(nums)
val, ans, sums = 1, 0, 0
while i < n:
sums += nums[i]
val = sums * (i-start+1)
while start <= i and val >= k:
sums -= nums[start]
start += 1
val = sums * (i-start+1)
ans += (i-start+1)
i += 1
return ans
|
'''
You are given a 0-indexed integer array nums of length n.
The average difference of the index i is the absolute difference between the average of
the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.
Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.
Note:
The absolute difference of two numbers is the absolute value of their difference.
The average of n elements is the sum of the n elements divided (integer division) by n.
The average of 0 elements is considered to be 0.
'''
class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
n = len(nums)
pre = list()
res=float('inf')
pre.append(nums[0])
for i in range(1,n):
pre.append(nums[i] + pre[i-1])
p=0
post=[0]*n
for i in range(n-1,-1,-1):
post[i]=p
p+=nums[i]
for i in range(n):
if pre[i]>0:
first = int(pre[i]/(i+1))
else:
first = 0
if post[i] > 0 and n - i -1 >0:
second = int(post[i]/(n-i-1))
else:
second = 0
if abs(first - second) < res:
res = abs(first-second)
idx = i
return idx
# n=len(nums)
# p=0
# pre=[]
# for i in range(n):
# p+=nums[i]
# pre.append(p)
# p=0
# post=[0]*n
# for i in range(n-1,-1,-1):
# post[i]=p
# p+=nums[i]
# res=float('inf')
# idx=0
# for i in range(n):
# first = int(pre[i]/(i+1)) if pre[i]>0 else 0
# second = int(post[i]/(n-i-1)) if post[i]>0 and n-i-1>0 else 0
# if abs(first-second)<res:
# idx=i
# res=abs(first-second)
# return idx
|
'''
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.
Return the number of nodes that have the highest score.
'''
'''
Explanation
Intuition: Maximum product of 3 branches, need to know how many nodes in each branch, use DFS to start with
Build graph
Find left, right, up (number of nodes) for each node
left: use recursion
right: use recursion
up: n - 1 - left - right
Calculate score store in a dictinary
Return count of max key
Time: O(n)
Implementation
'''
class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
graph = collections.defaultdict(list)
for node, parent in enumerate(parents): # build graph
graph[parent].append(node)
n = len(parents) # total number of nodes
d = collections.Counter()
def count_nodes(node): # number of children node + self
p, s = 1, 0 # p: product, s: sum
for child in graph[node]: # for each child (only 2 at maximum)
res = count_nodes(child) # get its nodes count
p *= res # take the product
s += res # take the sum
p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself)
d[p] += 1 # count the product
return s + 1 # return number of children node + 1 (self)
count_nodes(0) # starting from root (0)
return d[max(d.keys())] # return max count
-----------------------------------------------------------------------------------------
'''
for each node, when we remove it, we have the following parts:
child subtree if any
parent subtree if any
we use dfs to count the number of node in each child subtree (no.1) and calculate the number of
node in the parent subtree by N - sum(child_subtree) - 1(node itself). We use memo to aovid duplicated calculation in dfs.
'''
def countHighestScoreNodes(self, parents: List[int]) -> int:
children = collections.defaultdict(list)
for i, par in enumerate(parents):
children[par].append(i)
@lru_cache(None)
def dfs(root):
count = 1
for child in children[root]:
count += dfs(child)
return count
N = len(parents)
max_score = 0
score_counter = collections.defaultdict(int)
for root in range(N):
child = children[root]
_sum = 0
score = 1
# score of the child tree
for c in child:
count = dfs(c)
score *= count
_sum += count
curr_score = score * max(1, N-_sum-1) # score of the parent subtree
score_counter[curr_score] += 1
max_score = max(max_score, curr_score)
return score_counter[max_score]
|
'''
There is a function signFunc(x) that returns:
1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.
You are given an integer array nums. Let product be the product of all values in the array nums.
Return signFunc(product).
'''
#my own solution
class Solution:
def arraySign(self, nums: List[int]) -> int:
if nums.count(0) != 0:
return 0
else:
neg_counter = 0
for i in range(len(nums)):
if nums[i] < 0:
neg_counter +=1
if neg_counter % 2 == 0:
return 1
else:
return -1
|
'''
A happy string is a string that:
consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k happy strings of length n.
'''
class Solution:
def getHappyString(self, n: int, k: int) -> str:
res = []
for c in product('abc', repeat=n):
flag = True
for i in range(1, len(c)):
# Check if c[i] is not equal c[i-1] as mentioned in the problem
if c[i] == c[i-1]:
flag = False
if flag:
res.append(''.join(f for f in c))
# Check for boundary conditions
if k > len(res):
return ""
else:
return res[k-1]
|
'''
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
'''
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
digits = "123456789"
res = []
nl = len(str(low))
nh = len(str(high))
for i in range(nl, nh + 1):
for j in range(0, 10 - i):
num = int(digits[j: j + i])
if num >= low and num <= high: res.append(num)
return res
---------------------------------------------------------------------------
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
s='123456789'
ans=[]
for i in range(len(s)):
for j in range(i+1,len(s)):
st=int(s[i:j+1])
if(st>=low and st<=high):
ans.append(st)
ans.sort()
return ans
|
'''
You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.
The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0.
The value of the character is defined in the following way:
If the character is not in the string chars, then its value is its corresponding position (1-indexed) in the alphabet.
For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26.
Otherwise, assuming i is the index where the character occurs in the string chars, then its value is vals[i].
Return the maximum cost among all substrings of the string s.
'''
class Solution:
def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int:
cost1 = dict(zip(chars, vals))
ind = [i for i in range(1, 27)]
val = string.ascii_lowercase
cost = dict(zip(val, ind))
for k, v in cost1.items():
if k in cost:
cost[k] = v
max_cost = 0
cur_cost = 0
for i in range(len(s)):
cur_cost += cost[s[i]]
if cur_cost < 0:
cur_cost = 0
max_cost = max(cur_cost, max_cost)
print(max_cost)
return max_cost
|
'''
Given a 0-indexed integer array nums, return the number of
subarrays
of nums having an even product.
'''
from collections import defaultdict
class Solution:
def evenProduct(self, nums: List[int]) -> int:
i = -1
res = 0
for j,num in enumerate(nums):
if num%2 == 0:
i = j
res += i + 1
return res
-----------------------------------------------------------------------------------------
class Solution:
def evenProduct(self, nums: List[int]) -> int:
ans = val = 0
for i, x in enumerate(nums):
if not x&1: val = i+1
ans += val
return ans
|
'''
Given a list of integers prices representing the stock prices of a company in chronological order, return the
maximum profit you could have made from buying and selling that stock any number of times.
You must buy before you can sell it. But you are not required to buy or sell the stock.
'''
class Solution:
def solve(self, prices):
diffs = list()
for i in range(len(prices)-1):
j = i+1
diffs.append( prices[j] - prices[i])
total = sum(list(filter(lambda x : x > 0, diffs)))
return total
|
'''
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.
The grammar can best be understood through simple examples:
Single letters represent a singleton set containing that word.
R("a") = {"a"}
R("w") = {"w"}
When we take a comma-delimited list of two or more expressions, we take the union of possibilities.
R("{a,b,c}") = {"a","b","c"}
R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)
When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}
Formally, the three rules for our grammar:
For every lowercase letter x, we have R(x) = {x}.
For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...
For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product.
Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.
'''
The general idea
Split expressions into groups separated by top level ','; for each top-level sub expression (substrings with braces), process it and add it to the corresponding group; finally combine the groups and sort.
Thought process
in each call of the function, try to remove one level of braces
maintain a list of groups separated by top level ','
when meets ',': create a new empty group as the current group
when meets '{': check whether current level is 0, if so, record the starting index of the sub expression;
always increase level by 1, no matter whether current level is 0
when meets '}': decrease level by 1; then check whether current level is 0, if so, recursively call braceExpansionII to get the set of words from expresion[start: end], where end is the current index (exclusive).
add the expanded word set to the current group
when meets a letter: check whether the current level is 0, if so, add [letter] to the current group
base case: when there is no brace in the expression.
finally, after processing all sub expressions and collect all groups (seperated by ','), we initialize an empty word_set, and then iterate through all groups
for each group, find the product of the elements inside this group
compute the union of all groups
sort and return
note that itertools.product(*group) returns an iterator of tuples of characters, so we use''.join() to convert them to strings
class Solution:
def braceExpansionII(self, expression: str) -> List[str]:
groups = [[]]
level = 0
for i, c in enumerate(expression):
if c == '{':
if level == 0:
start = i+1
level += 1
elif c == '}':
level -= 1
if level == 0:
groups[-1].append(self.braceExpansionII(expression[start:i]))
elif c == ',' and level == 0:
groups.append([])
elif level == 0:
groups[-1].append([c])
word_set = set()
for group in groups:
word_set |= set(map(''.join, itertools.product(*group)))
return sorted(word_set)
-------------------------------------------------------------------------------
class Solution:
def braceExpansionII(self, expression: str) -> List[str]:
s = list(reversed("{" + expression + "}"))
def full_word():
cur = []
while s and s[-1].isalpha():
cur.append(s.pop())
return "".join(cur)
def _expr():
res = set()
if s[-1].isalpha():
res.add(full_word())
elif s[-1] == "{":
s.pop() # remove open brace
res.update(_expr())
while s and s[-1] == ",":
s.pop() # remove comma
res.update(_expr())
s.pop() # remove close brace
while s and s[-1] not in "},":
res = {e + o for o in _expr() for e in res}
return res
return sorted(_expr())
|
'''
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
'''
# 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 isUnivalTree(self, root: Optional[TreeNode]) -> bool:
main = root.val
def check(root, main):
if root:
if root.val!= main:
return False
if not check(root.right,main) or not check(root.left,main):
return False
return True
result = check(root,main)
return result
#from discussions
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
if not root:
return True
if root.left and root.val != root.left.val:
return False
if root.right and root.val != root.right.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
|
'''
You are given the head of a linked list.
The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,
The 1st node is assigned to the first group.
The 2nd and the 3rd nodes are assigned to the second group.
The 4th, 5th, and 6th nodes are assigned to the third group, and so on.
Note that the length of the last group may be less than or equal to 1 + the length of the second to last group.
Reverse the nodes in each group with an even length, and return the head of the modified linked list.
'''
class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
group = 2
tail = head # tail of previous group
while tail and tail.next:
cnt = 1 # actual size of the current group
cur = tail.next # first node of the current group
while cur.next and cnt < group:
cur = cur.next
cnt += 1
pre, cur = tail, tail.next
if cnt % 2 == 0: # if group size is even
while cnt and cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
cnt -= 1
first = tail.next # first node of the original group
first.next = cur
tail.next = pre
tail = first
else:
while cnt and cur:
pre, cur = cur, cur.next
cnt -= 1
tail = pre
group += 1
return head
-------------------------------------------------------------------------------------------
class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next == None:
return head
last: Optional[ListNode] = head
first: Optional[ListNode] = head
prev: Optional[ListNode] = head
lastprev: Optional[ListNode] = head
group: int = 1
length: int = 1
while last:
# length += 1
if length == group:
if length%2==0:
prev.next = last
nextG = last.next
prev = self.reverse(first,last)
prev.next = nextG
last = nextG
first = nextG
group += 1
length = 1
continue
first = last.next
prev = last
group += 1
length = 1
last = last.next
continue
length += 1
lastprev = last
last = last.next
if (length - 1) != 0 and (length - 1)%2==0:
prev.next = lastprev
self.reverse(first,lastprev).next = last
return head
def reverse(self,first: Optional[ListNode],last: Optional[ListNode]):
# to reverse
prev: Optional[ListNode] = None
current: Optional[ListNode] = first
last: Optional[ListNode] = last.next
temp: Optional[ListNode]
while (current != last):
temp = current.next
current.next = prev
prev = current
current = temp
return first
|
'''
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.
'''
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
qu=deque([start])
vis=set()
while qu:
r=len(qu)
for i in range(r):
temp=qu.popleft()
vis.add(temp)
if arr[temp]==0:
return True
if temp+arr[temp] in range(len(arr)) and temp+arr[temp] not in vis:
qu.append(temp+arr[temp])
if temp-arr[temp] in range(len(arr)) and temp-arr[temp] not in vis:
qu.append(temp-arr[temp])
return False
------------------------------------------------------------------------------------------------------------------
class Solution(object):
def canReach(self, arr, start):
if(start<0 or start>=len(arr) or arr[start]<0):
return False
if(arr[start]==0):
return True
arr[start]=-arr[start]
ans1 = self.canReach(arr,start+arr[start])
ans2 = self.canReach(arr,start-arr[start])
arr[start] = -arr[start] # change data back to orginal
return ans1 or ans2
------------------------------------------------------------------------------------
def canReach(self, arr: List[int], start: int) -> bool:
visited = set()
def DFS(position):
if position in visited or position<0 or position>=len(arr):
return False
visited.add(position)
if arr[position] == 0:
return True
return DFS(position+arr[position]) or DFS(position-arr[position])
return DFS(start)
---------------------------------------------------------------------------------------------
#bfs
from collections import deque
class Solution:
def canReach(self, arr, start):
_len_=len(arr)
seen=set()
queue=deque()
queue.append(start)
while(queue):
idx=queue.popleft()
if arr[idx]==0:
return True
seen.add(idx)
for var in (idx-arr[idx],idx+arr[idx]):
if (var not in seen) and (-1<var<_len_):
queue.append(var)
return False
------------------------------------------------------------------------
from collections import deque
class Solution:
def dfs(self,arr,idx,seen):
if idx>=len(arr) or (idx<0) or (idx in seen):
return False
if arr[idx]==0:
return True
seen.add(idx)
return self.dfs(arr,idx-arr[idx],seen) or self.dfs(arr,idx+arr[idx],seen)
def canReach(self, arr, start):
seen=set()
return self.dfs(arr,start,seen)
---------------------------------------------------------------------------------------------------------
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
queue = [start]
visited = set()
while queue:
u = queue.pop(0)
if arr[u] == 0:
return True
visited.add(u)
nextjump = u + arr[u]
if nextjump < len(arr) and nextjump not in visited:
if arr[nextjump] == 0:
return True
visited.add(nextjump)
queue.append(nextjump)
nextjump = u - arr[u]
if nextjump >= 0 and nextjump not in visited:
if arr[nextjump] == 0:
return True
visited.add(nextjump)
queue.append(nextjump)
return False
|
'''
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.
'''
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
res = list()
if len(nums)== 0:
if upper == lower:
return [str(upper)]
return [str(lower) + "->" + str(upper)]
# corner case at the start
if nums[0] > lower:
res.append(str(lower) + "->" + str(nums[0]-1))
for i in range(len(nums)-1):
diff = nums[i+1] - nums[i]
if diff > 1:
print('found diff', diff)
new_range = [nums[i]+1, nums[i+1]-1]
print(new_range)
res.append(str(nums[i]+1) + "->" + str(nums[i+1]-1))
# corner case in the end
if nums[-1] < upper:
res.append(str(nums[-1]+1) + "->" + str(upper))
# removing bad ranges!
for i in range(len(res)):
x = res[i].split("->")
if x[0] == x[1]:
res[i] = str(x[0])
print(res)
return res
#another solution from the discussions
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
res = []
prev = lower - 1 # so that I can handle case when nums is empty
for i in range(len(nums)+1):
current = nums[i] if i < len(nums) else upper+1
# means, not a continuos range where current number
# is 1 greater than the last number in the list
if current > prev+1:
# now my missing intervals will have number prev+1, current-1
# I can't take the number already present in the list
# that means, prev and current can't be part of my answer
if prev+1 < current-1:
res.append(str(prev+1) + "->" + str(current-1))
else:
res.append(str(prev+1))
prev = current
return res
|
'''
Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.
Return how many groups have the largest size.
'''
class Solution:
def countLargestGroup(self, n: int) -> int:
list_sums = dict.fromkeys([i for i in range(1,37)])
for i in list_sums.keys():
list_sums[i] = 0
for i in range(1,n+1):
num = str(i)
num = list(num)
num = list(map(lambda s: int(s),num))
temp_sum = sum(num)
if temp_sum in list_sums.keys():
list_sums[temp_sum]+=1
max_size = max(list_sums.values())
result= 0
for k in list_sums.keys():
if list_sums[k] == max_size:
result+=1
print(result)
return result
#a bit simplified solution
def f(n):
list_sums = dict.fromkeys([i for i in range(1,37)])
for i in list_sums.keys():
list_sums[i] = 0
for i in range(1,n+1):
num = str(i)
num = [int(c) for c in num]
if sum(num) in list_sums.keys():
list_sums[sum(num)]+=1
max_size = max(list_sums.values())
result= 0
for k in list_sums.keys():
if list_sums[k] == max_size:
result+=1
return result
f(2)
|
'''
There are n people, each person has a unique id between
0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.
Level 1 of videos are all
watched videos by your friends, level 2 of videos
are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.
'''
class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
queue = [id]
count = 0
seen = set(queue)
while queue and count < level: #bfs
count += 1
temp = set()
for i in queue:
for j in friends[i]:
if j not in seen:
temp.add(j)
seen.add(j)
queue = temp
movies = dict()
for i in queue:
for m in watchedVideos[i]:
movies[m] = movies.get(m, 0) + 1
return [k for _, k in sorted((v, k) for k, v in movies.items())]
-----------------------------------------
from collections import Counter
class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
queue, seen = {id}, {id}
for _ in range(level):
queue = {j for i in queue for j in friends[i] if j not in seen}
seen |= queue
freq = Counter(v for i in queue for v in watchedVideos[i])
return sorted(freq.keys(), key=lambda x: (freq[x], x))
--------------------------------------------------------------------------------
class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
friends_already_visited=set()
friends_at_last_level=set([id])
for l in range(0,level):
friends_already_visited.update(list(friends_at_last_level))
newfriends=set()
for oldfriend in friends_at_last_level:
newfriends.update(friends[oldfriend])
friends_at_last_level=newfriends.difference(friends_already_visited)
video_freq=dict()
for friend in friends_at_last_level:
for video in watchedVideos[friend]:
if video not in video_freq:
video_freq[video]=0
video_freq[video]+=1
return [video for video,freq in sorted(video_freq.items(), key= lambda item : (item[1], item[0]))]
|
'''
Given an integer n, return a binary string representing its representation in base -2.
Note that the returned string should not have leading zeros unless the string is "0".
'''
class Solution:
def baseNeg2(self, N: int) -> str:
if N in [0, 1]: return str(N)
if N % 2 == 0:
return self.baseNeg2(N // -2) + '0'
else:
return self.baseNeg2((N - 1) // -2) + '1'
-----------------------------------------------------------------------
class Solution:
def baseNeg2(self, n: int) -> str:
s = ''
if n == 0:
return '0'
while n != 0:
if n % 2 != 0:
s = '1' + s
n = (n - 1)//-2
else:
s = '0' + s
n = n//-2
return s
|
class TrieNode():
def __init__(self):
self.child = defaultdict(TrieNode)
class Trie():
def __init__(self):
self.root = TrieNode()
self.list = []
def add(self, word):
node = self.root
for ch in word:
node = node.child[ch]
self.list.append((node, len(word)+1))
class Solution(object):
def main(self, words):
trie = Trie()
for word in set(words):
trie.add(word[::-1])
ans = 0
|
'''
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
'''
class Solution:
def hIndex(self, citations: List[int]) -> int:
c = citations
c = sorted(c)
h_index = 0
for i in range(len(c)-1,-1,-1):
cnt = len(c)-i
if c[i] >=cnt:
h_index = cnt
else:
break
return h_index
|
'''
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
'''
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
adj = defaultdict(list)
# Make adjacency List in the form {A : [B, W]}
# Here adjacency list represents a map that represents and edge from A to B with W weight
for edge,probablity in zip(edges, succProb):
a, b = edge[0], edge[1]
# -1 multiplied as we would be using a min-heap functioning as a max-heap since we are required to return the max-probabilty
adj[a].append((b,-1*probablity))
adj[b].append((a,-1*probablity))
# Use of a min-Heap for Dijkstra's Algorithm
heap = [(-1,start)]
visited = {}
while heap:
prob,node = heapq.heappop(heap)
visited[node] = prob
if node == end: #Return Probability when we reach the destination Node
return -1 * prob
for nei,weight in adj[node]:
if nei not in visited:
heapq.heappush(heap, (-1*prob*weight,nei))
# Return Zero when we were never able to reach the destination node
return 0
-------------------------------------------------------
import heapq as hq
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
adj_list = {i: [] for i in range(0, n)}
for e, w in zip(edges, succProb):
v1, v2 = e
adj_list[v1].append((w, v2))
adj_list[v2].append((w, v1))
max_heap = [(-1, start)]
seen = set()
while max_heap:
weight, v = hq.heappop(max_heap)
if v in seen: continue
if v == end: return -weight
seen.add(v)
for neighbor_weight, neighbor in adj_list[v]:
if neighbor not in seen:
hq.heappush(max_heap, (weight * neighbor_weight, neighbor))
return 0.0
|
'''
Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels.
A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.
Example 1:
Input: picture = [["W","W","B"],["W","B","W"],["B","W","W"]]
Output: 3
Explanation: All the three 'B's are black lonely pixels.
Example 2:
Input: picture = [["B","B","B"],["B","B","W"],["B","B","B"]]
Output: 0
Constraints:
m == picture.length
n == picture[i].length
1 <= m, n <= 500
picture[i][j] is 'W' or 'B'.
'''
--------------------------------------------------------------
Go through the columns, count how many have exactly one black pixel and it's in a row that also has exactly one black pixel.
def findLonelyPixel(self, picture):
return sum(col.count('B') == 1 == picture[col.index('B')].count('B') for col in zip(*picture))
----------------------------------------------------------------------------------
Union the row and column index, this way, points in same row or col must be grouped into the same group. Finally, groups that only contains one point will be the answer.
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
n=len(picture)
m=len(picture[0]) if n else 0
uf={}
def find(x):
uf.setdefault(x,x)
if uf[x]!=x:
uf[x]=find(uf[x])
return uf[x]
def union(x,y):
uf[find(x)]=uf[find(y)]
for i in range(n):
for j in range(m):
if picture[i][j]=='B':
union(i,-(j+1))
return list(collections.Counter(find(u) for u in uf).values()).count(2)
Row scanning way:
Scan row one by one, if find any 'B', then search its column, if only one 'B' in the column, then this 'B' might be the candidate. Keep scanning this row, if find no other 'B', then this 'B' is one result. This way only takes O(1) memory.
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
n,m=len(picture),len(picture[0])
res=0
for j in range(m):
found=False
for i in range(n):
if picture[i][j]=='B':
if found or picture[i].count('B')!=1:
found=False
break
found=True
if found:
res+=1
return res
----------------------------------------------------------------------
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
rows = [sum(c == 'B' for c in r) for r in picture]
cols = [sum(c == 'B' for c in c) for c in zip(*picture)]
return sum(picture[i][j] == 'B' and rows[i] == 1 and cols[j] == 1 for i in range(len(picture)) for j in range(len(picture[i])))
--------------------------------------------------------------------------------
row: set of column indices, where there exists at least 1 row that has only 1 B pixel at column i
col[i]: total number of B at column i
A valid lonely pixel is when col[i] == 1 (meaning only 1 row at ith column has B pixel) and i exists in row (meaning picture[r][i] is the only B pixel for some row r).
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
m, n = len(picture), len(picture[0])
col = [0] * n
row = set()
for i in range(m):
cnt = 0
for j in range(n):
if picture[i][j] == 'B':
c = j
cnt += 1
col[j] += 1
if cnt == 1: row.add(c)
ans = 0
for i, c in enumerate(col):
if c == 1 and i in row:
ans += 1
return ans
-------------------------------------------------------------------------------------------------
if not picture:
return 0
count = 0
for row in picture:
if row.count('B') == 1: # if each row has lonely 'B'
count += 1
for col in zip(*picture):
if col.count('B') > 1: # if coulmn has some 'B' not alone
count -= col.count('B') # remove them from count
return count if count > 0 else 0
|
'''
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.
Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
'''
def partitionArray(self, A, k):
A.sort()
res, j = 1, 0
for i in range(len(A)):
if A[i] - A[j] > k:
res += 1
j = i
return res
------------------------------------------------------------------------------------------
def partitionArray(self, A, k):
A.sort()
res = 1
mn = mx = A[0]
for a in A:
mn = min(mn, a)
mx = max(mx, a)
if mx - mn > k:
res += 1
mn = mx = a
return res
-----------------------------------------------------------------------------------------------------------------
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
ans = 1
# To keep track of starting element of each subsequence
start = nums[0]
for i in range(1, len(nums)):
diff = nums[i] - start
if diff > k:
# If difference of starting and current element of subsequence is greater
# than K, then only start new subsequence
ans += 1
start = nums[i]
return ans
|
'''
Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values in the array. return the answer in any arbitrary order.
Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).
For arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.
For arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.
'''
class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort()
i, j = 0, len(arr) - 1
median = arr[(len(arr) - 1) // 2]
while len(arr) + i - j <= k:
if median - arr[i] > arr[j] - median:
i = i + 1
else:
j = j - 1
return arr[:i] + arr[j + 1:]
--------------------------------------------------------------------
def getStrongest(self, arr: List[int], k: int) -> List[int]:
med = sorted(arr[(len(arr)-1)//2])
return sorted(array, key=lambda x:(abs(x-med),x))[-k:]
-----------------------------------------------------------------------------
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort(reverse = True) # sort the arr in descending order, this will put the larger number at first if they have same distance to the median
m_index = len(arr) - (len(arr)-1)//2 - 1 # median index in reversely sorted arr
m = arr[m_index]
arr.sort(key = lambda x: abs(x-m), reverse = True) # sorted the arr again by absolute distance
return arr[:k]
----------------------------------------------------------------------------------------------------------
# Idea- Strongest value are willing to realy on boundary either side, and then inward with decreasing intesity.
# Steps to solve
# Sort, get median, and assign lastPointer, startPointer
# compare lastPointer's element with startPointer's element, then add accordingly
# only iterate loop for k, because elements in start and last with range of k, have Strongest value
# OR
# Explaination(hindi lang.)- https://www.youtube.com/watch?v=mvbTN2I3HxY
class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort()
lastPointer = -1
startPointer = 0
mInd = (len(arr)-1)//2
m = arr[mInd]
res = []
for i in range(k):
if abs(arr[lastPointer] - m) >= abs(arr[startPointer] - m):
res.append(arr[lastPointer])
lastPointer -= 1
else:
res.append(arr[startPointer])
startPointer += 1
return res
|
'''
There are n servers numbered from 0 to n - 1 connected by undirected
server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection
between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
'''
class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
edgeMap = defaultdict(list)
for a,b in connections:
edgeMap[a].append(b)
edgeMap[b].append(a)
disc, low, time, ans = [0] * n, [0] * n, [1], []
def dfs(curr: int, prev: int):
disc[curr] = low[curr] = time[0]
time[0] += 1
for next in edgeMap[curr]:
if not disc[next]:
dfs(next, curr)
low[curr] = min(low[curr], low[next])
elif next != prev:
low[curr] = min(low[curr], disc[next])
if low[next] > disc[curr]:
ans.append([curr, next])
dfs(0, -1)
return ans
|
'''
Given a string s, partition s such that every
substring
of the partition is a
palindrome
.
Return the minimum cuts needed for a palindrome partitioning of s.
'''
# python code
class Solution(object):
def minCut(self, s):
"""
s="abcgcbafj"
:type s: str
:rtype: int
"""
if s == s[::-1]:
return 0
for i in range(len(s)):
if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
return 1
l=len(s)
#d=[[0 for i in range(l)] for j in range(l)]
x=[[0 for i in range(l)] for j in range(l)]
for i in range(l):
for j in range(i,l):
st=s[i:j+1]
#d[i][j]=st
x[i][j]= (st==st[::-1])
p=[0 for c in range(l)]
for i in range(1,l):
if x[0][i]:
p[i]=0
else:
m=float("inf")
for j in range(i,0,-1):
if x[j][i]:
m=min(m,p[j-1])
p[i]=m+1
return p[-1]
|
'''
Please complete the code in solution.py to realize the function
of reverse_k_group. The reverse_k_group function has two parameters: the string str_in and the
positive integer k. Given a string, reverse each of k characters, and finally returns the updated string.
If the last remaining strings are less than k, keep the last
remaining strings in the original order
'''
def reverse_k_group(str_in, k) -> str:
"""
:param str_in: The first input list
:param k: Reverse every k strings
:return: The str_in after reverse
"""
s = str_in
q,r = divmod(len(s),k)
full = s[:q*k]
rem = s[-r:]
full = list(full)
for i in range(0,len(full),k):
full[i:i+k] = full[i:i+k][::-1]
full = "".join(full)
if r != 0:
full = full + rem
#print(full)
return full
--------------------------
def reverse_k_group(str_in, k) -> str:
"""
:param str_in: The first input list
:param k: Reverse every k strings
:return: The str_in after reverse
"""
times = len(str_in) // k
remain = len(str_in) % k
result = ''
for i in range(1, times+1):
for j in range(i*k-1, (i-1)*k-1, -1):
result += str_in[j]
if remain > 0:
result += str_in[-remain:]
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.