0%

Weekly Contest 194

Ranking: 429 / 13808 😋

Q1. 1486. XOR Operation in an Array

Given an integer n and an integer start.
Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length.
Return the bitwise XOR of all elements of nums.

Very straight forward.

1
2
3
4
5
6
7
class Solution:
def xorOperation(self, n: int, start: int) -> int:
arr = [start+2*i for i in range(n)]
rst = 0
for a in arr:
rst ^= a
return rst

Q2. 1487. Making File Names Unique

Too long. See description in link

Code is easy. It might takes a while to understand the question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
d = {}
rst = []
for name in names:
if name not in d:
rst.append(name)
d[name] = 1
else:
suffix = d[name]
while name+f'({suffix})' in d:
suffix += 1
d[name] = suffix + 1
new_name = name + f'({suffix})'
rst.append(new_name)
d[new_name] = 1
return rst

Q3 1488. Avoid Flood in The City

Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.

Given an integer array rains where: d

  • rains[i] > 0 means there will be rains over the rains[i] lake.
  • rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.

Return an array ans where:

  • ans.length == rains.length .
  • ans[i] == -1 if rains[i] > 0.
  • ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.

If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)

Note

  1. Failed 3 times to cover all corner cases.

Idea

  1. When there are no rains, append that day to a array. By nature, that array is sorted.
  2. Using a dictionary to track which lack is full and when it was filled. {lack: day_it_get_filled}
  3. When we found a lack is going to be flood, use binary search to find the earliest day we can use to dry that lake.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
rst = [-1] * len(rains)
dry, full = [], {}
for i, lack in enumerate(rains):
if lack > 0:
if lack in full:
prev = full[lack]
idx = bisect.bisect(dry, prev)
if idx >= len(dry): return []
rst[dry[idx]] = lack
del dry[idx]
full[lack] = i
else:
dry.append(i)
for i in dry:
rst[i] = 1
return rst

Q4. 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree

Too long. See description in link

Such a nice question. I learnt a lot from this one.

Intuition

Iterator each edge

1. If the cost of MST without this edge increased, this is a critical edge . 
2. elif the cost of MST without this edge does not change, this is a Pseudo-Critical edge

Minimal Spanning Tree

Kruskal’s algorithm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Kruskal:
def minimal_spanning_tree(self, n: int, edges: List[List]) -> List[List]:
# Args:
# n: vertices 0, 1, 2, 3, ..... n-1
# edges: [edge, edge, edge, ...]
# edge = (from, to, weight)
arr = [i for i in range(n)]
def find(x):
while arr[x] != arr[arr[x]]: arr[x] = find(arr[x])
return arr[x]

edges = sorted(edges, key=lambda x: x[2])
ret = []
for f, t, w in edges:
rf, rt = find(f), find(t)
if rf != rt:
arr[rf] = rt
ret.append((f, t, w))

return ret if all(find(i)==find(0) for i in range(n)) else []

Prim’s algorithm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Prim:
def minimal_spanning_tree(self, n: int, edges: List[List]) -> List[List]:
# Args:
# n: vertices 0, 1, 2, 3, ..... n-1
# edges: [edge, edge, edge, ...]
# edge = (from, to, weight)
graph = defaultdict(dict)
for u, v, w in edges:
graph[u][v] = w
graph[v][u] = w

ret, pq = [], [(0, -1, 0)]
visited = set()

while pq:
w, u, v = heappop(pq)
if v in visited: continue
visited.add(v)
ret.append((u, v, w))
for vv, ww in graph[v].items():
if vv in visited: continue
heappush(pq, (ww, v, vv))
if len(visited) == n:
return ret[1:]
return []

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# A decent implementation based on Kruskal's algorithm
class Solution:
def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
def find(arr, x):
while arr[x] != arr[arr[x]]: arr[x] = find(arr, arr[x])
return arr[x]
def mst(exclude_idx, pre_exist_idx):
cost, visited = 0, set()
arr = [i for i in range(n)]
if pre_exist_idx != -1:
f, t, w, _ = edges[pre_exist_idx]
cost += w
arr[f] = t
for i, edge in enumerate(edges):
f, t, w, _ = edge
if i == exclude_idx: continue
rf, rt = find(arr, f), find(arr, t)
if rf != rt:
arr[rf] = rt
cost += w
return cost if all(find(arr, i) == find(arr, 0) for i in range(n)) else math.inf

edges = sorted([edge+[i] for i, edge in enumerate(edges)], key=lambda x: x[2])
best = mst(-1, -1)

A, B = [], []
for i in range(len(edges)):
if mst(i, -1) > best:
A.append(edges[i][3])
elif mst(-1, i) == best:
B.append(edges[i][3])
return [A, B]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from heapq import heappush, heappop

class Solution:
def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
def mst(exclude_idx, pre_exist_idx) -> List[List]:
pq = []
visited, cost = set(), 0
if pre_exist_idx == -1:
start = 0
else:
start = edges[pre_exist_idx][0]
pq.append((0, start, math.inf))
while pq:
w, t, idx = heappop(pq)
if t in visited or idx == exclude_idx: continue
visited.add(t)
cost += w
for tt, ww, iidx in adj[t]:
if tt in visited: continue
if iidx == pre_exist_idx:
cost += ww
ww = 0
heappush(pq, (ww, tt, iidx))
if len(visited) == n:
return cost
return math.inf
# Build adjacent dict
adj = defaultdict(list)
for i, edge in enumerate(edges):
f, t, w = edge
adj[f].append((t, w, i))
adj[t].append((f, w, i))

best = mst(-1, -1)
# Main logic
A, B = [], []
for i in range(len(edges)):
if mst(i, -1) > best:
A.append(i)
elif mst(-1, i) == best:
B.append(i)
return [A, B]

Summary

  • OMG! I want to be as strong as Aoxiang Cui
  • Kruskal’s algorithm is easier to implement during contest/interview
  • Prim’s algorithm can be implemented with heapq in python. Red-Black tree is not needed.