id,desc,data,time_limit,memory_limit,std,test,cate,difficulty 1,"Given a sequence of length $n$, there are $q$ queries to find the maximum value in specified intervals. Return the XOR sum of the answers to these $q$ queries. solution main function ```python class Solution: def solve(self, s, q): pass # write your code here``` Example 1: Input: num = [5,4,8,9,3,4,6] , q = [[0,3],[3,5]] Output: 0 Constraints: 1 <= n,q <= @data 1 <= s_i <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[1000, 500, 64], [8000, 4000, 80], [64000, 32000, 640]]","import math class Solution: def solve1(self, nums, queries): xor_sum = 0 for q in queries: l, r = q[0], q[1] max_val = -1 if l <= r: max_val = nums[l] for i in range(l + 1, r + 1): max_val = max(max_val, nums[i]) else: max_val = -2147483648 current_max = 0 for i in range(l, r + 1): current_max = max(current_max, nums[i]) xor_sum ^= current_max return xor_sum def solve2(self, nums, queries): n = len(nums) if n == 0: return 0 block_size = int(math.sqrt(n)) num_blocks = (n + block_size - 1) // block_size block_max = [-(10**10)] * num_blocks for i in range(n): block_index = i // block_size block_max[block_index] = max(block_max[block_index], nums[i]) def query(l, r): max_val = -(10**10) while l <= r and l % block_size != 0: max_val = max(max_val, nums[l]) l += 1 while l + block_size <= r + 1: block_index = l // block_size max_val = max(max_val, block_max[block_index]) l += block_size while l <= r: max_val = max(max_val, nums[l]) l += 1 return max_val xor_sum = 0 for q in queries: l, r = q[0], q[1] xor_sum ^= query(l, r) return xor_sum def solve3(self, nums, queries): n = len(nums) if n == 0: return 0 log_val = int(math.log2(n)) + 1 if n > 0 else 0 sparse = [[0] * log_val for _ in range(n)] for i in range(n): sparse[i][0] = nums[i] j = 1 while (1 << j) <= n: i = 0 while i + (1 << j) <= n: sparse[i][j] = max(sparse[i][j - 1], sparse[i + (1 << (j - 1))][j - 1]) i += 1 j += 1 def query(l, r): length = r - l + 1 k = length.bit_length() - 1 return max(sparse[l][k], sparse[r - (1 << k) + 1][k]) xor_sum = 0 for q in queries: l, r = q[0], q[1] xor_sum ^= query(l, r) return xor_sum ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) q = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) q.append((x, y)) solution = Solution() result = solution.solve(s, q) sys.stdout.write(str(result) + ""\n"")",data_structures,medium 2,"Given a sequence of length n, there are q queries for the product of a subarray. Each query's answer is mod p. Return the XOR sum of the answers to the q queries. solution main function ```python class Solution: def solve(self, s, q, p): pass # write your code here``` Example 1: Input: num = [5,4,8,9,3,4,6] , q = [[0,3],[3,5]], p = 10 Output: 8 Constraints: 1 <= n,q <= @data 1 <= s_i <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[1406, 500, 64], [11250, 4000, 80], [90000, 32000, 640]]","import math class Solution: def solve1(self, num, queries, p): xor_sum = 0 for query in queries: l = query[0] r = query[1] product = 1 for i in range(l, r + 1): product = (product * num[i]) % p xor_sum ^= product return xor_sum def solve2(self, num, queries, p): n = len(num) block_size = int(math.sqrt(n)) num_blocks = (n + block_size - 1) // block_size block_product = [1] * num_blocks for i in range(n): block_idx = i // block_size block_product[block_idx] = (block_product[block_idx] * num[i]) % p xor_sum = 0 for query in queries: l = query[0] r = query[1] product = 1 start_block = l // block_size end_block = r // block_size if start_block == end_block: for i in range(l, r + 1): product = (product * num[i]) % p else: for i in range(l, (start_block + 1) * block_size): product = (product * num[i]) % p for i in range(start_block + 1, end_block): product = (product * block_product[i]) % p for i in range(end_block * block_size, r + 1): product = (product * num[i]) % p xor_sum ^= product return xor_sum def solve3(self, num, queries, p): n = len(num) log_n = int(math.log2(n)) + 1 if n > 0 else 0 st = [[0] * log_n for _ in range(n)] for i in range(n): st[i][0] = num[i] % p for j in range(1, log_n): for i in range(n - (1 << j) + 1): st[i][j] = (st[i][j - 1] * st[i + (1 << (j - 1))][j - 1]) % p def query_product(l, r): product = 1 for j in range(log_n - 1, -1, -1): if (1 << j) <= r - l + 1: product = (product * st[l][j]) % p l += (1 << j) return product xor_sum = 0 for query in queries: l = query[0] r = query[1] xor_sum ^= query_product(l, r) return xor_sum ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) p = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) q = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) q.append((x, y)) solution = Solution() result = solution.solve(s, q, p) sys.stdout.write(str(result) + ""\n"")",data_structures,medium 3,"You are given a dictionary `dic` consisting of `n` strings (with characters numbered starting from 0), and then `m` strings `q`. Each string in `q` represents a query asking whether the string exists in the dictionary. If it does, return the corresponding string's index; otherwise, return 0. The final answer is the XOR sum of all the returned values. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: num = [""abc"",""ac"",""ab"",""cd""] , q = [""abc"",""cd"",""dc"",""ac""] Output: 2 Constraints: 1 <= n <= @data the length of string <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 500, 1000]",4000,"[[1000, 500, 64], [8000, 4000, 400], [64000, 32000, 3200]]","import sys class Solution: def solve1(self, dic, q): MASK = (1 << 64) - 1 bas = 13331 ans = 0 mp = {} for i, s in enumerate(dic): has = 0 for char in s: has = (((has * bas) & MASK) + ord(char)) & MASK if has not in mp: mp[has] = i else: mp[has] ^= i for s in q: has = 0 for char in s: has = (((has * bas) & MASK) + ord(char)) & MASK if has in mp: ans ^= mp[has] return ans def solve2(self, dic, q): ans = 0 for s_q in q: for i, s_dic in enumerate(dic): if s_dic == s_q: ans ^= i return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] b = [] i = 1 while i <= n: x = None s = next(it) a.append(s) i += 1 i = 1 while i <= m: x = None s = next(it) b.append(s) i += 1 solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result) + ""\n"")",string,medium 4,"There are $n$ elements. The $i$-th element has three attributes: $a_i$, $b_i$, and $c_i$. Let $f(i)$ denote the number of $j$'s that satisfy $a_j \leq a_i$, $b_j \leq b_i$, $c_j \leq c_i$, and $j \neq i$. Returns the result of all $f(i)$ ' xor ' solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: num = [[3,3,3],[2,3,3],[2,3,1],[3,1,1],[3,1,2],[1,3,1],[1,1,2],[1,2,2],[1,3,2],[1,2,1]] Output: 8 Constraints: 1 <= s.length <= @data s[i].length == 3 Each element in s is $[a_i,b_i,c_i]$ 1 <= $a_i,b_i,c_i$ <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[1000, 500, 64], [8000, 4000, 400], [64000, 32000, 3200]]","import sys class Solution: class Node: def __init__(self, a=0, b=0, c=0, t=0, sum_val=0): self.a = a self.b = b self.c = c self.t = t self.sum_val = sum_val def __eq__(self, other): return self.a == other.a and self.b == other.b and self.c == other.c class BIT: def __init__(self, lim=0): self.lim = lim self.tre = [0] * (lim + 1) def lowbit(self, x): return x & -x def insert(self, x, val): i = x while i <= self.lim: self.tre[i] += val i += self.lowbit(i) def query(self, x): sum_val = 0 i = x while i > 0: sum_val += self.tre[i] i -= self.lowbit(i) return sum_val def CDQ(self, l, r): if l >= r: return mid = (l + r) // 2 self.CDQ(l, mid) self.CDQ(mid + 1, r) i, j, k = l, mid + 1, l while i <= mid and j <= r: if self.s[i].b <= self.s[j].b: self.T.insert(self.s[i].c, self.s[i].t) self.f[k] = self.s[i] i += 1 else: self.s[j].sum_val += self.T.query(self.s[j].c) self.f[k] = self.s[j] j += 1 k += 1 while i <= mid: self.T.insert(self.s[i].c, self.s[i].t) self.f[k] = self.s[i] i += 1 k += 1 while j <= r: self.s[j].sum_val += self.T.query(self.s[j].c) self.f[k] = self.s[j] j += 1 k += 1 for i_clean in range(l, mid + 1): self.T.insert(self.s[i_clean].c, -self.s[i_clean].t) for i_copy in range(l, r + 1): self.s[i_copy] = self.f[i_copy] def solve1(self, num): num.sort() n = len(num) if n == 0: return 0 m = n unique_nodes = [] if n > 0: last_node = self.Node(num[0][0], num[0][1], num[0][2], 1, 0) unique_nodes.append(last_node) for i in range(1, n): current_point = num[i] if current_point[0] == last_node.a and \ current_point[1] == last_node.b and \ current_point[2] == last_node.c: last_node.t += 1 else: last_node = self.Node(current_point[0], current_point[1], current_point[2], 1, 0) unique_nodes.append(last_node) cnt = len(unique_nodes) self.s = unique_nodes self.f = [None] * (cnt + 1) self.ans = [0] * (n + 1) self.T = self.BIT(m) if cnt > 0: self.CDQ(0, cnt - 1) for node in self.s: count = node.sum_val + node.t - 1 self.ans[count] += node.t out = 0 for i in range(n): if self.ans[i] & 1: out ^= i return out def solve2(self, s): n = len(s) res = 0 for i in range(n): ai = s[i][0] bi = s[i][1] ci = s[i][2] cnt = 0 for j in range(n): if j == i: continue tj = s[j] if tj[0] <= ai and tj[1] <= bi and tj[2] <= ci: cnt += 1 res ^= cnt return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, 3 + 1): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")",data_structures,medium 5,"# Problem Statement Even after copying the paintings from famous artists for ten years, unfortunately, Eric is still unable to become a skillful impressionist painter. He wants to forget something, but the white bear phenomenon just keeps hanging over him. Eric still remembers $n$ pieces of impressions in the form of an integer array. He records them as $w_1, w_2, \ldots, w_n$. However, he has a poor memory of the impressions. For each $1 \leq i \leq n$, he can only remember that $l_i \leq w_i \leq r_i$. Eric believes that impression $i$ is unique if and only if there exists a possible array $w_1, w_2, \ldots, w_n$ such that $w_i \neq w_j$ holds for all $1 \leq j \leq n$ with $j \neq i$. Please help Eric determine whether impression $i$ is unique for every $1 \leq i \leq n$, **independently** for each $i$. Perhaps your judgment can help rewrite the final story. The main function of the solution is defined as: ```python class Solution: def solve(self, n, l, r): pass # write your code here``` The function should return the answer string. The answer string has length $n$, where the $i$-th character is '1' if impression $i$ is unique, and '0' otherwise. # Example 1: - Input: n = 2 l = [1, 1] r = [1, 1] - Output: 00 # Constraints: - $1 \leq n \leq @data$ - $1 \leq l[i] \leq r[i] \leq 2 * n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[100, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, l, r): cnt = [0] * (2 * n) pre = [0] * (2 * n + 1) for i in range(n): l[i] -= 1 if l[i] + 1 == r[i]: cnt[l[i]] += 1 for i in range(2 * n): pre[i + 1] = pre[i] + (1 if cnt[i] == 0 else 0) ans = [] for i in range(n): if l[i] + 1 < r[i]: if pre[l[i]] != pre[r[i]]: ans.append('1') else: ans.append('0') else: if cnt[l[i]] == 1: ans.append('1') else: ans.append('0') return """".join(ans) def solve2(self, n, l, r): ans = [] for i in range(n): is_i_unique = False for j in range(l[i], r[i] + 1): is_j_forced = False for k in range(n): if k == i: continue if l[k] == r[k] and l[k] == j: is_j_forced = True break if not is_j_forced: is_i_unique = True break if is_i_unique: ans.append('1') else: ans.append('0') return """".join(ans)","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) l = [0] * n r = [0] * n for i in range(n): l[i] = int(next(it)) r[i] = int(next(it)) solution = Solution() result = solution.solve(n, l, r) sys.stdout.write(str(result) + ""\n"")","binary,data_structures,greedy",hard 6,"# Problem Statement Robin's brother and mother are visiting, and Robin gets to choose the start day for each visitor. All days are numbered from $1$ to $n$. Visitors stay for $d$ continuous days, all of those $d$ days must be between day $1$ and $n$ inclusive. Robin has a total of $k$ risky 'jobs' planned. The $i$-th job takes place between days $l_i$ and $r_i$ inclusive, for $1 \le i \le k$. If a job takes place on any of the $d$ days, the visit overlaps with this job (the length of overlap is unimportant). Robin wants his brother's visit to overlap with the maximum number of **distinct jobs**, and his mother's the minimum. Find suitable start days for the visits of Robin's brother and mother. If there are multiple suitable days, choose the earliest one. The main function of the solution is defined as: ```python class Solution: def solve(self, n, d, k, l, r): pass # write your code here``` where: - return: pair of integers, the start days for Robin's brother and mother respectively. # Example 1: - Input: n = 2, d = 1, k = 1 l = [1], r = [2] - Output: (1, 1) # Constraints: - $1 \leq d, k \leq n \leq @data$ - $1 \leq l[i] \leq r[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, d, k, l, r): L = [0] * (n + 2) R = [0] * (n + 2) for i in range(k): ll = l[i] rr = r[i] L[ll - 1] += 1 R[rr] += 1 for i in range(1, n + 1): R[i] += R[i - 1] for i in range(n - 1, -1, -1): L[i] += L[i + 1] mx = -1 imx = -1 mn = n + 1 imn = -1 for i in range(n - d + 1): v = R[i] + L[i + d] if v > mx: mx = v imx = i + 1 if v < mn: mn = v imn = i + 1 return (imn, imx) def solve2(self, n, d, k, l, r): max_val = -1 min_val = k + 1 maxl = -1 minl = -1 for i in range(1, n - d + 2): count = 0 visit_end = i + d - 1 for j in range(k): if not (r[j] < i or l[j] > visit_end): count += 1 if count > max_val: max_val = count maxl = i if count < min_val: min_val = count minl = i return (maxl, minl) ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) d = int(next(it)) k = int(next(it)) l = [0] * k r = [0] * k for i in range(k): l[i] = int(next(it)) r[i] = int(next(it)) solution = Solution() result = solution.solve(n, d, k, l, r) sys.stdout.write(str(result[0]) + "" "" + str(result[1]) + ""\n"")",data_structures,hard 7,"# Problem Statement Polycarp was given an array $a$ of $n$ integers. He really likes triples of numbers, so for each $j$ ($1 \le j \le n - 2$) he wrote down a triple of elements $[a_j, a_{j + 1}, a_{j + 2}]$. Polycarp considers a pair of triples $b$ and $c$ beautiful if they differ in exactly one position, that is, one of the following conditions is satisfied: - $b_1 \ne c_1$ and $b_2 = c_2$ and $b_3 = c_3$; - $b_1 = c_1$ and $b_2 \ne c_2$ and $b_3 = c_3$; - $b_1 = c_1$ and $b_2 = c_2$ and $b_3 \ne c_3$. Find the number of beautiful pairs of triples among the written triples $[a_j, a_{j + 1}, a_{j + 2}]$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of beautiful pairs of triples among the pairs of the form [aj,aj+1,aj+2]. # Example 1: - Input: n = 5 a = [3, 2, 2, 2, 3] - Output: 2 # Constraints: - $3 \leq n \leq @data$ - $1 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import collections class Solution: def solve1(self, n, a): ans = 0 mp = [collections.defaultdict(int) for _ in range(3)] mp2 = collections.defaultdict(int) for i in range(n - 2): for j in range(3): v = None if j == 0: v = (a[i + 1], a[i + 2]) elif j == 1: v = (a[i + 2], a[i]) else: v = (a[i], a[i + 1]) ans += mp[j][v] for j in range(3): v = None if j == 0: v = (a[i + 1], a[i + 2]) elif j == 1: v = (a[i + 2], a[i]) else: v = (a[i], a[i + 1]) mp[j][v] += 1 current_triple = (a[i], a[i + 1], a[i + 2]) ans -= 3 * mp2[current_triple] mp2[current_triple] += 1 return ans def solve2(self, n, a): ans = 0 for i in range(n - 2): for j in range(n - 2): if i == j: continue if ((a[i] != a[j] and a[i+1] == a[j+1] and a[i+2] == a[j+2]) or (a[i] == a[j] and a[i+1] != a[j+1] and a[i+2] == a[j+2]) or (a[i] == a[j] and a[i+1] == a[j+1] and a[i+2] != a[j+2])): ans += 1 return ans // 2 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",data_structures,hard 8,"# Problem Statement Maxim has an array $a$ of $n$ integers and an array $b$ of $m$ integers ($m \le n$). Maxim considers an array $c$ of length $m$ to be good if the elements of array $c$ can be rearranged in such a way that at least $k$ of them match the elements of array $b$. For example, if $b = [1, 2, 3, 4]$ and $k = 3$, then the arrays $[4, 1, 2, 3]$ and $[2, 3, 4, 5]$ are good (they can be reordered as follows: $[1, 2, 3, 4]$ and $[5, 2, 3, 4]$), while the arrays $[3, 4, 5, 6]$ and $[3, 4, 3, 4]$ are not good. Maxim wants to choose every subsegment of array $a$ of length $m$ as the elements of array $c$. Help Maxim count how many selected arrays will be good. In other words, find the number of positions $1 \le l \le n - m + 1$ such that the elements $a_l, a_{l+1}, \dots, a_{l + m - 1}$ form a good array. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, a, b): pass # write your code here``` where: - return: the number of good arrays. # Example 1: - Input: n = 7, m = 4, k = 2 a = [4, 1, 2, 3, 4, 5, 6] b = [1, 2, 3, 4] - Output: 4 # Constraints: - $1 \leq k \leq m \leq n \leq @data$ - $1 \leq a[i], b[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, m, k, a, b): cnt = collections.Counter(b) ans = 0 good = 0 for i in range(m - 1): if cnt[a[i]] > 0: good += 1 cnt[a[i]] -= 1 for i in range(n - m + 1): if cnt[a[i + m - 1]] > 0: good += 1 cnt[a[i + m - 1]] -= 1 if good >= k: ans += 1 cnt[a[i]] += 1 if cnt[a[i]] > 0: good -= 1 return ans def solve2(self, n, m, k, a, b): ans = 0 b.sort() for i in range(n - m + 1): good = 0 pre = 0 num = 0 sub_array = a[i : i + m] for j in range(m): if pre != b[j]: if pre != 0: good += min(num, sub_array.count(pre)) num = 1 pre = b[j] if pre != 0: good += sub_array.count(pre) if good >= k: ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) a = [0] * n b = [0] * m for i in range(n): a[i] = int(next(it)) for i in range(m): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, k, a, b) sys.stdout.write(str(result) + ""\n"")","data_structures,two_pointers",medium 9,"# Problem Statement A progressive square of size $n$ is an $n \times n$ matrix. Maxim chooses three integers $a_{1,1}$, $c$, and $d$ and constructs a progressive square according to the following rules: $$ a_{i+1,j} = a_{i,j} + c $$ $$ a_{i,j+1} = a_{i,j} + d $$ For example, if $n = 3$, $a_{1,1} = 1$, $c=2$, and $d=3$, then the progressive square looks as follows: $$ \begin{pmatrix} 1 & 4 & 7 \\ 3 & 6 & 9 \\ 5 & 8 & 11 \end{pmatrix} $$ Last month Maxim constructed a progressive square and remembered the values of $n$, $c$, and $d$. Recently, he found an array $b$ of $n^2$ integers in random order and wants to make sure that these elements are the elements of **that specific** square. It can be shown that for any values of $n$, $a_{1,1}$, $c$, and $d$, there exists exactly one progressive square that satisfies all the rules. The main function of the solution is defined as: ```python class Solution: def solve(self, n, c, d, a): pass # write your code here``` where: - return ""YES"" if a progressive square for the given n, c, and d can be constructed from the array elements a, otherwise return ""NO"". # Example 1: - Input: n = 3, c = 2, d = 3 b = [3, 9, 6, 5, 7, 1, 10, 4, 8] - Output: NO # Constraints: - $1 \leq n * n \leq @data$ - $1 \leq c, d \leq 10^6$ - $1 \leq b[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, c, d, a): a.sort() b = [0] * (n * n) a11 = a[0] for i in range(n * n): row = i // n col = i % n b[i] = a11 + row * c + col * d b.sort() if a == b: return ""YES"" else: return ""NO"" def solve2(self, n, c, d, a): a.sort() x = a[0] size = n * n for i in range(size): target = x + (i // n) * c + (i % n) * d found = False for j in range(size): if a[j] == target: a[j] = -1 found = True break if not found: return ""NO"" return ""YES"" ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) c = int(next(it)) d = int(next(it)) a = [0] * (n * n) for i in range(n * n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, c, d, a) sys.stdout.write(str(result) + ""\n"")","sort,data_structures",medium 10,"# Problem Statement Iulia has $n$ glasses arranged in a line. The $i$-th glass has $a_i$ units of juice in it. Iulia drinks only from odd-numbered glasses, while her date drinks only from even-numbered glasses. To impress her date, Iulia wants to find a contiguous subarray of these glasses such that both Iulia and her date will have the same amount of juice in total if only the glasses in this subarray are considered. Please help her to do that. More formally, find out if there exists two indices $l$, $r$ such that $1 \leq l \leq r \leq n$, and $a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r} = a_{l + 1} + a_{l + 3} + \dots + a_{r-1}$ if $l$ and $r$ have the same parity and $a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r - 1} = a_{l + 1} + a_{l + 3} + \dots + a_{r}$ otherwise. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return ""YES"" if there exists a subarray satisfying the condition, and ""NO"" otherwise. # Example 1: - Input: n = 3 a = [1, 3, 2] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): s = {0} sum_val = 0 for i in range(n): sum_val += a[i] if i % 2 else -a[i] s.add(sum_val) return ""NO"" if len(s) == n + 1 else ""YES"" def solve2(self, n, a): for i in range(n): sum_val = 0 for j in range(i, n): sum_val += a[j] if j % 2 else -a[j] if sum_val == 0: return ""YES"" return ""NO"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,math",medium 11,"# Problem Statement In the summer, Vika likes to visit her country house. There is everything for relaxation: comfortable swings, bicycles, and a river. There is a wooden bridge over the river, consisting of $n$ planks. It is quite old and unattractive, so Vika decided to paint it. And in the shed, they just found cans of paint of $k$ colors. After painting each plank in one of $k$ colors, Vika was about to go swinging to take a break from work. However, she realized that the house was on the other side of the river, and the paint had not yet completely dried, so she could not walk on the bridge yet. In order not to spoil the appearance of the bridge, Vika decided that she would still walk on it, but only stepping on planks of the same color. Otherwise, a small layer of paint on her sole will spoil the plank of another color. Vika also has a little paint left, but it will only be enough to repaint **one** plank of the bridge. Now Vika is standing on the ground in front of the first plank. To walk across the bridge, she will choose some planks of the same color (after repainting), which have numbers $1 \le i_1 < i_2 < \ldots < i_m \le n$ (planks are numbered from $1$ from left to right). Then Vika will have to cross $i_1 - 1, i_2 - i_1 - 1, i_3 - i_2 - 1, \ldots, i_m - i_{m-1} - 1, n - i_m$ planks as a result of each of $m + 1$ steps. Since Vika is afraid of falling, she does not want to take too long steps. Help her and tell her the minimum possible maximum number of planks she will have to cross **in one step**, if she can repaint one (**or zero**) plank a different color while crossing the bridge. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a): pass # write your code here``` where: - return: the minimum possible maximum number of planks that Vika will have to step over in one step. # Example 1: - Input: n = 5, k = 2 a = [1, 1, 2, 1, 1] - Output: 0 # Constraints: - $1 \leq k \leq n \leq @data$ - $1 \leq c[i] \leq k$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 100, 64], [4000, 800, 80], [32000, 6400, 640]]","import sys class Solution: def solve1(self, n, k, c): lst = [-1] * k f = [[] for _ in range(k)] c_copy = [x - 1 for x in c] for i in range(n): color_idx = c_copy[i] f[color_idx].append(i - lst[color_idx] - 1) lst[color_idx] = i ans = n for i in range(k): f[i].append(n - lst[i] - 1) f[i].sort(reverse=True) res = f[i][0] // 2 if len(f[i]) > 1: res = max(res, f[i][1]) ans = min(ans, res) return ans def solve2(self, n, k, c): ans = n for i in range(1, k + 1): pre = -1 mx1 = 0 mx2 = 0 for j in range(n): if c[j] == i: x = j - pre if x > mx1: mx2 = mx1 mx1 = x elif x > mx2: mx2 = x pre = j x = n - pre if x > mx1: mx2 = mx1 mx1 = x elif x > mx2: mx2 = x ans = min(ans, max(mx2 - 1, (mx1 - 1) // 2)) return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a) sys.stdout.write(str(result) + ""\n"")","binary,data_structures,greedy,sort",hard 12,"# Problem Statement There is a deck of $n$ cards, each of which is characterized by its power. There are two types of cards: - a hero card, the power of such a card is always equal to $0$; - a bonus card, the power of such a card is always positive. You can do the following with the deck: - take a card from the top of the deck; - if this card is a bonus card, you can put it **on top** of your bonus deck or discard; - if this card is a hero card, then the power of **the top** card from your bonus deck is added to his power (if it is not empty), after that the hero is added to your army, and the used bonus discards. Your task is to use such actions to gather an army with the maximum possible total power. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum possible total power of the army that can be achieved. # Example 1: - Input: n = 5 s = [3, 3, 3, 0, 0] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $0 \leq s[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import heapq class Solution: def solve1(self, n, s): q = [] ans = 0 for i in range(n): if s[i] == 0: if q: ans += -heapq.heappop(q) else: heapq.heappush(q, -s[i]) return ans def solve2(self, n, s): ans = 0 for i in range(n): if s[i] == 0: max_val = 0 max_index = -1 for j in range(i): if s[j] > max_val: max_val = s[j] max_index = j if max_index != -1: ans += max_val s[max_index] = 0 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,greedy",medium 13,"# Problem Statement To destroy humanity, The Monster Association sent $n$ monsters to Earth's surface. The $i$-th monster has health $h_i$ and power $p_i$. With his last resort attack, True Spiral Incineration Cannon, Genos can deal $k$ damage to all monsters alive. In other words, Genos can reduce the health of all monsters by $k$ (if $k > 0$) with a single attack. However, after every attack Genos makes, the monsters advance. With their combined efforts, they reduce Genos' attack damage by the power of the $^\dagger$weakest monster $^\ddagger$alive. In other words, the minimum $p_i$ among all currently living monsters is subtracted from the value of $k$ after each attack. $^\dagger$The Weakest monster is the one with the least power. $^\ddagger$A monster is alive if its health is strictly greater than $0$. Will Genos be successful in killing all the monsters? The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, h, p): pass # write your code here``` where: - return: YES if Genos could kill all monsters and NO otherwise. # Example 1: - Input: n = 6, k = 7 h = [18, 5, 13, 9, 10, 1] p = [2, 7, 2, 1, 2, 6] - Output: YES # Constraints: - $1 \leq n, k \leq @data$ - $1 \leq h[i], p[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import heapq class Solution: def solve1(self, n, k, h, p): q = [] for i in range(n): heapq.heappush(q, (p[i], h[i])) cnt = k while q: power, health = heapq.heappop(q) if cnt >= health: continue heapq.heappush(q, (power, health)) k -= power if k <= 0: return ""NO"" cnt += k return ""YES"" def solve2(self, n, k, h, p): cnt = k while True: mn = float('inf') pos = -1 for i in range(n): if p[i] == 0: continue if p[i] < mn: mn = p[i] pos = i if pos == -1: break p[pos] = 0 if cnt >= h[pos]: continue k -= mn if k <= 0: return ""NO"" cnt += k return ""YES"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) h = [0] * n p = [0] * n for i in range(n): h[i] = int(next(it)) for i in range(n): p[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, h, p) sys.stdout.write(str(result) + ""\n"")","binary,data_structures,math,sort",medium 14,"A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i. Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [6,0,8,2,1,5] Output: 4 Example 2: Input: nums = [9,8,1,0,1,9,4,0,4,1] Output: 7 Constraints: 2 <= nums.length <= @data 0 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, nums): n = len(nums) indices_stack = [] for i in range(n): if not indices_stack or nums[indices_stack[-1]] > nums[i]: indices_stack.append(i) max_width = 0 for j in range(n - 1, -1, -1): while indices_stack and nums[indices_stack[-1]] <= nums[j]: max_width = max(max_width, j - indices_stack[-1]) indices_stack.pop() return max_width def solve2(self, nums): n = len(nums) max_width = 0 for i in range(n): for j in range(i + 1, n): if nums[i] <= nums[j]: max_width = max(max_width, j - i) return max_width ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result) + ""\n"")",two_pointers,medium 15,"There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti. Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares. Return an integer array ans where ans[i] represents the height described above after dropping the ith square. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: positions = [[1,2],[2,3],[6,1]] Output: [2,5,5] Example 2: Input: positions = [[100,100],[200,100]] Output: [100,100] Constraints: 1 <= positions.length <= @data 1 <= lefti <= 10^8 1 <= sideLengthi <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 500], [320000, 32000, 4000]]","import bisect class SegmentTree: def __init__(self, n): self.n = n self.size = 1 while self.size < n: self.size <<= 1 self.tree = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) def add_range(self, l, r, h): l += self.size r += self.size self.tree[l] = max(self.tree[l], h) self.tree[r] = max(self.tree[r], h) if l != r: if not (l & 1): self.lazy[l + 1] = max(self.lazy[l - 1], h) if r & 1: self.lazy[r - 1] = max(self.lazy[r - 1], h) l >>= 1 r >>= 1 while l != r: self.tree[l] = max(self.tree[2 * l], self.tree[2 * l + 1]) self.tree[r] = max(self.tree[2 * r], self.tree[2 * r + 1]) if l // 2 != r // 2: if not (l & 1): self.lazy[l + 1] = max(self.lazy[l + 1], h) if r & 1: self.lazy[r - 1] = max(self.lazy[r - 1], h) l >>= 1 r >>= 1 while l > 0: self.tree[l] = max(self.tree[2 * l], self.tree[2 * l + 1]) l >>= 1 def max_range(self, l, r): l += self.size r += self.size max_val = max(self.tree[l], self.tree[r]) while l // 2 != r // 2: if not (l & 1): max_val = max(self.tree[l + 1], max_val) max_val = max(self.lazy[l + 1], max_val) if r & 1: max_val = max(self.tree[r - 1], max_val) max_val = max(self.lazy[r - 1], max_val) max_val = max(max_val, self.lazy[l]) max_val = max(max_val, self.lazy[r]) l >>= 1 r >>= 1 max_val = max(max_val, self.lazy[r]) while l // 2 > 0: max_val = max(self.lazy[l], max_val) l >>= 1 return max_val def global_max(self): return self.max_range(0, self.n - 1) class Solution: def solve1(self, positions): n = len(positions) qans = [0] * n for i in range(n): left = positions[i][0] size = positions[i][1] right = left + size qans[i] += size for j in range(i + 1, n): left2 = positions[j][0] size2 = positions[j][1] right2 = left2 + size2 if left2 < right and left < right2: qans[j] = max(qans[j], qans[i]) ans = [] cur = -1 for x in qans: cur = max(cur, x) ans.append(cur) return ans def solve2(self, positions): points_set = set() for rect in positions: points_set.add(rect[0]) points_set.add(rect[0] + rect[1] - 1) points = sorted(list(points_set)) st = SegmentTree(len(points)) results = [] max_height = 0 for rect in positions: x_1 = rect[0] x_2 = rect[0] + rect[1] - 1 l = bisect.bisect_left(points, x_1) r = bisect.bisect_left(points, x_2) cur_height = st.max_range(l, r) new_height = rect[1] + cur_height max_height = max(new_height, max_height) st.add_range(l, r, new_height) results.append(max_height) return results ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) s.append(temp) solution = Solution() result = solution.solve(s) out = [] for it_value in result: out.append(str(it_value)) sys.stdout.write("" "".join(out))",data_structures,hard 16,"There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). solution main function ```python class Solution: def solve(self, rat): pass # write your code here``` Example 1: Input: rating = [2,5,3,4,1] Output: 3 Example 2: Input: rating = [2,1,3] Output: 0 Constraints: n == rating.length 3 <= n <= @data 1 <= rating[i] <= 10^5 All the integers in rating are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",12000,"[[10000, 1000, 100], [80000, 8000, 800], [640000, 64000, 6400]]","import bisect from array import array class Solution: def update(self, index, val): i = index + 1 while i < len(self.tree): self.tree[i] += val i += i & -i def sum(self, r): res = 0 i = r + 1 while i > 0: res += self.tree[i] i -= i & -i return res def solve1(self, rating): n = len(rating) max_val = max(rating) if rating else 0 self.tree = array('I', [0]) * (max_val + 2) lo = array('I', [0]) * n for i in range(n): cur_rate = rating[i] ridx = cur_rate lo[i] = self.sum(ridx) self.update(ridx, 1) self.tree = array('I', [0]) * (max_val + 2) ans = 0 for i in range(n - 1, -1, -1): ridx = rating[i] hi_i = self.sum(max_val) - self.sum(ridx) ans += lo[i] * hi_i ans += (i - lo[i]) * (n - 1 - i - hi_i) self.update(ridx, 1) ans = ((ans + (1 << 31)) % (1 << 32)) - (1 << 31) return ans def solve2(self, rating): n = len(rating) ans = 0 for j in range(1, n - 1): iless = 0 imore = 0 kless = 0 kmore = 0 for i in range(j): if rating[i] < rating[j]: iless += 1 elif rating[i] > rating[j]: imore += 1 for k in range(j + 1, n): if rating[k] < rating[j]: kless += 1 elif rating[k] > rating[j]: kmore += 1 ans += iless * kmore + imore * kless return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) rat = [] for i in range(1, n + 1): x = int(next(it)) rat.append(x) solution = Solution() result = solution.solve(rat) sys.stdout.write(str(result))",data_structures,medium 17,"Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string. solution main function ```python class Solution: def solve(self, str_var): pass # write your code here``` Example 1: Input: s = ""abc"" Output: 3 Example 2: Input: s = ""aaa"" Output: 6 Constraints: 1 <= s.length <= @data s consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: def solve1(self, s): t = ""$#"" for c in s: t += c t += '#' n = len(t) t += '!' f = [0] * n iMax = 0 rMax = 0 ans = 0 for i in range(1, n): if i <= rMax: f[i] = min(rMax - i + 1, f[2 * iMax - i]) else: f[i] = 1 while t[i + f[i]] == t[i - f[i]]: f[i] += 1 if i + f[i] - 1 > rMax: iMax = i rMax = i + f[i] - 1 ans += (f[i] // 2) return ans def solve2(self, s): n = len(s) ans = 0 for i in range(2 * n - 1): l = i // 2 r = i // 2 + i % 2 while l >= 0 and r < n and s[l] == s[r]: l -= 1 r += 1 ans += 1 return ans ","import sys def main(): data = sys.stdin.read().split() str_var = data[0] if data else """" solution = Solution() result = solution.solve(str_var) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,easy 18,"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. solution main function ```python class Solution: def solve(self, num, k): pass # write your code here``` Example 1: Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Example 2: Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= @data 0 <= matrix[i][j] <= 10^6 1 <= k <= m * n Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[1000, 625, 312], [8000, 5000, 2500], [64000, 40000, 20000]]","import heapq class Solution: def solve1(self, matrix, k): m = len(matrix) n = len(matrix[0]) results = [] for i in range(m): for j in range(n): if i > 0: matrix[i][j] ^= matrix[i - 1][j] if j > 0: matrix[i][j] ^= matrix[i][j - 1] if i > 0 and j > 0: matrix[i][j] ^= matrix[i - 1][j - 1] results.append(matrix[i][j]) results.sort(reverse=True) return results[k - 1] def solve2(self, matrix, k): m = len(matrix) n = len(matrix[0]) pq = [] for i in range(m): for j in range(n): matrix[i][j] ^= (matrix[i - 1][j] if i > 0 else 0) \ ^ (matrix[i][j - 1] if j > 0 else 0) \ ^ (matrix[i - 1][j - 1] if i > 0 and j > 0 else 0) if len(pq) < k: heapq.heappush(pq, matrix[i][j]) else: if pq[0] < matrix[i][j]: heapq.heapreplace(pq, matrix[i][j]) return pq[0] ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) num = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) num.append(temp) solution = Solution() result = solution.solve(num, k) sys.stdout.write(str(result))",bit_manipulation,medium 19,"Given an array of integers arr. We want to select three indices i, j and k where (0 <= i < j <= k < arr.length). Let's define a and b as follows: a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1] b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k] Note that ^ denotes the bitwise-xor operation. Return the number of triplets (i, j and k) Where a == b. solution main function ```python class Solution: def solve(self, arr): pass # write your code here``` Example 1: Input: arr = [2,3,1,6,7] Output: 4 Example 2: Input: arr = [2,3,1,6,7] Output: 4 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 10^8 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import collections class Solution: def solve1(self, arr): ans = 0 n = len(arr) for i in range(n - 1): temp = arr[i] for j in range(i + 1, n): temp ^= arr[j] if temp == 0: ans += j - i return ans def solve2(self, arr): n = len(arr) cnt = {} total = {} ans = 0 s = 0 for k in range(n): val = arr[k] if (s ^ val) in cnt: ans += cnt[s ^ val] * k - total[s ^ val] cnt[s] = cnt.get(s, 0) + 1 total[s] = total.get(s, 0) + k s ^= val return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) arr = [] for i in range(1, n + 1): x = int(next(it)) arr.append(x) solution = Solution() result = solution.solve(arr) sys.stdout.write(str(result))","dp,bit_manipulation",medium 20,"You are given an integer array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all. Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount. solution main function ```python class Solution: def solve(self, price): pass # write your code here``` Example 1: Input: prices = [8,4,6,2,3] Output: [4,2,4,2,3] Example 2: Input: prices = [1,2,3,4,5] Output: [1,2,3,4,5] Constraints: 1 <= prices.length <= @data 1 <= prices[i] <= 10^3 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections from typing import List class Solution: def solve1(self, prices: List[int]) -> List[int]: n = len(prices) ans = [0] * n st = [] for i in range(n - 1, -1, -1): while st and st[-1] > prices[i]: st.pop() if not st: ans[i] = prices[i] else: ans[i] = prices[i] - st[-1] st.append(prices[i]) return ans def solve2(self, prices: List[int]) -> List[int]: n = len(prices) ans = [] for i in range(n): discount = 0 for j in range(i + 1, n): if prices[j] <= prices[i]: discount = prices[j] break ans.append(prices[i] - discount) return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) price = [] for i in range(1, n + 1): x = int(next(it)) price.append(x) solution = Solution() result = solution.solve(price) out = [] for val in result: out.append(str(val)) sys.stdout.write("" "".join(out))",data_structures,easy 21,"Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. solution main function ```python class Solution: def solve(self, num1, num2): pass # write your code here``` Example 1: Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Example 2: Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5 Constraints: 1 <= nums1.length, nums2.length <= @data 0 <= nums1[i], nums2[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import collections class Solution: mod = 1000000009 base = 113 def qPow(self, x, n): ret = 1 while n: if n & 1: ret = ret * x % self.mod x = x * x % self.mod n >>= 1 return ret def check(self, A, B, length): hashA = 0 for i in range(length): hashA = (hashA * self.base + A[i]) % self.mod bucketA = {hashA} mult = self.qPow(self.base, length - 1) for i in range(length, len(A)): hashA = ((hashA - A[i - length] * mult % self.mod + self.mod) % self.mod * self.base + A[i]) % self.mod bucketA.add(hashA) hashB = 0 for i in range(length): hashB = (hashB * self.base + B[i]) % self.mod if hashB in bucketA: return True for i in range(length, len(B)): hashB = ((hashB - B[i - length] * mult % self.mod + self.mod) % self.mod * self.base + B[i]) % self.mod if hashB in bucketA: return True return False def solve1(self, A, B): left, right = 1, min(len(A), len(B)) + 1 while left < right: mid = (left + right) >> 1 if self.check(A, B, mid): left = mid + 1 else: right = mid return left - 1 def maxLength(self, A, B, addA, addB, length): ret = 0 k = 0 for i in range(length): if A[addA + i] == B[addB + i]: k += 1 else: k = 0 ret = max(ret, k) return ret def solve2(self, A, B): n, m = len(A), len(B) ret = 0 for i in range(n): length = min(m, n - i) maxlen = self.maxLength(A, B, i, 0, length) ret = max(ret, maxlen) for i in range(m): length = min(n, m - i) maxlen = self.maxLength(A, B, 0, i, length) ret = max(ret, maxlen) return ret ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) num1 = [] num2 = [] for i in range(1, n + 1): x = int(next(it)) num1.append(x) for i in range(1, m + 1): x = int(next(it)) num2.append(x) solution = Solution() result = solution.solve(num1, num2) sys.stdout.write(str(result))","dp,binary,string",medium 22,"The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). 1 2 3 4 5 6 7 8 9 * 0 # '*' and '#' are red,the others are blue Given an integer n, return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 1 Output: 10 Example 2: Input: n = 2 Output: 20 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000000, 1000000000]",4000,"[[20000, 2000, 200], [160000, 16000, 1600], [1280000, 128000, 12800]]","class Solution: mod = 10**9 + 7 def solve1(self, n): moves = [ [4, 6], [6, 8], [7, 9], [4, 8], [3, 9, 0], [], [1, 7, 0], [2, 6], [1, 3], [2, 4] ] d = [[0] * 10 for _ in range(2)] for i in range(10): d[1][i] = 1 for i in range(2, n + 1): x = i & 1 for j in range(10): d[x][j] = 0 for k in moves[j]: d[x][j] = (d[x][j] + d[x ^ 1][k]) % self.mod res = 0 for x_val in d[n % 2]: res = (res + x_val) % self.mod return res def mul(self, lth, rth): res = [[0] * len(rth[0]) for _ in range(len(lth))] for k in range(len(lth[0])): for i in range(len(lth)): for j in range(len(rth[0])): res[i][j] = (res[i][j] + lth[i][k] * rth[k][j]) % self.mod return res def solve2(self, n): base = [ [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0, 0, 0] ] res = [[1] * 10] base2 = [[0] * 10 for _ in range(10)] for i in range(10): base2[i][i] = 1 n -= 1 while n > 0: if n & 1: base2 = self.mul(base2, base) base = self.mul(base, base) n >>= 1 res = self.mul(res, base2) ret = 0 for x in res[0]: ret = (ret + x) % self.mod return ret ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,medium 23,"You are given a 0-indexed integer array nums of length n. You can perform the following operation as many times as you want: Pick an index i that you haven’t picked before, and pick a prime p strictly less than nums[i], then subtract p from nums[i]. Return 1 if you can make nums a strictly increasing array using the above operation and 0 otherwise. A strictly increasing array is an array whose each element is strictly greater than its preceding element. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [4,9,6,10] Output: 1 Example 2: Input: nums = [6,8,11,12] Output: 1 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= @data*10 nums.length == n Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums): maxElement = max(nums) sieve = [1] * (maxElement + 1) if maxElement >= 1: sieve[1] = 0 i = 2 while i * i <= maxElement: if sieve[i] == 1: for j in range(i * i, maxElement + 1, i): sieve[j] = 0 i += 1 currValue = 1 i = 0 while i < len(nums): difference = nums[i] - currValue if difference < 0: return 0 if difference == 0 or sieve[difference] == 1: i += 1 currValue += 1 else: currValue += 1 return 1 def checkPrime(self, x): if x < 2: return 0 i = 2 while i * i <= x: if x % i == 0: return 0 i += 1 return 1 def solve2(self, nums): for i in range(len(nums)): bound = 0 if i == 0: bound = nums[0] else: bound = nums[i] - nums[i - 1] if bound <= 0: return 0 largestPrime = 0 for j in range(bound - 1, 1, -1): if self.checkPrime(j): largestPrime = j break nums[i] = nums[i] - largestPrime return 1 ","import sys data = sys.stdin.buffer.read().split() it = iter(data) try: n = int(next(it)) except StopIteration: n = 0 num = [] i = 1 while i <= n: try: x = int(next(it)) except StopIteration: break num.append(x) i += 1 solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))","math,greedy,binary",hard 24,"You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal. The chemistry of a team is equal to the product of the skills of the players on that team. Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: skill = [3,2,5,1,3,4] Output: 22 Example 2: Input: skill = [3,4] Output: 12 Constraints: 2 <= skill.length <= @data skill.length is even. 1 <= skill[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 10000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, skill): n = len(skill) totalSkill = 0 skillFrequency = [0] * 2001 for playerSkill in skill: totalSkill += playerSkill skillFrequency[playerSkill] += 1 if n == 0: return 0 num_teams = n // 2 if totalSkill % num_teams != 0: return -1 targetTeamSkill = totalSkill // num_teams totalChemistry = 0 for playerSkill in skill: partnerSkill = targetTeamSkill - playerSkill if partnerSkill < 0 or partnerSkill >= len(skillFrequency): return -1 if skillFrequency[partnerSkill] == 0: return -1 totalChemistry += playerSkill * partnerSkill skillFrequency[partnerSkill] -= 1 return totalChemistry // 2 def solve2(self, skill): skill.sort() if not skill: return 0 total = skill[0] + skill[-1] chemistry = 0 i, j = 0, len(skill) - 1 while i < j: if skill[i] + skill[j] != total: return -1 chemistry += skill[i] * skill[j] i += 1 j -= 1 return chemistry ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))","two_pointers,sort",easy 25,"You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: nums = [1,2,3] Output: 4 Example 2: Input: nums = [1,3,3] Output: 4 Constraints: 1 <= nums.length <= @data -10^6 <= nums[i] <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums): n = len(nums) answer = 0 stk = [] for right in range(n + 1): while stk and (right == n or nums[stk[-1]] >= nums[right]): mid = stk.pop() left = stk[-1] if stk else -1 answer -= nums[mid] * (right - mid) * (mid - left) stk.append(right) stk.pop() for right in range(n + 1): while stk and (right == n or nums[stk[-1]] <= nums[right]): mid = stk.pop() left = stk[-1] if stk else -1 answer += nums[mid] * (right - mid) * (mid - left) stk.append(right) return answer def solve2(self, nums): n = len(nums) answer = 0 for left in range(n): min_val = nums[left] max_val = nums[left] for right in range(left, n): max_val = max(max_val, nums[right]) min_val = min(min_val, nums[right]) answer += max_val - min_val return answer ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(a) sys.stdout.write(str(result) + ""\n"")",math,medium 26,"# Problem Statement Given an array with $n$ intergers $a_1, a_2, \dots, a_n$, and $m$ operations, the $i$-th operation is * $1, p, b$: Given $p$ and $b$, update $a_p = b$. * $2, l, r$: Given $l$ and $r$, return the sum of values in interval $[l, r]$. The solution's main function is: ```python class Solution: def solve(self, n, a, m, ops): pass # write your code here``` where: - `op` is an array of 3 integers, $op[0]$ is the operation type, $op[1]$ and $op[2]$ are the parameters of the operation. - return the xor value of all operation 2 answers, please return the result in a `long long` type. # Example 1 - Input: n = 5 a = [1, 2, 3, 4, 5] m = 3 ops = [[2, 1, 3], [1, 2, 6], [2, 1, 3]] - Output: 12 # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq a_i, b \leq 10^6$ - $1 \leq p, l, r \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[5000, 50000, 100000]",4000,"[[500, 64, 64], [4000, 400, 64], [32000, 3200, 400]]","import math class Solution: def solve1(self, n, a, m, ops): b = [0] * (n + 1) def add(i, x): while i <= n: b[i] += x i += i & -i def ask(i): res = 0 while i > 0: res += b[i] i -= i & -i return res for i in range(n): add(i + 1, a[i]) ans = 0 for op, l, r in ops: if op == 1: add(l, -a[l - 1]) a[l - 1] = r add(l, r) else: ans = ans ^ (ask(r) - ask(l - 1)) return ans def solve2(self, n, a, m, ops): ans = 0 for op, l, r in ops: if op == 1: a[l - 1] = r else: sum_val = 0 for i in range(l - 1, r): sum_val += a[i] ans = ans ^ sum_val return ans def solve3(self, n, a, m, ops): block_size = int(math.sqrt(n)) + 1 block_count = (n + block_size - 1) // block_size block_sum = [0] * block_count for i in range(n): block_sum[i // block_size] += a[i] result = 0 for op in ops: op_type = op[0] if op_type == 1: p = op[1] - 1 b = op[2] block_index = p // block_size block_sum[block_index] += b - a[p] a[p] = b elif op_type == 2: l = op[1] - 1 r = op[2] - 1 current_sum = 0 start_block = l // block_size end_block = r // block_size if start_block == end_block: for i in range(l, r + 1): current_sum += a[i] else: for i in range(l, (start_block + 1) * block_size): current_sum += a[i] for i in range(start_block + 1, end_block): current_sum += block_sum[i] for i in range(end_block * block_size, r + 1): current_sum += a[i] result ^= current_sum return result ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(n): a.append(int(next(it))) m = int(next(it)) ops = [] for i in range(m): x0 = int(next(it)) x1 = int(next(it)) x2 = int(next(it)) ops.append([x0, x1, x2]) solution = Solution() result = solution.solve(n, a, m, ops) sys.stdout.write(str(result) + ""\n"")",data_structures,medium 27,"You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""aacaba"" Output: 2 Example 2: Input: s = ""abcd"" Output: 1 Constraints: 1 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, s): ls = [0] * 26 rs = [0] * 26 res = 0 lu = 0 ru = 0 for char in s: idx = ord(char) - ord('a') rs[idx] += 1 if rs[idx] == 1: ru += 1 for char in s: idx = ord(char) - ord('a') rs[idx] -= 1 ls[idx] += 1 if rs[idx] == 0: ru -= 1 if ls[idx] == 1: lu += 1 res += (ru == lu) return res def solve2(self, s): n = len(s) res = 0 for i in range(1, n): left_mask = 0 for j in range(i): left_mask |= 1 << (ord(s[j]) - 97) right_mask = 0 for j in range(i, n): right_mask |= 1 << (ord(s[j]) - 97) if left_mask.bit_count() == right_mask.bit_count(): res += 1 return res ","import sys def main(): data = sys.stdin.read().split() s = """" if len(data) > 0: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","string,dynamic_programming,other",medium 28,"You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s. Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: s = ""aabaaaacaabc"", k = 2 Output: 8 Example 2: Input: s = ""a"", k = 1 Output: -1 Constraints: 1 <= s.length <= @data s consists of only the letters 'a', 'b', and 'c'. 0 <= k <= s.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s, k): n = len(s) freq = [0] * 3 for char in s: freq[ord(char) - ord('a')] += 1 if any(f < k for f in freq): return -1 ans = n l = 0 for r in range(n): freq[ord(s[r]) - ord('a')] -= 1 while any(f < k for f in freq): freq[ord(s[l]) - ord('a')] += 1 l += 1 ans = min(ans, n - (r - l + 1)) return ans def solve2(self, s, k): n = len(s) if k == 0: return 0 ca = cb = cc = 0 for ch in s: if ch == 'a': ca += 1 elif ch == 'b': cb += 1 else: cc += 1 if ca < k or cb < k or cc < k: return -1 ans = n aL = bL = cL = 0 for i in range(n + 1): aR = bR = cR = 0 j = 0 while i + j <= n: if aL + aR >= k and bL + bR >= k and cL + cR >= k: if i + j < ans: ans = i + j break if i + j == n: break ch = s[n - 1 - j] if ch == 'a': aR += 1 elif ch == 'b': bR += 1 else: cR += 1 j += 1 if i < n: ch = s[i] if ch == 'a': aL += 1 elif ch == 'b': bL += 1 else: cL += 1 return ans ","import sys data = sys.stdin.read().split() if len(data) >= 2: s = data[0] k = int(data[1]) else: s = """" k = 0 solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result) + ""\n"")",string,hard 29,"On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed. solution main function ```python class Solution: def solve(self, stones): pass # write your code here``` Example 1: Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Constraints: 1 <= stones.length <= @data 0 <= xi, yi <= 10^4 No two stones are at the same coordinate point. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[10000, 1000, 100], [80000, 8000, 800], [640000, 64000, 6400]]","class Solution: def solve(self, stones): num_stones = len(stones) if num_stones <= 1: return 0 parent = list(range(num_stones)) rank = [0] * num_stones def find(index): while parent[index] != index: parent[index] = parent[parent[index]] index = parent[index] return index def union(index_a, index_b): root_a = find(index_a) root_b = find(index_b) if root_a == root_b: return False if rank[root_a] < rank[root_b]: parent[root_a] = root_b elif rank[root_a] > rank[root_b]: parent[root_b] = root_a else: parent[root_b] = root_a rank[root_a] += 1 return True components = num_stones row_representative = {} col_representative = {} for index, (x_coord, y_coord) in enumerate(stones): if x_coord in row_representative: if union(index, row_representative[x_coord]): components -= 1 else: row_representative[x_coord] = index if y_coord in col_representative: if union(index, col_representative[y_coord]): components -= 1 else: col_representative[y_coord] = index return num_stones - components ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) stones = [] i = 1 while i <= n: x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) stones.append(temp) i += 1 solution = Solution() result = solution.solve(stones) sys.stdout.write(str(result))","graph,data_structures",medium 30,"You are given two 0-indexed strings str1 and str2. In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes 'c', and so on, and 'z' becomes 'a'. Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise. Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: str1 = ""abc"", str2 = ""ad"" Output: 1 Example 2: Input: str1 = ""zc"", str2 = ""ad"" Output: 1 Constraints: 1 <= str1.length,str2.length <= @data str1 and str2 consist of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 93], [32000, 3200, 750]]","import math class Solution: def solve1(self, str1, str2): str2Index = 0 lengthStr1 = len(str1) lengthStr2 = len(str2) str1Index = 0 while str1Index < lengthStr1 and str2Index < lengthStr2: if (str1[str1Index] == str2[str2Index] or ord(str1[str1Index]) + 1 == ord(str2[str2Index]) or ord(str1[str1Index]) - 25 == ord(str2[str2Index])): str2Index += 1 str1Index += 1 return str2Index == lengthStr2 def solve2(self, str1, str2): j = 0 n2 = len(str2) if n2 == 0: return True for ch in str1: if ch == str2[j] or (ch != 'z' and ord(ch) + 1 == ord(str2[j])) or (ch == 'z' and str2[j] == 'a'): j += 1 if j == n2: return True return j == n2 ","import sys def main(): data = sys.stdin.read().strip().split() a = """" b = """" if len(data) > 0: a = data[0] if len(data) > 1: b = data[1] solution = Solution() result = solution.solve(a, b) sys.stdout.write(""1"" if result else ""0"") if __name__ == ""__main__"": main()","two_pointers,string",medium 31,"Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays. solution main function ```python class Solution: def solve(self, num, k): pass # write your code here``` Example 1: Input: nums = [1,1,2,1,1], k = 3 Output: 2 Example 2: Input: nums = [2,4,6], k = 1 Output: 0 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^5 1 <= k <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, nums, k): return self.atMost(nums, k) - self.atMost(nums, k - 1) def solve2(self, nums, k): res = 0 n = len(nums) for i in range(n): odd = 0 for j in range(i, n): if nums[j] & 1: odd += 1 if odd == k: res += 1 elif odd > k: break return res def atMost(self, nums, k): windowSize = 0 subarrays = 0 start = 0 for end in range(len(nums)): windowSize += nums[end] % 2 while windowSize > k: windowSize -= nums[start] % 2 start += 1 subarrays += end - start + 1 return subarrays ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num, k) sys.stdout.write(str(result))",math,medium 32,"# Problem Statement Ball is the teacher in Paperfold University. The seats of his classroom are arranged in $2$ rows with $m$ seats each. Ball is teaching $a + b + c$ monkeys, and he wants to assign as many monkeys to a seat as possible. Ball knows that $a$ of them only want to sit in row $1$, $b$ of them only want to sit in row $2$, and $c$ of them have no preference. Only one monkey may sit in each seat, and each monkey's preference must be followed if it is seated. What is the maximum number of monkeys that Ball can seat? The main function of the solution is defined as: ```python class Solution: def solve(self, m, a, b, c): pass # write your code here``` where: - return: the maximum number of monkeys you can seat. # Example 1: - Input: m = 2, a = 1, b = 2, c = 3 - Output: 4 # Constraints: - $1 \leq m, a, b, c \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 100000, 10000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, m, a, b, c): x = m y = m ans = 0 take = min(x, a) x -= take ans += take take = min(y, b) y -= take ans += take take = min(x + y, c) ans += take return ans def solve2(self, m, a, b, c): x = m y = m ans = 0 take = min(x, a) x -= take ans += take take = min(y, b) y -= take ans += take take = min(x + y, c) ans += take return ans ","import sys data = sys.stdin.read().strip().split() m = int(data[0]) a = int(data[1]) b = int(data[2]) c = int(data[3]) solution = Solution() result = solution.solve(m, a, b, c) sys.stdout.write(str(result) + ""\n"")",math,easy 33,"You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 Example 2: Input: matrix = [[1,0,1,0,1]] Output: 3 Constraints: m == matrix.length n == matrix[i].length 1 <= m * n <= @data matrix[i][j] is either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, matrix): m = len(matrix) n = len(matrix[0]) ans = 0 for j in range(n): for i in range(1, m): if matrix[i][j] == 1: matrix[i][j] += matrix[i - 1][j] for i in range(m): matrix[i].sort(reverse=True) for j in range(n): ans = max(ans, matrix[i][j] * (j + 1)) return ans def solve2(self, matrix): m = len(matrix) n = len(matrix[0]) if m else 0 if m == 0 or n == 0: return 0 ans = 0 for i in range(m): max_h = 0 for j in range(n): if matrix[i][j] == 1: if i > 0: matrix[i][j] = matrix[i - 1][j] + 1 else: matrix[i][j] = 1 if matrix[i][j] > max_h: max_h = matrix[i][j] else: matrix[i][j] = 0 h = 1 while h <= max_h: cnt = 0 for j in range(n): if matrix[i][j] >= h: cnt += 1 area = cnt * h if area > ans: ans = area h += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))","sort,greedy",medium 34,"Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. solution main function ```python class Solution: def solve(self, mat): pass # write your code here``` Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Constraints: 1 <= mat.length <= @data 1 <= mat[0].length <= @data 0 <= mat[i][j] <= 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, matrix: list[list[int]]) -> int: if not matrix or not matrix[0]: return 0 row = len(matrix) col = len(matrix[0]) result = 0 prev = 0 dp = [0] * (col + 1) for i in range(1, row + 1): for j in range(1, col + 1): if matrix[i - 1][j - 1] == 1: temp = dp[j] dp[j] = 1 + min(prev, dp[j - 1], dp[j]) prev = temp result += dp[j] else: dp[j] = 0 return result def solve2(self, matrix: list[list[int]]) -> int: if not matrix or not matrix[0]: return 0 n = len(matrix) m = len(matrix[0]) result = 0 for i in range(n): for j in range(m): if matrix[i][j] != 1: continue result += 1 max_size = min(n - i, m - j) size = 1 while size < max_size: r = i + size c = j + size ok = True for x in range(i, r): if matrix[x][c] != 1: ok = False break if ok: for y in range(j, c + 1): if matrix[r][y] != 1: ok = False break if not ok: break result += 1 size += 1 return result ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) mat = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) mat.append(temp) solution = Solution() result = solution.solve(mat) sys.stdout.write(str(result))",dp,medium 35,"# Problem Statement You are given a tree with `n` nodes numbered from `1` to `n`. There are `k` distinct colors numbered from `1` to `k`. Every node `u` has a set `C_u` of colors. Let `s = sum(|C_u|)` be the total number of (node, color) pairs. You will receive `q` queries. For each query `(u, v)`, let `P` be the set of nodes on the simple path between `u` and `v` (inclusive). Your task is to compute: - the number of colors that appear in every set `C_w` for all `w` on the path from `u` to `v`, i.e. `| ⋂_{w ∈ P} C_w |`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, s, q, edges, colors, queries): pass # write your code here``` where: - `n`: number of nodes in the tree - `k`: number of distinct colors - `s`: total number of (node, color) assignments - `q`: number of queries - `edges`: `n-1` edges (u, v), 1-based, describing the tree - `colors`: `s` pairs (v, x), meaning color `x` is in `C_v` (all pairs are distinct) - `queries`: `q` pairs (u, v), each a path query - return: a vector of `q` integers, the answers in input order, printed space-separated # Example 1: - Input: - n = 3, k = 5, s = 5, q = 4 - edges = [(1,3), (2,1)] - colors = [(1,1), (1,2), (1,3), (1,4), (1,5)] - queries = [(1,3), (2,3), (1,2), (1,1)] - Output: - [0, 0, 0, 5] # Constraints: - $1 \leq n, k, q \leq @data$ - $1 \leq s \leq \min(n \cdot k, @data)$ - Edges form a tree - All `s` pairs in `colors` are pairwise distinct - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[5000, 2500, 1250], [40000, 20000, 10000], [320000, 160000, 80000]]","import sys class Solution: def solve1(self, n, k, s, q, edges, colors, queries): g = [[] for _ in range(n)] for e in edges: u = e[0] - 1 v = e[1] - 1 g[u].append(v) g[v].append(u) f = [[] for _ in range(n)] for px in colors: v = px[0] - 1 x = px[1] - 1 f[v].append([x, v]) tin = [0] * n tout = [0] * n T = 0 par = [-1] * n idx = [0] * n st = [] mark = [-1] * k if n > 0: st.append(0) par[0] = -1 while st: v = st[-1] if idx[v] == 0: T += 1 tin[v] = T for pc in f[v]: mark[pc[0]] = pc[1] if idx[v] < len(g[v]): u = g[v][idx[v]] idx[v] += 1 if u == par[v]: continue par[u] = v for i in range(len(f[u])): c = f[u][i][0] if mark[c] != -1: f[u][i][1] = mark[c] st.append(u) continue for pc in f[v]: mark[pc[0]] = -1 T += 1 tout[v] = T st.pop() def isAnc(x, y): return tin[x] <= tin[y] and tout[y] <= tout[x] qs = [[] for _ in range(n)] for i in range(q): u = queries[i][0] - 1 v = queries[i][1] - 1 if len(f[u]) > len(f[v]): u, v = v, u qs[v].append((u, i)) ans = [0] * q colMark = [-1] * k memo = [(-1, -1) for _ in range(n)] for v in range(n): for pc in f[v]: colMark[pc[0]] = pc[1] for qq in qs[v]: u = qq[0] qi = qq[1] if memo[u][0] == v: ans[qi] = memo[u][1] continue cnt = 0 for pc in f[u]: c = pc[0] verU = pc[1] verV = colMark[c] if verV != -1: if isAnc(verU, v) and isAnc(verV, u): cnt += 1 ans[qi] = cnt memo[u] = (v, cnt) for pc in f[v]: colMark[pc[0]] = -1 return ans def solve2(self, n, k, s, q, edges, colors, queries): if n <= 0: return [0] * q parent = [-1] * (n + 1) depth = [0] * (n + 1) parent[1] = 1 changed = True while changed: changed = False for a, b in edges: pa = parent[a] pb = parent[b] if pa != -1 and pb == -1: parent[b] = a depth[b] = depth[a] + 1 changed = True elif pb != -1 and pa == -1: parent[a] = b depth[a] = depth[b] + 1 changed = True def has_color(node, color): for v, x in colors: if v == node and x == color: return True return False def lca(u, v): while depth[u] > depth[v]: u = parent[u] while depth[v] > depth[u]: v = parent[v] while u != v: u = parent[u] v = parent[v] return u res = [] for u0, v0 in queries: l = lca(u0, v0) cnt = 0 for x in range(1, k + 1): if not has_color(u0, x): continue if not has_color(v0, x): continue ok = True w = u0 while w != l: if not has_color(w, x): ok = False break w = parent[w] if not ok: continue w = v0 while w != l: if not has_color(w, x): ok = False break w = parent[w] if not ok: continue if not has_color(l, x): continue cnt += 1 res.append(cnt) return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = int(next(it)) q = int(next(it)) edges = [] for i in range(n - 1): u = int(next(it)) v = int(next(it)) edges.append((u, v)) colors = [] for i in range(s): v = int(next(it)) x = int(next(it)) colors.append((v, x)) queries = [] for i in range(q): u = int(next(it)) v = int(next(it)) queries.append((u, v)) solution = Solution() result = solution.solve(n, k, s, q, edges, colors, queries) out_lines = [] for i in range(len(result)): if i + 1 == len(result): out_lines.append(str(result[i])) else: out_lines.append(str(result[i]) + "" "") sys.stdout.write("""".join(out_lines))","graph,data_structures",hard 36,"There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. solution main function ```python class Solution: def solve(self, row): pass # write your code here``` Example 1: Input: row = [0,2,1,3] Output: 1 Example 2: Input: row = [3,2,0,1] Output: 0 Constraints: 2n == row.length 2 <= n <= @data n is even. 0 <= row[i] < 2n Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 20, 30]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import sys class DSU: def __init__(self, n): self.parent = list(range(n)) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def unionset(self, x, y): rootx = self.find(x) rooty = self.find(y) if rootx != rooty: self.parent[rootx] = rooty class Solution: def solve1(self, row): n = len(row) // 2 obj = DSU(n) for i in range(0, len(row), 2): grp1 = row[i] // 2 grp2 = row[i+1] // 2 obj.unionset(grp1, grp2) ans = 0 for i in range(n): if obj.find(i) == i: ans += 1 return n - ans def solve2(self, row): ans = 0 n = len(row) i = 0 while i < n: partner = row[i] ^ 1 if row[i + 1] != partner: ans += 1 j = i + 2 while j < n and row[j] != partner: j += 1 row[i + 1], row[j] = row[j], row[i + 1] i += 2 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) row = [] for i in range(1, n + 1): x = int(next(it)) row.append(x) solution = Solution() result = solution.solve(row) sys.stdout.write(str(result))","graph,other",hard 37,"# Problem Statement For a positive integer $a$, define the sequence $b$ by $ b_0 = 1,\quad b_n = a^{\,b_{n-1}} \quad (n \ge 1). $ We say that $a$ is $m$-tetrative if there exists $N \ge 0$ such that $b_n \equiv 1 \pmod m$ for all $n \ge N$. Given $m = x \cdot y \cdot z$, compute the density of the set of $m$-tetrative positive integers, i.e. $ \lim_{n\to\infty}\frac{\left\lvert\{a \in \{1,\dots,n\}\mid a\text{ is }m\text{-tetrative}\}\right\rvert}{n}. $ It can be shown the density is a rational number whose denominator is not divisible by $998244353$. You should output this density modulo $998244353$ as $p \cdot q^{-1} \bmod 998244353$, where the exact answer is the irreducible fraction $p/q$ and $q \not\equiv 0 \pmod{998244353}$. The main function of the solution is defined as: ```python class Solution: def solve(self, x, y, z): pass # write your code here``` where: - `x, y, z`: positive integers with $1 \le x,y,z \le @data$, and $m = xyz \ge 2$ - return: the density modulo $998244353$ # Example 1: - Input: 5 1 1 - Output: 499122177 # Constraints: - $1 \leq x,y,z \leq @data$ - $m = xyz \ge 2$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 100000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: MOD = 998244353 primes = [] inited = False def modPow(self, a, e, mod): r = 1 a %= mod while e > 0: if e & 1: r = (r * a) % mod a = (a * a) % mod e >>= 1 return r def sievePrimes(self, limit, primes_out): is_comp = [False] * (limit + 1) primes_out.clear() for i in range(2, limit + 1): if not is_comp[i]: primes_out.append(i) for p in primes_out: v = p * i if v > limit: break is_comp[v] = True if i % p == 0: break def factorSmallInt(self, n, primes, out): for p in primes: if p * p > n: break if n % p == 0: c = 0 while n % p == 0: n //= p c += 1 out[p] = out.get(p, 0) + c if n > 1: out[n] = out.get(n, 0) + 1 def solve1(self, x, y, z): if not Solution.inited: self.sievePrimes(1000, Solution.primes) Solution.inited = True fm = {} self.factorSmallInt(x, Solution.primes, fm) self.factorSmallInt(y, Solution.primes, fm) self.factorSmallInt(z, Solution.primes, fm) fphim = {} for p in fm: t = p - 1 if t > 1: tmp = {} self.factorSmallInt(t, Solution.primes, tmp) for q, c in tmp.items(): fphim[q] = fphim.get(q, 0) + c prod = 1 for q, beta in fphim.items(): if q in fm: continue qk = self.modPow(q, beta, self.MOD) inv_q = self.modPow(q, self.MOD - 2, self.MOD) term = (1 + (qk - 1 + self.MOD) % self.MOD * inv_q) % self.MOD prod = (prod * term) % self.MOD mmod = (x % self.MOD) * (y % self.MOD) % self.MOD mmod = (mmod * (z % self.MOD)) % self.MOD ans = prod * self.modPow(mmod, self.MOD - 2, self.MOD) % self.MOD return ans def solve2(self, x, y, z): mod = self.MOD m = x * y * z n = m phi = m p = 2 while p * p <= n: if n % p == 0: while n % p == 0: n //= p phi = phi // p * (p - 1) p = 3 if p == 2 else p + 2 if n > 1: phi = phi // n * (n - 1) tmp = phi prod = 1 q = 2 while q * q <= tmp: if tmp % q == 0: beta = 0 while tmp % q == 0: tmp //= q beta += 1 if m % q != 0: qk = pow(q % mod, beta, mod) term = (1 + ((qk - 1) * pow(q, mod - 2, mod)) % mod) % mod prod = (prod * term) % mod q = 3 if q == 2 else q + 2 if tmp > 1: q = tmp if m % q != 0: qk = q % mod term = (1 + ((qk - 1) * pow(q, mod - 2, mod)) % mod) % mod prod = (prod * term) % mod inv_m = pow(m % mod, mod - 2, mod) ans = prod * inv_m % mod return ans","import sys data = sys.stdin.buffer.read().split() x = int(data[0]) y = int(data[1]) z = int(data[2]) solution = Solution() result = solution.solve(x, y, z) sys.stdout.write(str(result) + ""\n"")",math,hard 38,"Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. Return the maximum product you can get modulo 998244353. If n = 1, the answer is considered 0 because it cannot be split into at least two positive integers. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 1 Output: 0 Example 2: Input: n = 2 Output: 1 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 1000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: mod = 998244353 def power(self, x, y): temp = 1 while y > 0: if y & 1: temp = temp * x % self.mod x = x * x % self.mod y >>= 1 return temp def solve1(self, n): if n <= 3: return n - 1 quotient = n // 3 remainder = n % 3 if remainder == 0: return self.power(3, quotient) elif remainder == 1: return (self.power(3, quotient - 1) * 4) % self.mod else: return (self.power(3, quotient) * 2) % self.mod def solve2(self, n): if n <= 3: return n - 1 q = n // 3 r = n % 3 res = 1 if r == 0: while q > 0: res = (res * 3) % self.mod q -= 1 return res elif r == 1: q -= 1 while q > 0: res = (res * 3) % self.mod q -= 1 return (res * 4) % self.mod else: while q > 0: res = (res * 3) % self.mod q -= 1 return (res * 2) % self.mod","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,medium 39,"A teacher of abacus arithmetic in a certain school used a test method to quickly test the ability of abacus arithmetic addition. He randomly generated a set of positive integers, each with different numbers, and asked the students to answer: How many of these numbers are exactly equal to the sum of two other (different) numbers in the set? Recently the teacher gave some test questions, please help to find out the answers. solution main function ```python class Solution: def solve(self, n, num): pass # write your code here``` Pass in parameters: 1 integer, n. An array with num containing n positive integers. Return parameters: An integer representing the answer to the quiz question Example 1: Input: n=4,num=[1, 2, 3, 4] Output: 2 Constraints: 3≤n≤@data, 1≤num[i] ≤10000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 20, 100]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, int_vector): num = int_vector num.sort() m = 0 for i in range(2, n): found = False for j in range(i - 1): for k in range(j + 1, i): if num[j] + num[k] == num[i]: m += 1 found = True break if found: break return m def solve2(self, n, int_vector): cnt = 0 for i in range(n): target = int_vector[i] found = False for j in range(n): if j == i: continue for k in range(j + 1, n): if k == i: continue if int_vector[j] + int_vector[k] == target: cnt += 1 found = True break if found: break return cnt ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(n, num) sys.stdout.write(str(result) + ""\n"")",greedy,medium 40,"There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Start at the 1st friend. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. The last friend you counted leaves the circle and loses the game. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. Else, the last friend in the circle wins the game. Given the number of friends, n, and an integer k, return the winner of the game. solution main function ```python class Solution: def solve(self, n, k): pass # write your code here``` Example 1: Input: n = 5, k = 2 Output: 3 Example 2: Input: n = 6, k = 5 Output: 1 Constraints: 1 <= k <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: def solve1(self, n, k): ans = 0 for i in range(1, n + 1): ans = (ans + k) % i return ans + 1 def solve2(self, n, k): ans = 0 for i in range(1, n + 1): ans = (ans + k) % i return ans + 1 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, k) sys.stdout.write(str(result))",math,medium 41,"You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. For each index i, names[i] and heights[i] denote the name and height of the ith person. Return names sorted in descending order by the people's heights. solution main function ```python class Solution: def solve(self, s, h): pass # write your code here``` Example 1: Input: names = [""Mary"",""John"",""Emma""], heights = [180,165,170] Output: [""Mary"",""Emma"",""John""] Example 2: Input: names = [""Alice"",""Bob"",""Bob""], heights = [155,185,150] Output: [""Bob"",""Alice"",""Bob""] Constraints: n == names.length == heights.length 1 <= n <= @data 1 <= names[i].length <= 20 1 <= heights[i] <= 10^5 names[i] consists of lower and upper case English letters. All the values of heights are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 125, 64], [4000, 1000, 500], [32000, 8000, 4000]]","import math class Solution: def solve1(self, names, heights): n = len(heights) indexes = list(range(n)) indexes.sort(key=lambda i: heights[i], reverse=True) res = [names[i] for i in indexes] return res def solve2(self, names, heights): n = len(heights) for i in range(n): max_idx = i max_h = heights[i] j = i + 1 while j < n: if heights[j] > max_h: max_h = heights[j] max_idx = j j += 1 if max_idx != i: heights[i], heights[max_idx] = heights[max_idx], heights[i] names[i], names[max_idx] = names[max_idx], names[i] return names ","import sys data = sys.stdin.read().split() it = 0 if it < len(data): n = int(data[it]) it += 1 else: n = 0 s = [] h = [] i = 1 while i <= n: if it < len(data): x = data[it] it += 1 else: x = """" s.append(x) i += 1 i = 1 while i <= n: if it < len(data): x = int(data[it]) it += 1 else: x = 0 h.append(x) i += 1 solution = Solution() result = solution.solve(s, h) out = [] for it in result: out.append(str(it)) sys.stdout.write("" "".join(out))",bit_manipulation,easy 42,"# Problem Statement You are given a tree$^{\dagger}$. In one zelda-operation you can do follows: - Choose two vertices of the tree $u$ and $v$; - Compress all the vertices on the path from $u$ to $v$ into one vertex. In other words, all the vertices on path from $u$ to $v$ will be erased from the tree, a new vertex $w$ will be created. Then every vertex $s$ that had an edge to some vertex on the path from $u$ to $v$ will have an edge to the vertex $w$. Determine the minimum number of zelda-operations required for the tree to have only one vertex. $^{\dagger}$A tree is a connected acyclic undirected graph. The main function of the solution is defined as: ```python class Solution: def solve(self, n, edges): pass # write your code here``` where: - `n` is the number of vertices - `edges` is the array of edges (u, v) - Return the minimum number of zelda-operations # Example 1: - Input: n = 4 edges = [(1, 2), (1, 3), (3, 4)] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 64], [4000, 2000, 400], [32000, 16000, 3200]]","import collections class Solution: def solve1(self, n, edges): deg = [0] * n for x, y in edges: deg[x - 1] += 1 deg[y - 1] += 1 leaf_count = deg.count(1) ans = (leaf_count + 1) // 2 return ans def solve2(self, n, edges): leaf_count = 0 for i in range(1, n + 1): deg = 0 for u, v in edges: if u == i or v == i: deg += 1 if deg == 1: leaf_count += 1 return (leaf_count + 1) // 2 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) edges = [] for i in range(n - 1): u = int(next(it)) v = int(next(it)) edges.append((u, v)) solution = Solution() result = solution.solve(n, edges) sys.stdout.write(str(result) + ""\n"")","tree,greedy",medium 43,"# Problem Statement You are given a list of $n$ integers $a_1, a_2, \dots, a_n$. You need to pick $8$ elements from the list and use them as coordinates of four points. These four points should be corners of a rectangle which has its sides parallel to the coordinate axes. Your task is to pick coordinates in such a way that the resulting rectangle has the maximum possible area. The rectangle can be degenerate, i. e. its area can be $0$. Each integer can be used as many times as it occurs in the list (or less). The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return : the maximum area of the rectangle, or $-1$ if it is impossible to form a rectangle. # Example 1: - Input: n = 8 a = [0, 0, -1, 2, 2, 1, 1, 3] - Output: -1 # Constraints: - $8 \leq n \leq @data$ - $-10^4 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): a.sort() min1 = float('inf') min2 = float('inf') max1 = float('-inf') max2 = float('-inf') pre = 1E9 for i in range(n): if a[i] != pre: pre = a[i] continue pre = 1E9 if a[i] < min1: min2 = min1 min1 = a[i] elif a[i] < min2: min2 = a[i] elif a[i] > max1: max2 = max1 max1 = a[i] elif a[i] > max2: max2 = a[i] if min1 == float('inf') or min2 == float('inf') or max1 == float('-inf') or max2 == float('-inf'): return -1 return max((max1 - min1) * (max2 - min2), (max2 - min1) * (max1 - min2)) def solve2(self, n, a): a.sort() min1 = 10**18 min2 = 10**18 max1 = -10**18 max2 = -10**18 pairs = 0 i = 0 while i + 1 < n: if a[i] == a[i + 1]: v = a[i] pairs += 1 if v < min1: min2 = min1 min1 = v elif v < min2: min2 = v if v > max1: max2 = max1 max1 = v elif v > max2: max2 = v i += 2 else: i += 1 if pairs < 4: return -1 return max((max1 - min1) * (max2 - min2), (max2 - min1) * (max1 - min2)) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","sort,greedy",hard 44,"Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. solution main function ```python class Solution: def solve(self, str_val, n): pass # write your code here``` Example 1: Input: s = ""00110110"", k = 2 Output: 1 Example 2: Input: s = ""0110"", k = 1 Output: 1 Constraints: 1 <= s.length <= @data s[i] is either '0' or '1'. 1 <= k <= 20 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[1000, 312, 171], [8000, 2500, 1375], [64000, 20000, 11000]]","import math class Solution: def solve1(self, s, k): n = len(s) if k > n: return False vis = [False] * (1 << k) cur = 0 for i in range(k): cur = (cur << 1) + (s[i] == '1') vis[cur] = True mask = (1 << k) - 1 for i in range(k, n): cur = (cur << 1) + (s[i] == '1') cur &= mask vis[cur] = True for v in vis: if not v: return False return True def solve2(self, s, k): n = len(s) if k > n: return False if (1 << k) > n - k + 1: return False mask = (1 << k) - 1 init_cur = 0 for i in range(k): init_cur = (init_cur << 1) + (s[i] == '1') for target in range(1 << k): if init_cur == target: continue cur = init_cur found = False for i in range(k, n): cur = ((cur << 1) + (s[i] == '1')) & mask if cur == target: found = True break if not found: return False return True ","import sys data = sys.stdin.read().split() it = iter(data) str_val = next(it) n = int(next(it)) solution = Solution() result = solution.solve(str_val, n) out = int(result) if isinstance(result, bool) else result sys.stdout.write(str(out))","string,bit_manipulation",medium 45,"You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: arr = [4,3,2,1,0] Output: 1 Example 2: Input: arr = [1,0,2,3,4] Output: 4 Constraints: n == arr.length 1 <= n <= @data 0 <= arr[i] < n All the elements of arr are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, arr: List[int]) -> int: n = len(arr) chunks = 0 maxElement = 0 for i in range(n): maxElement = max(maxElement, arr[i]) if maxElement == i: chunks += 1 return chunks def solve2(self, arr: List[int]) -> int: n = len(arr) chunks = 0 for i in range(n): m = arr[0] k = 1 while k <= i: if arr[k] > m: m = arr[k] k += 1 if m == i: chunks += 1 return chunks","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return num = [] i = 1 while i <= n: try: x = int(next(it)) except StopIteration: break num.append(x) i += 1 solution = Solution() result = solution.solve(num) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","sort,greedy",medium 46,"You are given a positive integer array nums. The element sum is the sum of all the elements in nums. The digit sum is the sum of all the digits (not necessarily distinct) that appear in nums. Return the absolute difference between the element sum and digit sum of nums. Note that the absolute difference between two integers x and y is defined as |x - y|. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [1,15,6,3] Output: 9 Example 2: Input: nums = [1,2,3,4] Output: 0 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 2000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, nums): elementSum = 0 digitSum = 0 for i in range(len(nums)): elementSum += nums[i] n = nums[i] while n > 0: lastDigit = n % 10 digitSum += lastDigit n = n // 10 absoluteDifference = abs(elementSum - digitSum) return absoluteDifference def solve2(self, nums): elementSum = 0 digitSum = 0 for x in nums: elementSum += x n = x while n > 0: digitSum += n % 10 n //= 10 return abs(elementSum - digitSum) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))","sort,greedy",easy 47,"# Problem Statement You are given an array $a$ of length $n$. Start with $c = 0$. Then, for each $i$ from $1$ to $n$ (in increasing order) do **exactly one** of the following: - Option $1$: set $c$ to $c + a_i$. - Option $2$: set $c$ to $|c + a_i|$, where $|x|$ is the absolute value of $x$. Let the maximum final value of $c$ after the procedure described above be equal to $k$. Find the number of unique procedures that result in $c = k$. Two procedures are different if at any index $i$, one procedure chose option $1$ and another chose option $2$, even if the value of $c$ is equal for both procedures after that turn. Since the answer may be large, output it modulo $998\,244\,353$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return the the number of unique procedures that result in c=k, modulo 998244353. # Example 1: - Input: n = 4 a = [2, -5, 3, -3] - Output: 12 # Constraints: - $2 \leq n \leq @data$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): mod = 998244353 cnt1 = 1 cnt2 = 1 c1 = 0 c2 = 0 for i in range(n): pre1 = c1 pre2 = c2 c1 = max(pre1 + a[i], abs(pre2 + a[i])) c2 = pre2 + a[i] if pre1 + a[i] == abs(pre2 + a[i]): if pre1 == pre2: cnt1 = cnt1 * 2 % mod cnt2 = cnt2 * 2 % mod else: cnt1 = (cnt1 * 2 + cnt2) % mod elif c1 == pre1 + a[i]: cnt1 = cnt1 * 2 % mod if c2 >= 0: cnt2 = cnt2 * 2 % mod else: cnt1 = cnt2 return cnt1 def solve2(self, n, a): mod = 998244353 maxc = None cnt = 0 total = 1 << n for mask in range(total): c = 0 for i in range(n): s = c + a[i] if (mask >> i) & 1: c = s if s >= 0 else -s else: c = s if maxc is None or c > maxc: maxc = c cnt = 1 elif c == maxc: cnt += 1 if cnt >= mod: cnt -= mod return cnt % mod ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",dp,hard 48,"There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes: At the first minute, color any arbitrary unit cell blue. Every minute thereafter, color blue every uncolored cell that touches a blue cell Return the number of colored cells at the end of n minutes. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 1 Output: 1 Example 2: Input: n = 2 Output: 5 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n: int) -> int: return n * n + (n - 1) * (n - 1) def solve2(self, n: int) -> int: total = 0 for minute in range(1, n + 1): if minute == 1: total += 1 else: total += 4 * (minute - 1) return total ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,medium 49,"# Problem Statement Rudolf has a string $s$ of length $n$. Rudolf considers the string $s$ to be ugly if it contains the substring$^\dagger$ ""pie"" or the substring ""map"", otherwise the string $s$ will be considered beautiful. For example, ""ppiee"", ""mmap"", ""dfpiefghmap"" are ugly strings, while ""mathp"", ""ppiiee"" are beautiful strings. Rudolf wants to shorten the string $s$ by removing some characters to make it beautiful. The main character doesn't like to strain, so he asks you to make the string beautiful by removing the minimum number of characters. He can remove characters from **any** positions in the string (not just from the beginning or end of the string). $^\dagger$ String $a$ is a substring of $b$ if there exists a **consecutive** segment of characters in string $b$ equal to $a$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - the return value is the minimum number of characters to be removed to make the string beautiful # Example 1: - Input: n = 9 s = ""mmapnapie"" - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $s[i]$ is a lowercase letter - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): ans = 0 for i in range(n): if i + 3 <= n and s[i:i + 3] == ""pie"": ans += 1 if i + 3 <= n and s[i:i + 3] == ""map"": ans += 1 if i + 5 <= n and s[i:i + 5] == ""mapie"": ans -= 1 return ans def solve2(self, n, s): ans = 0 for i in range(n): if i + 2 < n: if s[i] == 'p' and s[i + 1] == 'i' and s[i + 2] == 'e': ans += 1 if s[i] == 'm' and s[i + 1] == 'a' and s[i + 2] == 'p': ans += 1 if i + 4 < n: if s[i] == 'm' and s[i + 1] == 'a' and s[ i + 2] == 'p' and s[i + 3] == 'i' and s[i + 4] == 'e': ans -= 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","math,dp,greedy,string",easy 50,"# Problem Statement Vika and her friends went shopping in a mall, which can be represented as a rectangular grid of rooms with sides of length $n$ and $m$. Each room has coordinates $(a, b)$, where $1 \le a \le n, 1 \le b \le m$. Thus we call a hall with coordinates $(c, d)$ a neighbouring for it if $|a - c| + |b - d| = 1$. Tired of empty fashion talks, Vika decided to sneak away unnoticed. But since she hasn't had a chance to visit one of the shops yet, she doesn't want to leave the mall. After a while, her friends noticed Vika's disappearance and started looking for her. Currently, Vika is in a room with coordinates $(x, y)$, and her $k$ friends are in rooms with coordinates $(x_1, y_1)$, $(x_2, y_2)$, ... $, (x_k, y_k)$, respectively. The coordinates can coincide. Note that all the girls **must** move to the neighbouring rooms. Every minute, first Vika moves to one of the adjacent to the side rooms of her choice, and then each friend (**seeing Vika's choice**) also chooses one of the adjacent rooms to move to. If **at the end of the minute** (that is, after all the girls have moved on to the neighbouring rooms) at least one friend is in the same room as Vika, she is caught and all the other friends are called. Tell us, can Vika run away from her annoying friends forever, or will she have to continue listening to empty fashion talks after some time? The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, x, y, a): pass # write your code here``` where: - `n` and `m` are the size of the mall, `k` is the number of friends - `x` and `y` are Vika's initial position - `a` is the initial position of the friends - return ""YES"" if Vika can run away from her friends forever, otherwise return ""NO"" # Example 1: - Input: n = 2, m = 2, k = 2 x = 1, y = 1 a = [(1, 1), (1, 2)] - Output: NO # Constraints: - $1 \leq n, m, k \leq @data$ - $1 \leq x, x_i \leq n$ - $1 \leq y, y_i \leq m$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, m, k, x, y, a): caught = False for i in range(k): X = a[i][0] Y = a[i][1] if (x + y + X + Y) % 2 == 0: caught = True return ""NO"" if caught else ""YES"" def solve2(self, n, m, k, x, y, a): p = (x + y) & 1 for i in range(k): if ((a[i][0] + a[i][1]) & 1) == p: return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) x = int(next(it)) y = int(next(it)) a = [] for _ in range(k): X = int(next(it)) Y = int(next(it)) a.append((X, Y)) solution = Solution() result = solution.solve(n, m, k, x, y, a) sys.stdout.write(str(result) + ""\n"")","graph,math",medium 51,"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. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: target = [1,2,3,2,1] Output: 3 Example 2: Input: target = [3,1,1,2] Output: 4 Constraints: 1 <= target.length <= @data 1 <= target[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math from typing import List class Solution: def solve1(self, target: List[int]) -> int: if not target: return 0 noOfOperations = target[0] for i in range(1, len(target)): if target[i] > target[i - 1]: noOfOperations += (target[i] - target[i - 1]) return noOfOperations def solve2(self, target: List[int]) -> int: if not target: return 0 res = target[0] prev = target[0] i = 1 n = len(target) while i < n: curr = target[i] if curr > prev: res += curr - prev prev = curr i += 1 return res","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return s = [] i = 1 while i <= n: try: x = int(next(it)) except StopIteration: break s.append(x) i += 1 solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","dynamic_programming,greedy,other",hard 52,"Yangtze River Yacht Club set up $n$yacht rental station on the Yangtze River $1,2,\cdots,n$. Visitors can hire their yacht at these yacht hire stations and return it at any of the yacht hire stations downstream. The rental between the yacht rental station $i$and the yacht rental station $j$is $r(i,j)$($1\le i\lt j\le n$). Try to design an algorithm to calculate the minimum rental required from the yacht rental station $1 to the yacht rental station $n$. solution main function ```python class Solution: def solve(self, n, r): pass # write your code here``` Pass in parameters: 1 integer n. A two-dimensional vector array $n-1$row is a semi-matrix $r(i,j)$($1\le i f[i] + r[i - 1][j - i - 1]: f[j] = f[i] + r[i - 1][j - i - 1] return f[n] def solve2(self, n, r): if n <= 1: return 0 cuts = n - 2 best = None for mask in range(1 << cuts): total = 0 i = 1 for pos in range(cuts): j = pos + 2 if (mask >> pos) & 1: total += r[i - 1][j - i - 1] i = j total += r[i - 1][n - i - 1] if best is None or total < best: best = total return 0 if best is None else best ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) r = [] for i in range(1, n): temp = [] for j in range(1, n - i + 1): x = int(next(it)) temp.append(x) r.append(temp) solution = Solution() result = solution.solve(n, r) sys.stdout.write(str(result) + ""\n"")","dp,graph",medium 53,"# Problem Statement You are given an array consisting of $n$ integers $a_1$, $a_2$, ..., $a_n$. Initially $a_x = 1$, all other elements are equal to $0$. You have to perform $m$ operations. During the $i$-th operation, you choose two indices $c$ and $d$ such that $l_i \le c, d \le r_i$, and swap $a_c$ and $a_d$. Calculate the number of indices $k$ such that it is possible to choose the operations so that $a_k = 1$ in the end. The main function of the solution is defined as: ```python class Solution: def solve(self, n, x, m, l, r): pass # write your code here``` where: - return: the number of indices k such that it is possible to choose the operations so that ak=1 in the end. # Example 1: - Input: n = 6, x = 4, m = 3 l = [1,2,5] r = [6,3,5] - Output: 6 # Constraints: - $1 \leq m \leq @data$ - $1 \leq x \leq n \leq 10^9$ - $1 \leq l[i] \leq r[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve(self, n, x, m, l, r): cl = x cr = x for i in range(m): if max(l[i], cl) <= min(r[i], cr): cl = min(l[i], cl) cr = max(r[i], cr) return cr - cl + 1 ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) x = int(next(it)) m = int(next(it)) l = [0] * m r = [0] * m for i in range(m): l[i] = int(next(it)) r[i] = int(next(it)) solution = Solution() result = solution.solve(n, x, m, l, r) sys.stdout.write(str(result) + ""\n"")","math,two_pointers",hard 54,"# Problem Statement: YunQian is standing on an infinite plane with the Cartesian coordinate system on it. In one move, she can move to the diagonally adjacent point on the top right or the adjacent point on the left. That is, if she is standing on point $(x,y)$, she can either move to point $(x+1,y+1)$ or point $(x-1,y)$. YunQian initially stands at point $(a,b)$ and wants to move to point $(c,d)$. Find the minimum number of moves she needs to make or declare that it is impossible. The main function of the solution is defined as: ```python class Solution: def solve(self, a, b, c, d): pass # write your code here``` Where: - `a, b, c, d`: integers representing the coordinates of Yunqian's initial position and target position. - return value: the minimum number of moves Yunqian needs to make to reach the target position. If it is impossible to reach the target position, return -1. # Example 1: - Input: a = -1, b = 0, c = -1, d = 2 - Output: 4 # Constraints: - $-@data \leq a, b, c, d \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, a, b, c, d): a -= b c -= d if a < c or b > d: return -1 return (a - c) + (d - b) def solve2(self, a, b, c, d): p = d - b if p < 0: return -1 q = a + p - c if q < 0: return -1 return p + q ","import sys data = sys.stdin.read().split() a = int(data[0]) b = int(data[1]) c = int(data[2]) d = int(data[3]) solution = Solution() result = solution.solve(a, b, c, d) sys.stdout.write(str(result) + ""\n"")","graph,greedy,math",hard 55,"# Problem Statement You have $5$ different types of coins, each with a value equal to one of the first $5$ triangular numbers: $1$, $3$, $6$, $10$, and $15$. These coin types are available in abundance. Your goal is to find the minimum number of these coins required such that their total value sums up to exactly $n$. We can show that the answer always exists. The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - return: the minimum number of coins required. # Example 1: - Input: n = 2 - Output: 2 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 1000000, 100000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): a = (1, 3, 6, 10, 15) cnt = 0 if n >= 30: num = n // 15 cnt = num - 2 n = n % 15 + 30 dp = [math.inf] * (n + 1) dp[0] = 0 for j in range(1, n + 1): for i in range(5): if j - a[i] >= 0: if dp[j - a[i]] != math.inf: dp[j] = min(dp[j], dp[j - a[i]] + 1) return int(dp[n] + cnt) def solve2(self, n): def f(x): best = None for c15 in range(x // 15 + 1): rem15 = x - 15 * c15 for c10 in range(rem15 // 10 + 1): rem10 = rem15 - 10 * c10 for c6 in range(rem10 // 6 + 1): r = rem10 - 6 * c6 total = c15 + c10 + c6 + (r // 3) + (r % 3) if best is None or total < best: best = total return best if n >= 30: num = n // 15 cnt = num - 2 m = (n % 15) + 30 return f(m) + cnt else: return f(n) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")","dp,math",hard 56,"# Problem Statement You are given an undirected unweighted tree $T$ with $n$ vertices. Define a complete undirected weighted graph $G$ with the same vertex set, where the weight between $u$ and $v$ in $G$ equals the distance between them in the tree $T$. For every subset $S$ of vertices, consider the minimum spanning tree (MST) of the subgraph of $G$ induced by $S$. Compute the sum of MST weights over all subsets $S$, modulo $10^9+7$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, edges): pass # write your code here``` where: - `n`: the number of vertices in the tree - `edges`: `n-1` edges `(u, v)` (1-based), forming a tree - return: the sum of MST weights over all subsets, modulo $10^9+7$ # Example 1: - Input: ``` n = 3 edges = [(1,2),(2,3)] ``` - Output: ``` 6 ``` # Constraints: - $1 \le n \le @data$ - Tree input: exactly $n-1$ edges, $1 \le u,v \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 1000, 5000]",8000,"[[500, 250, 100], [4000, 2000, 800], [32000, 16000, 6400]]","import sys from collections import deque class Solution: def solve(self, n, edges): if n > 1000: sys.setrecursionlimit(n + 50) MOD = 1000000007 g = [[] for _ in range(n + 1)] for u, v in edges: g[u].append(v) g[v].append(u) order = [] order.reverse() pos = [0] * (n + 1) q = deque() vis = [False] * (n + 1) vis[1] = True q.append(1) while q: u = q.popleft() order.append(u) pos[u] = len(order) for v in g[u]: if not vis[v]: vis[v] = True q.append(v) pw2 = [0] * (n + 1) pw2[0] = 1 for i in range(1, n + 1): pw2[i] = (pw2[i - 1] * 2) if pw2[i] >= MOD: pw2[i] -= MOD ans = 0 cnt = [0] * (n + 1) def dfs(u, fa, lim, depth): if depth > 0: cnt[depth] += 1 for v in g[u]: if v == fa: continue if pos[v] > lim: continue dfs(v, u, lim, depth + 1) for lim in range(1, n + 1): for i in range(len(cnt)): cnt[i] = 0 root = order[lim - 1] dfs(root, 0, lim, 0) cur = 0 for j in range(1, n + 1): cnt[j] += cnt[j - 1] for j in range(1, n + 1): exp = lim - cnt[j - 1] - 1 add = pw2[exp] add -= 1 if add < 0: add += MOD cur += add if cur >= MOD: cur -= MOD ans = (ans + cur * pw2[n - lim]) % MOD if ans < 0: ans += MOD return int(ans) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) edges = [] capacity = max(0, n - 1) for i in range(n - 1): u = int(next(it)) v = int(next(it)) edges.append((u, v)) solution = Solution() result = solution.solve(n, edges) sys.stdout.write(str(result) + ""\n"")","graph,tree,combinatorics",hard 57,"You are given two strings s1 and s2 of equal length consisting of letters ""x"" and ""y"" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: s1 = ""xx"", s2 = ""yy"" Output: 1 Example 2: Input: s1 = ""xy"", s2 = ""yx"" Output: 2 Constraints: 1 <= s1.length, s2.length <= @data s1.length == s2.length s1, s2 only contain 'x' or 'y' Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, s1, s2): xy = 0 yx = 0 for i in range(len(s1)): if s1[i] == 'x' and s2[i] == 'y': xy += 1 if s1[i] == 'y' and s2[i] == 'x': yx += 1 if (xy + yx) % 2 != 0: return -1 return xy // 2 + yx // 2 + (xy % 2) * 2 def solve2(self, s1, s2): if len(s1) != len(s2): return -1 xy = 0 yx = 0 for i in range(len(s1)): a = s1[i] b = s2[i] if a != b: if a == 'x': xy += 1 else: yx += 1 if (xy + yx) % 2 != 0: return -1 return xy // 2 + yx // 2 + (xy % 2) * 2 ","import sys def main(): data = sys.stdin.read().split() if len(data) < 2: a = """" b = """" else: a = data[0] b = data[1] solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,medium 58,"You are given a string s consisting of lowercase English letters, and an integer k. Your task is to convert the string into an integer by a special process, and then transform it by summing its digits repeatedly k times. More specifically, perform the following steps: Convert s into an integer by replacing each letter with its position in the alphabet (i.e. replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Transform the integer by replacing it with the sum of its digits. Repeat the transform operation (step 2) k times in total. For example, if s = ""zbax"" and k = 2, then the resulting integer would be 8 by the following operations: Convert: ""zbax"" ➝ ""(26)(2)(1)(24)"" ➝ ""262124"" ➝ 262124 Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 Transform #2: 17 ➝ 1 + 7 ➝ 8 Return the resulting integer after performing the operations described above. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: s = ""iiii"", k = 1 Output: 36 Example 2: Input: s = ""leetcode"", k = 2 Output: 6 Constraints: 1 <= s.length <= @data 1 <= k <= 10 s consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s, k): currentNumber = 0 for ch in s: position = ord(ch) - ord('a') + 1 while position > 0: currentNumber += position % 10 position //= 10 for i in range(1, k): digitSum = 0 temp_num = currentNumber while temp_num > 0: digitSum += temp_num % 10 temp_num //= 10 currentNumber = digitSum if currentNumber < 10: break return currentNumber def solve2(self, s, k): total = 0 for ch in s: val = ord(ch) - 96 while val > 0: total += val % 10 val //= 10 for _ in range(k - 1): if total < 10: break dsum = 0 while total > 0: dsum += total % 10 total //= 10 total = dsum return total ","import sys data = sys.stdin.read().split() k = int(data[0]) s = data[1] solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result))",string,easy 59,"You are given two integer arrays nums1 and nums2 with the same length. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: nums1[i] == nums2[j], and the line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here ``` Example 1: Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5] Output: 3 Example 2: Input: nums1 = [1,3,7,1,7], nums2 = [1,9,2,5,1] Output: 2 Constraints: 1 <= nums1.length == nums2.length <= @data 1 <= nums1[i], nums2[i] <= 2000 Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, nums1, nums2): n1 = len(nums1) n2 = len(nums2) dp = [0] * (n2 + 1) dpPrev = [0] * (n2 + 1) for i in range(1, n1 + 1): for j in range(1, n2 + 1): if nums1[i - 1] == nums2[j - 1]: dp[j] = 1 + dpPrev[j - 1] else: dp[j] = max(dp[j - 1], dpPrev[j]) dpPrev = list(dp) return dp[n2] def solve2(self, nums1, nums2): n1 = len(nums1) n2 = len(nums2) if n1 == 0 or n2 == 0: return 0 B = 4096 for i in range(n1): prev = 0 a = nums1[i] for j in range(n2): v = nums2[j] dpj_prev = v // B b = v % B temp = dpj_prev if a == b: dp_new = prev + 1 else: if j > 0: left = nums2[j - 1] // B if left > dpj_prev: dp_new = left else: dp_new = dpj_prev else: dp_new = dpj_prev nums2[j] = dp_new * B + b prev = temp return nums2[n2 - 1] // B ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] b = [] i = 1 while i <= n: x = int(next(it)) a.append(x) i += 1 i = 1 while i <= n: x = int(next(it)) b.append(x) i += 1 solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result) + ""\n"")",dp,medium 60,"# Problem Statement You are given an array $a$ of size $n$. You will do the following process to calculate your penalty: 1. Split array $a$ into two (possibly empty) subsequences$^\dagger$ $s$ and $t$ such that every element of $a$ is either in $s$ or $t^\ddagger$. 2. For an array $b$ of size $m$, define the penalty $p(b)$ of an array $b$ as the number of indices $i$ between $1$ and $m - 1$ where $b_i < b_{i + 1}$. 3. The total penalty you will receive is $p(s) + p(t)$. If you perform the above process optimally, find the minimum possible penalty you will receive. $^\dagger$ A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements. $^\ddagger$ Some valid ways to split array $a=[3,1,4,1,5]$ into $(s,t)$ are $([3,4,1,5],[1])$, $([1,1],[3,4,5])$ and $([\,],[3,1,4,1,5])$ while some invalid ways to split $a$ are $([3,4,5],[1])$, $([3,1,4,1],[1,5])$ and $([1,3,4],[5,1])$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return a single integer representing the minimum possible penalty you will receive. # Example 1: - Input: n = 5 a = [1, 2, 3, 4, 5] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = 0 x = n y = n for ai in a: if ai > x and ai > y: ans += 1 if x < y: x = ai else: y = ai elif ai <= x and ai <= y: if x < y: x = ai else: y = ai elif ai <= x: x = ai else: y = ai return ans def solve2(self, n, a): best = n limit = 1 << n mask = 0 while mask < limit: count = 0 hasS = False hasT = False lastS = 0 lastT = 0 m = mask j = 0 while j < n: ai = a[j] if (m & 1) != 0: if hasS: if lastS < ai: count += 1 else: hasS = True lastS = ai else: if hasT: if lastT < ai: count += 1 else: hasT = True lastT = ai m >>= 1 j += 1 if count < best: best = count mask += 1 return best ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",dp,hard 61,"You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. There is at least one element to the right of i. That is, 0 <= i < n - 1. Return the number of valid splits in nums. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [10,4,-8,7] Output: 2 Example 2: Input: nums = [2,3,1,0] Output: 2 Constraints: 2 <= nums.length <= @data -10^5 <= nums[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, nums: List[int]) -> int: leftSum = 0 rightSum = 0 for num in nums: rightSum += num count = 0 for i in range(len(nums) - 1): leftSum += nums[i] rightSum -= nums[i] if leftSum >= rightSum: count += 1 return count def solve2(self, nums: List[int]) -> int: n = len(nums) count = 0 for i in range(n - 1): left = 0 for k in range(i + 1): left += nums[k] right = 0 for k in range(i + 1, n): right += nums[k] if left >= right: count += 1 return count","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")",math,easy 62,"# Problem Statement Monocarp is playing a computer game on a grid with $2$ rows and $n$ columns. The strings $s1$ and $s2$ describe the two rows of the grid. A character `0` means the cell is safe, and a character `1` means the cell contains a trap. Determine whether the level is passable. For this task, the level is passable if every column has at least one safe cell. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s1, s2): pass # write your code here``` where: - `n` is the number of columns. - `s1` is the first row of the grid. - `s2` is the second row of the grid. - return: `""YES""` if the level is passable, and `""NO""` otherwise. # Example 1 - Input: n = 6 s1 = ""010101"" s2 = ""101010"" - Output: YES # Constraints - $3 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve(self, n, s1, s2): for i in range(n): if s1[i] == '1' and s2[i] == '1': return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s1 = next(it) s2 = next(it) solution = Solution() result = solution.solve(n, s1, s2) sys.stdout.write(str(result) + ""\n"")","search,dp,greedy",medium 63,"# Problem Statement We call a polynomial $f(x) = a_0 + a_1 x + a_2 x^2 + \dots + a_n x^n$ valid of degree $n$ if and only if each $a_i$ is a non-negative integer for $0 \le i \le n$, and $a_n \ne 0$. For a valid polynomial $f(x)$, define its twin polynomial $g(x) = \sum_{i=0}^{n} i \cdot x^{a_i}$. For example, if $f(x)=1+2x+2x^3$, then $g(x)=0\cdot x^{1} + 1\cdot x^{2} + 2\cdot x^{0} + 3\cdot x^{2} = 2 + 4x^2$. We call $f(x)$ cool if and only if $f(x) = g(x)$. You are given an incomplete valid polynomial of degree $n$: the array $(a_0,\dots,a_n)$, where some positions are determined and others are $-1$. It is guaranteed that $a_0$ and $a_n$ are $-1$ in the input. Count the number of cool valid polynomials consistent with the given information. Return the answer modulo $10^9+7$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: degree of the polynomial. - `a`: an array of length `n+1`, where `a[i] = -1` means unknown, otherwise `0 <= a[i] <= n`. - return: the number of cool valid polynomials modulo $10^9+7$. # Example: - Input: - n = 2 - a = [-1, -1, -1] - Output: - 3 # Constraints: - $1 \le n \le @data$ - $a_i \in \{-1\} \cup [0, n]$ - $a_0 = a_n = -1$ in the input - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve(self, n, a): MOD = 1000000007 if len(a) != n + 1: return 0 for i in range(n + 1): if a[i] != -1 and not (0 <= a[i] <= n): return 0 for i in range(1, n + 1): if a[i] == -1: continue if a[i] == 0 or a[i] == i: continue j = a[i] if j < 0 or j > n: return 0 if a[j] == -1: a[j] = i elif a[j] != i: return 0 if a[n] == 0: return 0 m = 0 for i in range(1, n + 1): if a[i] == -1: m += 1 def computeF(t): if t < 0: return 0, 0 if t == 0: return 1, 0 f0 = 1 f1 = 2 if t == 1: return f1, f0 prev2 = f0 prev1 = f1 cur = 0 for i in range(2, t + 1): cur = (2 * prev1 + (i - 1) * prev2) % MOD prev2 = prev1 prev1 = cur return cur, prev2 Fm, Fm_1 = computeF(m) ans = 0 if a[n] == -1: ans = Fm - Fm_1 if ans < 0: ans += MOD else: ans = Fm return ans % MOD ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * (n + 1) for i in range(n + 1): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,math",hard 64,"# Problem Statement There are two screens which can display sequences of uppercase Latin letters. Initially, both screens display nothing. In one second, you can do one of the following two actions: - choose a screen and an uppercase Latin letter, and append that letter to **the end** of the sequence displayed on that screen; - choose a screen and copy the sequence from it to the other screen, **overwriting the sequence that was displayed on the other screen**. You have to calculate the minimum number of seconds you have to spend so that the first screen displays the sequence $s$, and the second screen displays the sequence $t$. The main function of the solution is defined as: ```python class Solution: def solve(self, s, t): pass # write your code here``` where: - return: the minimum possible number of seconds you have to spend so that the first screen displays the sequence s, and the second screen displays the sequence t. # Example 1: - Input: s = ""GARAGE"" t = ""GARAGEFORSALE"" - Output: 14 # Constraints: - $1 \leq s.length, t.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s, t): i = 0 while i < len(s) and i < len(t) and s[i] == t[i]: i += 1 ans = len(s) + len(t) - max(0, i - 1) return ans def solve2(self, s, t): i = 0 ls, lt = len(s), len(t) while i < ls and i < lt and s[i] == t[i]: i += 1 return ls + lt - (i - 1 if i > 0 else 0) ","import sys data = sys.stdin.read().split() it = iter(data) s = next(it) t = next(it) solution = Solution() result = solution.solve(s, t) sys.stdout.write(str(result) + ""\n"")","string,greedy,two_pointers",hard 65,"Xiao Ming's flower shop has just opened. In order to attract customers, he wants to put a row of flowers in front of the shop, with a total of $m$ pots. By investigating customers' preferences, Xiao Ming made a list of customers' favorite $n$ flowers. In order to display more flowers at the door, it is stipulated that the $i$-th type of flower cannot exceed $a_i$ pots, and the same type of flowers must be placed together, and the different types must be arranged in increasing order of their labels. Try programming to figure out how many different flower arrangements there are. Since the answer can be very large, return it modulo 1000007. Function Signature ```python class Solution: def solve(self, n, m, a): pass # write your code here``` Example 1: Input: n=2, m=4, a=[3, 2] Output: 2 Constraints: 0 < n, m <= @data 0 <= a[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 50, 100]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys import math class Solution: def solve1(self, n, m, a): mod = 1000007 a.insert(0, 0) f = [0] * (m + 1) sum_arr = [0] * (m + 1) f[0] = 1 for i in range(m + 1): sum_arr[i] = 1 for i in range(1, n + 1): for j in range(m, 0, -1): t = j - min(a[i], j) - 1 if t < 0: f[j] = (f[j] + sum_arr[j - 1]) % mod else: f[j] = (f[j] + sum_arr[j - 1] - sum_arr[t] + mod) % mod for j in range(1, m + 1): sum_arr[j] = (sum_arr[j - 1] + f[j]) % mod return f[m] def solve2(self, n, m, a): mod = 1000007 k = n - 1 def comb_fixed_k(N): if N < 0: return 0 K = k if K < 0: return 0 if K == 0: return 1 if K > N: return 0 if K > N - K: K = N - K res = 1 for i in range(1, K + 1): num = N - K + i den = i g = math.gcd(num, den) if g > 1: num //= g den //= g g = math.gcd(res, den) if g > 1: res //= g den //= g res *= num return res total = 0 size = 1 << n prev_g = 0 sumB = 0 parity = 0 for i in range(size): g = i ^ (i >> 1) if i == 0: sumB = 0 parity = 0 else: diff = g ^ prev_g idx = diff.bit_length() - 1 bi = a[idx] + 1 if (g >> idx) & 1: sumB += bi parity ^= 1 else: sumB -= bi parity ^= 1 N = m - sumB + n - 1 t = comb_fixed_k(N) if parity == 0: total += t else: total -= t if total >= (1 << 63) or total <= -(1 << 63): total %= mod prev_g = g return total % mod","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(n, m, a) sys.stdout.write(str(result) + ""\n"")",dp,hard 66,"# Problem Statement This is a counting problem on binary strings. For a binary string r, define f(r) as the result of repeatedly and simultaneously deleting all substrings ""10"" from r, until no ""10"" remains. For example, f(100110001) = 001 since: 10_0110_001 → 010_01 → 001. A binary string s is called almost-palindrome if and only if f(s) = f(rev(s)), where rev(s) is the reverse of s. Given an integer n, compute the number of distinct almost-palindrome binary strings of length n, modulo 998244353. The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - `n`: the length of the binary string - return: the number of almost-palindrome binary strings of length `n` modulo 998244353 # Example 1: - Input: n = 3 - Output: 4 # Constraints: - $1 \leq n \leq @data$ - Modulo: 998244353 - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 250, 125], [4000, 2000, 1000], [32000, 16000, 8000]]","class Solution: def solve1(self, n): mod = 998244353 def add(x, y): res = x + y return res if res < mod else res - mod def sub(x, y): res = x - y return res if res >= 0 else res + mod if n == 0: return 1 inv = [0] * (n + 1) a = [0] * (n + 1) s = [0] * (n + 1) if n > 0: inv[1] = 1 for i in range(2, n + 1): inv[i] = (mod - mod // i) * inv[mod % i] % mod a[0] = 1 s[0] = 1 for i in range(1, n + 1): a[i] = a[i - 1] * (n - i + 1) % mod * inv[i] % mod s[i] = add(s[i - 1], a[i]) def ask(l, r): l = max(l, 0) r = min(r, n) if l > r: return 0 if l == 0: return s[r] return sub(s[r], s[l - 1]) def calc(k, t): sum_val = 0 p = 0 while ((n + k) // 2) - p * (k + 2 - t) >= 0: sum_val = add(sum_val, ask(((n - k) // 2) - p * (k + 2 - t), ((n + k) // 2) - t - p * (k + 2 - t))) p += 1 p = 0 while ((n - k) // 2) - 1 - p * (k + 2 - t) >= 0: term = (k + 1 - t) * a[((n - k) // 2) - 1 - p * (k + 2 - t)] % mod sum_val = sub(sum_val, term) p += 1 p = 1 while ((n - k) // 2) + p * (k + 2 - t) <= n: sum_val = add(sum_val, ask(((n - k) // 2) + p * (k + 2 - t), ((n + k) // 2) - t + p * (k + 2 - t))) p += 1 p = 0 while ((n + k) // 2) + 1 - t + p * (k + 2 - t) <= n: term = (k + 1 - t) * a[((n + k) // 2) + 1 - t + p * (k + 2 - t)] % mod sum_val = sub(sum_val, term) p += 1 return sum_val ans = 0 x = 0 for i in range(1, n + 1): if (n + i) & 1: continue ans = add(ans, x) x = calc(i, 0) ans = add(ans, x) y = calc(i, 1) ans = sub(ans, add(y, y)) return ans def solve2(self, n): mod = 998244353 if n == 0: return 1 total = 0 limit = 1 << n for x in range(limit): depth = 0 u0f = 0 i = n - 1 while i >= 0: if (x >> i) & 1: depth += 1 else: if depth: depth -= 1 else: u0f += 1 i -= 1 u1f = depth depth = 0 u0r = 0 i = 0 while i < n: if (x >> i) & 1: depth += 1 else: if depth: depth -= 1 else: u0r += 1 i += 1 u1r = depth if u0f == u0r and u1f == u1r: total += 1 if total >= mod: total -= mod return total % mod ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")",math,hard 67,"# Problem Statement You are given a row of $n$ towers with heights $a_1, a_2, \dots, a_n$. When looking from the left, you see all towers that are strictly higher than all previous ones. When looking from the right, you see all towers that are strictly higher than all following ones. For a height sequence $h$, let $L(h)$ be the set of heights visible from the left, and $R(h)$ the set of heights visible from the right. Count the number of subsequences $a'$ of $a$ such that: - $L(a') = L(a)$, and - $R(a') = R(a)$. Return the answer modulo $998244353$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: length of the sequence, - `a`: the array of heights, - return: the number of valid subsequences modulo $998244353$. ## Example - Input: ``` n = 9 a = [3, 5, 5, 7, 4, 6, 7, 2, 4] ``` - Output: ``` 51 ``` ## Constraints - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[100, 1000, 5000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): MOD = 998244353 if n == 0: return 0 m = max(a) L = [] cur = -sys.maxsize - 1 for i in range(n): if a[i] > cur: L.append(a[i]) cur = a[i] K = len(L) dpL = [0] * n c = [0] * (K + 1) c[0] = 1 for i in range(n): inc = [0] * (K + 1) for j in range(K, 0, -1): if a[i] == L[j - 1]: inc[j] = (inc[j] + c[j - 1]) % MOD for j in range(1, K + 1): if a[i] <= L[j - 1]: c[j] = (2 * c[j]) % MOD for j in range(1, K + 1): c[j] = (c[j] + inc[j]) if c[j] >= MOD: c[j] -= MOD if a[i] == m: if K > 0: dpL[i] = c[K - 1] R = [] cur = -sys.maxsize - 1 for i in range(n - 1, -1, -1): if a[i] > cur: R.append(a[i]) cur = a[i] KR = len(R) dpR = [0] * n cR = [0] * (KR + 1) cR[0] = 1 for i in range(n - 1, -1, -1): incR = [0] * (KR + 1) for j in range(KR, 0, -1): if a[i] == R[j - 1]: incR[j] = (incR[j] + cR[j - 1]) % MOD for j in range(1, KR + 1): if a[i] <= R[j - 1]: cR[j] = (2 * cR[j]) % MOD for j in range(1, KR + 1): cR[j] = (cR[j] + incR[j]) if cR[j] >= MOD: cR[j] -= MOD if a[i] == m: if KR > 0: dpR[i] = cR[KR - 1] p2 = [1] * (n + 1) for i in range(1, n + 1): p2[i] = (2 * p2[i - 1]) % MOD pos = [] for i in range(n): if a[i] == m: pos.append(i) ans = 0 s = len(pos) for u in range(s): i = pos[u] for v in range(u, s): j = pos[v] between = j - i - 1 if j > i else 0 ways = (dpL[i] * dpR[j]) % MOD ans = (ans + ways * p2[between]) % MOD return ans def solve2(self, n, a): MOD = 998244353 if n == 0: return 0 m = 0 for i in range(n): if a[i] > m: m = a[i] B = m + 1 cur = -1 codeL_orig = 0 for i in range(n): v = a[i] if v > cur: cur = v codeL_orig = codeL_orig * B + v cur = -1 codeR_orig = 0 for i in range(n - 1, -1, -1): v = a[i] if v > cur: cur = v codeR_orig = codeR_orig * B + v total = 0 limit = 1 << n for mask in range(limit): cur = -1 codeL = 0 for i in range(n): if (mask >> i) & 1: v = a[i] if v > cur: cur = v codeL = codeL * B + v if codeL != codeL_orig: continue cur = -1 codeR = 0 for i in range(n - 1, -1, -1): if (mask >> i) & 1: v = a[i] if v > cur: cur = v codeR = codeR * B + v if codeR != codeR_orig: continue total += 1 if total >= MOD: total -= MOD return total","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,data_structures",hard 68,"# Problem Statement The next lecture in a high school requires two topics to be discussed. The $i$-th topic is interesting by $a_i$ units for the teacher and by $b_i$ units for the students. The pair of topics $i$ and $j$ ($i < j$) is called **good** if $a_i + a_j > b_i + b_j$ (i.e. it is more interesting for the teacher). Your task is to find the number of **good** pairs of topics. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, b): pass # write your code here``` where: - return: the number of **good** pairs of topics. # Example 1: - Input: n = 5 a = [4, 8, 2, 6, 2] b = [4, 5, 4, 1, 3] - Output: 7 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i], b[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a, b): diff = [] for i in range(n): diff.append(a[i] - b[i]) diff.sort() ans = 0 j = n for i in range(n): while j > 0 and diff[i] + diff[j - 1] > 0: j -= 1 ans += n - max(i + 1, j) return ans def solve2(self, n, a, b): ans = 0 for i in range(n): di = a[i] - b[i] for j in range(i + 1, n): if di + (a[j] - b[j]) > 0: ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n b = [0] * n for i in range(n): a[i] = int(next(it)) for i in range(n): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, a, b) sys.stdout.write(str(result) + ""\n"")","two_pointers,sort",easy 69,"# Problem Statement Initially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\dagger}$ of $a$ and add into $a$ an element equal to the sum of all elements of the subsequence. You are given a final array $c$. Check if $c$ can be obtained from the initial array $a$ by performing some number (possibly 0) of operations on the initial array. $^{\dagger}$ A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly zero, but not all) elements. In other words, select $k$ ($1 \leq k \leq |a|$) distinct indices $i_1, i_2, \dots, i_k$ and insert anywhere into $a$ a new element with the value equal to $a_{i_1} + a_{i_2} + \dots + a_{i_k}$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: ""YES"" if such a sequence of operations exists, and ""NO"" otherwise. # Example 1: - Input: n = 1 c = [1] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq c[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, c): c.sort() s = 0 for i in range(n): if s + (i == 0) < c[i]: return ""NO"" s += c[i] return ""YES"" def solve2(self, n, c): s = 0 used = 0 while used < n: idx = -1 for i in range(n): if c[i] > 0: idx = i min_val = c[i] break if idx == -1: return ""NO"" for i in range(idx + 1, n): v = c[i] if v > 0 and v < min_val: min_val = v idx = i if used == 0: if min_val != 1: return ""NO"" else: if min_val > s: return ""NO"" s += min_val c[idx] = 0 used += 1 return ""YES"" ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","sort,two_pointers",medium 70,"Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] Output: [15] Example 2: Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] Output: [12] Constraints: m == matrix.length n == matrix[i].length 1 <= n, m <= @data 1 <= matrix[i][j] <= 10^5. All elements in the matrix are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 500]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, matrix): N = len(matrix) M = len(matrix[0]) rMinMax = -math.inf for i in range(N): rMin = math.inf for j in range(M): rMin = min(rMin, matrix[i][j]) rMinMax = max(rMinMax, rMin) cMaxMin = math.inf for i in range(M): cMax = -math.inf for j in range(N): cMax = max(cMax, matrix[j][i]) cMaxMin = min(cMaxMin, cMax) if rMinMax == cMaxMin: return [int(rMinMax)] return [] def solve2(self, matrix): n = len(matrix) if n == 0: return [] m = len(matrix[0]) if n > 0 else 0 if m == 0: return [] res = [] for i in range(n): jmin = 0 v = matrix[i][0] j = 1 while j < m: x = matrix[i][j] if x < v: v = x jmin = j j += 1 ok = True r = 0 while r < n: if matrix[r][jmin] > v: ok = False break r += 1 if ok: res.append(int(v)) return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) s = [] try: n = int(next(it)) m = int(next(it)) except StopIteration: n = 0 m = 0 for i in range(1, n + 1): temp = [] j = 1 while j <= m: try: x = int(next(it)) except StopIteration: x = 0 temp.append(x) j += 1 s.append(temp) solution = Solution() result = solution.solve(s) result.sort() out = [] for it_val in result: out.append(str(it_val)) if out: sys.stdout.write("" "".join(out) + "" "") else: sys.stdout.write("""")",math,easy 71,"# Problem Statement In his dream, Cocoly would go on a long holiday with no worries around him. So he would try out for many new things, such as... being a carpenter. To learn it well, Cocoly decides to become an apprentice of Master, but in front of him lies a hard task waiting for him to solve. Cocoly is given an array $a_1, a_2,\ldots, a_n$. Master calls a set of integers $S$ stable if and only if, for any possible $u$, $v$, and $w$ from the set $S$ (note that $u$, $v$, and $w$ do not necessarily have to be pairwise distinct), sticks of length $u$, $v$, and $w$ can form a non-degenerate triangle$^{\text{∗}}$. Cocoly is asked to partition the array $a$ into several (possibly, $1$ or $n$) **non-empty** continuous subsegments$^{\text{†}}$, such that: for each of the subsegments, the set containing all the elements in it is stable. Master wants Cocoly to partition $a$ in **at least two** different$^{\text{‡}}$ ways. You have to help him determine whether it is possible. $^{\text{∗}}$A triangle with side lengths $x$, $y$, and $z$ is called non-degenerate if and only if: - $x + y > z$, - $y + z > x$, and - $z + x > y$. $^{\text{†}}$A sequence $b$ is a subsegment of a sequence $c$ if $b$ can be obtained from $c$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. $^{\text{‡}}$Two partitions are considered different if and only if at least one of the following holds: - the numbers of continuous subsegments split in two partitions are different; - there is an integer $k$ such that the lengths of the $k$-th subsegment in two partitions are different. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return YES if there are at least two ways to partition a, and NO otherwise. # Example 1: - Input: n = 4 a = [2, 3, 5, 7] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import math import sys class Solution: def solve1(self, n, a): for i in range(1, n): x = a[i - 1] y = a[i] if x > y: x, y = y, x if 2 * x > y: return ""YES"" return ""NO"" def solve2(self, n, a): m = n - 1 limit = 1 << m count = 0 mask = 0 while mask < limit: ok = True i = 0 while i < n: seg_min = a[i] seg_max = a[i] j = i while j + 1 < n and ((mask >> j) & 1) == 0: j += 1 v = a[j] if v < seg_min: seg_min = v if v > seg_max: seg_max = v if seg_min + seg_min <= seg_max: ok = False break i = j + 1 if ok: count += 1 if count >= 2: return ""YES"" mask += 1 return ""NO"" ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy,math",hard 72,"Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19] Example 2: Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44] Constraints: 1 <= arr1.length, arr2.length <= @data 0 <= arr1[i], arr2[i] <= @data All the elements of arr2 are distinct. Each arr2[i] is in arr1. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections class Solution: def solve1(self, arr1: list[int], arr2: list[int]) -> list[int]: if not arr1: return [] freq = collections.Counter(arr1) result: list[int] = [] for element in arr2: if element in freq: count = freq.pop(element) if count > 0: result.extend([element] * count) if freq: for num in sorted(freq.keys()): count = freq[num] if count > 0: result.extend([num] * count) return result def solve2(self, arr1: list[int], arr2: list[int]) -> list[int]: n = len(arr1) if n == 0: return arr1 w = 0 for v in arr2: i = w while i < n: if arr1[i] == v: arr1[w], arr1[i] = arr1[i], arr1[w] w += 1 i += 1 for pos in range(w, n): min_idx = pos j = pos + 1 while j < n: if arr1[j] < arr1[min_idx]: min_idx = j j += 1 if min_idx != pos: arr1[pos], arr1[min_idx] = arr1[min_idx], arr1[pos] return arr1 ","import sys def main(): data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, m + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) out = [] for it_item in result: out.append(str(it_item)) out.append(' ') sys.stdout.write(''.join(out)) if __name__ == ""__main__"": main()",sort,easy 73,"You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j]. Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j]. solution main function ```python class Solution: def solve(self, num, k): pass # write your code here``` Example 1: Input: arr = [1,2,3,5], k = 3 Output: [2,5] Example 2: Input: arr = [1,7], k = 1 Output: [1,7] Constraints: 2 <= arr.length <= @data 1 <= arr[i] <= 2*10^6 arr[0] == 1 arr[i] is a prime number for i > 0. All the numbers of arr are unique and sorted in strictly increasing order. 1 <= k <= arr.length * (arr.length - 1) / 2 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 1000, 50000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: def solve(self, arr, k): n = len(arr) left = 0.0 right = 1.0 while True: mid = (left + right) / 2 i = -1 count = 0 x = 0 y = 1 for j in range(1, n): while i + 1 < j and arr[i + 1] / arr[j] < mid: i += 1 if arr[i] * y > arr[j] * x: x = arr[i] y = arr[j] count += i + 1 if count == k: return [x, y] if count < k: left = mid else: right = mid if right - left < 1e-12: return [x, y] ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num, k) out = [] for v in result: out.append(str(v)) sys.stdout.write("" "".join(out))",two_pointers,hard 74,"# Problem Statement The girl named Masha was walking in the forest and found a complete binary tree of height $n$ and a permutation $p$ of length $m=2^n$. A complete binary tree of height $n$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $n$. The picture below shows the complete binary tree for $n=2$. A permutation is an array consisting of $n$ different integers from $1$ to $n$. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not ($2$ occurs twice), and $[1,3,4]$ is also not a permutation ($n=3$, but there is $4$ in the array). Let's enumerate $m$ leaves of this tree from left to right. The leaf with the number $i$ contains the value $p_i$ ($1 \le i \le m$). Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order. In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees). Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful. The main function of the solution is defined as: ```python class Solution: def solve(self, m, p): pass # write your code here``` where: - return the minimum possible number of operations for which Masha will be able to make the tree beautiful, or -1 if this is not possible. # Example 1: - Input: m = 8 p = [6, 5, 7, 8, 4, 3, 1, 2] - Output: 4 # Constraints: - $1 \leq m \leq @data$ - $m$ is a power of $2$ - $1 \leq p[i] \leq m$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 131072]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, a): ans = 0 len_val = 2 while len_val <= n: for i in range(0, n, len_val): mid = len_val // 2 if a[i] > a[i + mid]: ans += 1 for j in range(mid): a[i + j], a[i + mid + j] = a[i + mid + j], a[i + j] len_val *= 2 for i in range(n): if a[i] != i + 1: return -1 return ans def solve2(self, n, a): ans = 0 len_val = 2 while len_val <= n: mid = len_val // 2 i = 0 while i < n: if a[i] > a[i + mid]: ans += 1 j = 0 while j < mid: tmp = a[i + j] a[i + j] = a[i + mid + j] a[i + mid + j] = tmp j += 1 i += len_val len_val <<= 1 i = 0 while i < n: if a[i] != i + 1: return -1 i += 1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) m = int(next(it)) p = [0] * m for i in range(m): p[i] = int(next(it)) solution = Solution() result = solution.solve(m, p) sys.stdout.write(str(result) + ""\n"")","search,graph,tree,sort",hard 75,"You are given an integer array nums of size n where n is a multiple of 3 and a positive integer k. In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. Rick stated that magnetic force between two different balls at positions x and y is |x - y|. Given the integer array position and the integer m. Return the required force. solution main function ```python class Solution: def solve(self, num, m): pass # write your code here``` Example 1: Input: position = [1,2,3,4,7], m = 3 Output: 3 Example 2: Input: position = [5,4,3,2,1,1000000000], m = 2 Output: 999999999 Constraints: n == position.length 2 <= n <= @data 1 <= position[i] <= 10^9 All integers in position are distinct. 2 <= m <= position.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[10000, 5000, 500], [80000, 40000, 4000], [640000, 320000, 32000]]","import math class Solution: def canPlaceBalls(self, x, position, m): prevBallPos = position[0] ballsPlaced = 1 for i in range(1, len(position)): if ballsPlaced == m: break currPos = position[i] if currPos - prevBallPos >= x: ballsPlaced += 1 prevBallPos = currPos return ballsPlaced == m def solve1(self, position, m): if m <= 1: return 0 answer = 0 n = len(position) position.sort() low = 1 high = position[n - 1] - position[0] if n > 0 else 0 while low <= high: mid = low + (high - low) // 2 if self.canPlaceBalls(mid, position, m): answer = mid low = mid + 1 else: high = mid - 1 return answer def solve2(self, position, m): if m <= 1: return 0 n = len(position) position.sort() low = 1 high = position[n - 1] - position[0] if n > 0 else 0 answer = 0 while low <= high: mid = (low + high) // 2 prev = position[0] count = 1 i = 1 while i < n and count < m: if position[i] - prev >= mid: count += 1 prev = position[i] i += 1 if count == m: answer = mid low = mid + 1 else: high = mid - 1 return answer ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num, m) sys.stdout.write(str(result) + ""\n"") return 0 if __name__ == ""__main__"": main()","sort,binary",medium 76,"# Problem Statement You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root is vertex $1$. There is also a string $s$ denoting the color of each vertex: if $s_i = \texttt{B}$, then vertex $i$ is black, and if $s_i = \texttt{W}$, then vertex $i$ is white. A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees. A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $1$. The tree is specified by an array of parents $a_2, \dots, a_n$ containing $n-1$ numbers: $a_i$ is the parent of the vertex with the number $i$ for all $i = 2, \dots, n$. The parent of a vertex $u$ is a vertex that is the next vertex on a simple path from $u$ to the root. The subtree of a vertex $u$ is the set of all vertices that pass through $u$ on a simple path to the root. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, s): pass # write your code here``` where: - `a`: contains $n-1$ integers, $a_i$ is the parent of the vertex with the number $i$ for all $i = 2, \dots, n$. - `s`: 'B' or 'W' denoting the color of each vertex. - return: the number of balanced subtrees. # Example 1: - Input: n = 7 a = [1, 1, 2, 3, 3, 5] s = ""WBBWWBW"" - Output: 2 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] < i$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 100, 64], [4000, 800, 400], [32000, 6400, 3200]]","import collections class Solution: def solve1(self, n: int, a: list[int], s: str) -> int: b = [0] * n for i in range(n): if s[i] == 'W': b[i] = 1 else: b[i] = -1 for i in range(n - 2, -1, -1): b[a[i] - 1] += b[i + 1] return b.count(0) def solve2(self, n, a, s): count = 0 for u in range(1, n + 1): total = 0 for v in range(1, n + 1): t = v while t != 0 and t != u: t = a[t - 2] if t > 1 else 0 if t == u: total += 1 if s[v - 1] == 'W' else -1 if total == 0: count += 1 return count ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(n - 1): a.append(int(next(it))) s = next(it) solution = Solution() result = solution.solve(n, a, s) sys.stdout.write(str(result) + ""\n"")","search,dp,graph,tree",hard 77,"You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [3,2,4,6] Output: 7 Example 2: Input: nums = [1,2,3,9,2] Output: 11 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 10^8 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math from typing import List class Solution: def solve(self, nums: List[int]) -> int: res = 0 n = len(nums) for i in range(n): res |= nums[i] return res","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return s = [] i = 1 while i <= n: try: x = int(next(it)) except StopIteration: x = 0 s.append(x) i += 1 solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","math,other",medium 78,"# Problem Statement You are given an array of $n$ non-negative integers. You want to answer $q$ independent scenarios. In the $i$-th scenario, you are allowed to perform the following operation at most $b_i$ times: - Choose an element of the array and increase it by $1$. Your goal is to maximize the number of bits that are equal to $1$ in the bitwise OR of all numbers in the array. For each scenario, output that maximum number. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, q, b): pass # write your code here``` where: - `n`: the size of the array - `a`: the array of non-negative integers - `q`: number of scenarios - `b`: for each scenario, the max number of allowed operations - return: an array of size `q`, the answer for each scenario # Example 1: - Input: ``` n = 2, q = 2 a = [1, 3] b = [0, 3] ``` - Output: ``` 2 3 ``` # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - $1 \leq q \leq @data$ - $0 \leq b_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 250, 125], [4000, 2000, 1000], [32000, 16000, 8000]]","import bisect class Solution: def solve1(self, n, a, q, b): ora = 0 for i in range(n): ora |= a[i] base = bin(ora).count('1') costs = [] costs.append(0) ta = list(a) cost = 0 x = ora for i in range(31): if not ((x >> i) & 1): x |= (1 << i) for j in range(i, -1, -1): nv = 0 for k in range(n): nv |= ta[k] if (nv >> j) & 1: continue mask = (1 << j) - 1 t = -1 for k in range(n): if t == -1 or (ta[k] & mask) > (ta[t] & mask): t = k delta = (1 << j) - (ta[t] & mask) cost += delta ta[t] += delta costs.append(cost) ans = [0] * q for i in range(q): bi = b[i] t = bisect.bisect_right(costs, bi) - 1 if t < 0: t = 0 ans[i] = base + t return ans def solve2(self, n, a, q, b): ora = 0 for i in range(n): ora |= a[i] base = 0 x = ora while x: base += x & 1 x >>= 1 costs = [0] cost = 0 x = ora OR_current = ora for i in range(31): if ((x >> i) & 1) == 0: x |= 1 << i j = i while j >= 0: if ((OR_current >> j) & 1) != 0: j -= 1 continue mask = (1 << j) - 1 if mask != 0: t = 0 best = a[0] & mask k = 1 while k < n: val = a[k] & mask if val > best: best = val t = k k += 1 delta = (1 << j) - best else: t = 0 delta = 1 cost += delta a[t] += delta OR_current |= a[t] j -= 1 costs.append(cost) m = len(costs) ans = [0] * q for i in range(q): bi = b[i] t = 0 idx = 0 while idx < m and costs[idx] <= bi: t = idx idx += 1 ans[i] = base + t return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) q = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) b = [0] * q for i in range(q): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, a, q, b) out_lines = [] for i in range(len(result)): out_lines.append(str(result[i])) sys.stdout.write(""\n"".join(out_lines))","greedy,math",hard 79,"# Problem Statement There is an initially empty sheet with `n` rows and `m` columns. You perform painting operations, each time choosing either any row or any column and painting all its cells in a color. In the first operation, cells are painted with color `1`. For operation `i > 1`, you may choose color `c_{i-1}` or `c_{i-1} + 1`, where `c_{i-1}` is the color chosen at operation `i-1`. We call the final coloring beautiful if: - every cell is colored; - for each color from `1` to `k`, there is at least one cell of that color, and no other colors are used. For a beautiful coloring, define its value as the minimum number of operations to obtain it. For each `i` from `min(n, m)` to `n + m - 1`, compute the number of beautiful colorings with value `i`, modulo `998244353`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k): pass # write your code here``` where: - `n`: number of rows - `m`: number of columns - `k`: number of colors used (exactly colors `1..k`) - return: an array `ans` of length `n + m`, where for each `i` in `[min(n,m), n+m-1]`, `ans[i]` equals the number of beautiful colorings with value `i` modulo `998244353` (positions outside the range may be `0`). Example: Input: n = 2, m = 2, k = 2 Output: 4 4 Explanation: The answers for values 2 and 3 are both 4. # Constraints: - $2 \le n, m \le @data$ - $1 \le k \le n + m - 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 1000, 2000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: MOD = 998244353 @staticmethod def add_mod(a, b): s = a + b if s >= Solution.MOD: s -= Solution.MOD if s < 0: s += Solution.MOD return s @staticmethod def mul_mod(a, b): return (a * b) % Solution.MOD @staticmethod def pow_mod(a, e): return pow(a, e, Solution.MOD) def solve1(self, n, m, k): NM = n + m fact = [1] * (NM + 1) ifact = [1] * (NM + 1) for i in range(1, NM + 1): fact[i] = self.mul_mod(fact[i - 1], i) ifact[NM] = self.pow_mod(fact[NM], self.MOD - 2) for i in range(NM, 0, -1): ifact[i - 1] = self.mul_mod(ifact[i], i) def C(nn, rr): if rr < 0 or rr > nn: return 0 return self.mul_mod(fact[nn], self.mul_mod(ifact[rr], ifact[nn - rr])) f = [0] * NM colors = k - 1 if colors >= 0: for j in range(colors + 1): base = colors - j coeff = C(colors, j) if j & 1: coeff = (self.MOD - coeff) % self.MOD p = 1 for t in range(NM): if t >= colors: f[t] = self.add_mod(f[t], self.mul_mod(coeff, p)) p = self.mul_mod(p, base) ans = [0] * NM for a in range(n): cn = C(n, a) for b in range(m): cm = C(m, b) t = a + b idx = t + min(n - a, m - b) if t < len(f): waysAssign = f[t] if waysAssign != 0: ans[idx] = self.add_mod(ans[idx], self.mul_mod(waysAssign, self.mul_mod(cn, cm))) return ans def solve2(self, n, m, k): MOD = self.MOD NM = n + m ans = [0] * NM colors = k - 1 def f_of_t(t): if t < colors: return 0 if colors == 0: return 1 if t == 0 else 0 s = 0 comb = 1 j = 0 while j <= colors: base = colors - j term = self.pow_mod(base, t) if j & 1: term = (MOD - term) % MOD term = (term * comb) % MOD s += term if s >= MOD: s -= MOD j += 1 if j <= colors: comb = comb * (colors - (j - 1)) % MOD comb = comb * self.pow_mod(j, MOD - 2) % MOD return s a = 0 cn = 1 while a < n: b = 0 cm = 1 while b < m: t = a + b idx = t + (n - a if n - a < m - b else m - b) waysAssign = f_of_t(t) if waysAssign != 0: v = waysAssign v = (v * cn) % MOD v = (v * cm) % MOD ans[idx] += v if ans[idx] >= MOD: ans[idx] -= MOD b1 = b + 1 if b1 < m: cm = cm * (m - b) % MOD cm = cm * self.pow_mod(b1, MOD - 2) % MOD b = b1 a1 = a + 1 if a1 < n: cn = cn * (n - a) % MOD cn = cn * self.pow_mod(a1, MOD - 2) % MOD a = a1 return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, m, k) L = n if n < m else m out = [] end_index = n + m - 1 for i in range(L, n + m): if i == end_index: out.append(str(result[i]) + ""\n"") else: out.append(str(result[i]) + "" "") sys.stdout.write("""".join(out))","math,dp",hard 80,"Given a list of 24-hour clock points in the format ""HH:MM"", return the minimum minute difference between any two points in the list. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: timePoints = [""23:59"",""00:00""] Output: 1 Example 2: Input: timePoints = [""00:00"",""23:59"",""00:00""] Output: 0 Constraints: 2 <= timePoints.length <= @data timePoints[i] is in the format ""HH:MM"" Time limit: @time_limit ms Memory limit: @memory_limit KB ","[20, 100, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, timePoints): minutes = [False] * (24 * 60) for time in timePoints: h = int(time[0:2]) m = int(time[3:]) total_min = h * 60 + m if minutes[total_min]: return 0 minutes[total_min] = True prev_index = float('inf') first_index = float('inf') last_index = float('inf') ans = float('inf') for i in range(24 * 60): if minutes[i]: if prev_index != float('inf'): ans = min(ans, i - prev_index) prev_index = i if first_index == float('inf'): first_index = i last_index = i return min(ans, 24 * 60 - last_index + first_index) def solve2(self, timePoints): n = len(timePoints) ans = 1440 for i in range(n): s1 = timePoints[i] h1 = int(s1[0:2]) m1 = int(s1[3:]) t1 = h1 * 60 + m1 for j in range(i + 1, n): s2 = timePoints[j] h2 = int(s2[0:2]) m2 = int(s2[3:]) t2 = h2 * 60 + m2 d = t1 - t2 if d < 0: d = -d if d == 0: return 0 if 1440 - d < d: d = 1440 - d if d < ans: ans = d return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = next(it) a.append(x) solution = Solution() result = solution.solve(a) sys.stdout.write(str(result) + ""\n"")","math,sort,string",easy 81,"# Problem Statement You are at a marketplace with two traders, each represented by a permutation over the same set of $n$ items. Let those permutations be $p$ and $s$. If you hold item $i$, you may trade it for item $j$ if either $p_i > p_j$ (using the first trader) or $s_i > s_j$ (using the second trader). We say item $i$ is at least as valuable as item $j$ if starting with item $i$ you can perform some (possibly zero) trades and obtain item $j$. At any time, you have exactly one item. Assume traders have infinite supply of each item. There will be $q$ updates; each update swaps two positions in one of the permutations. After every update, output the number of ordered pairs $(i,j)$ ($1 \le i,j \le n$) such that item $i$ is at least as valuable as item $j$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, q, p, s, ops): pass # write your code here``` where: - `n`: number of items - `q`: number of updates - `p`, `s`: permutations of `[1..n]` - `ops`: `q` updates `(tp, i, j)` where `tp=1` swaps `p[i], p[j]` and `tp=2` swaps `s[i], s[j]` - return: an array of length `q`, the k-th value is the answer after the first k updates # Example - Input: - n = 3, q = 3 - p = [1, 2, 3] - s = [3, 2, 1] - ops = [(2, 1, 3), (2, 1, 3), (1, 1, 2)] - Output: - [6, 9, 9] # Constraints: - $2 \le n \le @data$ - $1 \le q \le @data$ - `p`, `s` are permutations of `[1..n]` - each update has `i \ne j` - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",8000,"[[5000, 2500, 1250], [40000, 20000, 10000], [320000, 160000, 80000]]","import sys class Solution: class Tag: def __init__(self, add=0): self.add = add def apply(self, other_tag): self.add += other_tag.add class Info: def __init__(self, min_val=sys.maxsize, l=-1, r=-1, ans=0): self.min = min_val self.l = l self.r = r self.ans = ans def apply(self, tag): self.min += tag.add @staticmethod def __add__(L, R): x = Solution.Info() if L.min < R.min: x.min = L.min x.l = L.l x.r = L.r x.ans = L.ans return x if L.min > R.min: x.min = R.min x.l = R.l x.r = R.r x.ans = R.ans return x x.min = L.min x.l = L.l x.r = R.r d = R.l - L.r x.ans = L.ans + R.ans + d * (d - 1) // 2 return x class LazySegmentTree: def __init__(self, init_data): self.n = len(init_data) if self.n == 0: self.info = [] self.tag = [] return log_n = max(1, self.n).bit_length() - 1 size = 4 << log_n self.info = [Solution.Info() for _ in range(size)] self.tag = [Solution.Tag() for _ in range(size)] if self.n > 0: self._build(1, 0, self.n, init_data) def _build(self, p, l, r, init_data): if r - l == 1: self.info[p] = init_data[l] return m = (l + r) // 2 self._build(2 * p, l, m, init_data) self._build(2 * p + 1, m, r, init_data) self._pull(p) def _pull(self, p): self.info[p] = Solution.Info.__add__(self.info[2 * p], self.info[2 * p + 1]) def _apply(self, p, v_tag): self.info[p].apply(v_tag) self.tag[p].apply(v_tag) def _push(self, p): self._apply(2 * p, self.tag[p]) self._apply(2 * p + 1, self.tag[p]) self.tag[p] = Solution.Tag() def _modify(self, p, l, r, x, v_info): if r - l == 1: self.info[p] = v_info return m = (l + r) // 2 self._push(p) if x < m: self._modify(2 * p, l, m, x, v_info) else: self._modify(2 * p + 1, m, r, x, v_info) self._pull(p) def modify(self, p_idx, v_info): self._modify(1, 0, self.n, p_idx, v_info) def _rangeQuery(self, p, l, r, x, y): if l >= y or r <= x: return Solution.Info() if l >= x and r <= y: return self.info[p] m = (l + r) // 2 self._push(p) res_l = self._rangeQuery(2 * p, l, m, x, y) res_r = self._rangeQuery(2 * p + 1, m, r, x, y) return Solution.Info.__add__(res_l, res_r) def rangeQuery(self, l, r): return self._rangeQuery(1, 0, self.n, l, r) def _rangeApply(self, p, l, r, x, y, v_tag): if l >= y or r <= x: return if l >= x and r <= y: self._apply(p, v_tag) return m = (l + r) // 2 self._push(p) self._rangeApply(2 * p, l, m, x, y, v_tag) self._rangeApply(2 * p + 1, m, r, x, y, v_tag) self._pull(p) def rangeApply(self, l, r, v_tag): if l < r: self._rangeApply(1, 0, self.n, l, r, v_tag) def solve1(self, n, q, p, s, ops): p = [x - 1 for x in p] s = [x - 1 for x in s] ip = [0] * n is_ = [0] * n for i in range(n): ip[p[i]] = i is_[s[i]] = i init_data = [self.Info(0, i, i, 0) for i in range(n + 1)] seg = self.LazySegmentTree(init_data) vis = [False] * n def add(x, t=1): vis[x] = (t == 1) if s[x] > 0: y = is_[s[x] - 1] if vis[y] and p[x] < p[y]: seg.rangeApply(p[x] + 1, p[y] + 1, self.Tag(t)) if s[x] + 1 < n: y = is_[s[x] + 1] if vis[y] and p[y] < p[x]: seg.rangeApply(p[y] + 1, p[x] + 1, self.Tag(t)) for i in range(n): add(i) out = [] for t, x, y in ops: x -= 1 y -= 1 add(x, -1) add(y, -1) if t == 1: p[x], p[y] = p[y], p[x] ip[p[x]], ip[p[y]] = ip[p[y]], ip[p[x]] else: s[x], s[y] = s[y], s[x] is_[s[x]], is_[s[y]] = is_[s[y]], is_[s[x]] add(x, 1) add(y, 1) out.append(n * (n + 1) // 2 + seg.rangeQuery(0, n + 1).ans) return out def solve2(self, n, q, p, s, ops): def count_total(): total = 0 for i in range(n): if p[i] > 0: p[i] = -p[i] count = 1 curMaxP = -p[i] curMaxS = s[i] while True: updated = False for y in range(n): py = p[y] if py > 0: if py < curMaxP or s[y] < curMaxS: p[y] = -py count += 1 updated = True if updated: mp = 0 ms = 0 for k in range(n): if p[k] < 0: pk = -p[k] if pk > mp: mp = pk sk = s[k] if sk > ms: ms = sk curMaxP = mp curMaxS = ms else: break for k in range(n): if p[k] < 0: p[k] = -p[k] total += count return total res = [] for tp, i, j in ops: i -= 1 j -= 1 if tp == 1: p[i], p[j] = p[j], p[i] else: s[i], s[j] = s[j], s[i] res.append(count_total()) return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) q = int(next(it)) p = [0] * n s = [0] * n for i in range(n): p[i] = int(next(it)) for i in range(n): s[i] = int(next(it)) ops = [[0, 0, 0] for _ in range(q)] for i in range(q): tp = int(next(it)) x = int(next(it)) y = int(next(it)) ops[i] = [tp, x, y] solution = Solution() result = solution.solve(n, q, p, s, ops) out_lines = [] for i in range(len(result)): out_lines.append(str(result[i])) sys.stdout.write(""\n"".join(out_lines))","data_structures,graph",hard 82,"You are given an integer array nums and an integer k. Select exactly k elements from nums such that their sum is as large as possible. Return the selected values as an integer array of length k. The returned order does not matter; the runner compares the selected values after sorting them. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: nums = [2,1,3,3], k = 2 Output: [3,3] Example 2: Input: nums = [-1,-2,3,4], k = 3 Output: [-1,3,4] Constraints: 1 <= nums.length <= @data -10^5 <= nums[i] <= 10^5 1 <= k <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, nums, k): n = len(nums) i = 0 t = k ans = [] while t > 0: ans.append(nums[i]) i += 1 t -= 1 for j in range(i, n): mini = ans.index(min(ans)) if ans[mini] < nums[j]: ans.pop(mini) ans.append(nums[j]) return ans def solve2(self, nums, k): ans = [] chosen = 0 prev = None while chosen < k: cur_max = None if prev is None: for x in nums: if cur_max is None or x > cur_max: cur_max = x else: for x in nums: if x < prev: if cur_max is None or x > cur_max: cur_max = x cnt = 0 for x in nums: if x == cur_max: cnt += 1 take = cnt if cnt < (k - chosen) else (k - chosen) i = 0 while i < take: ans.append(cur_max) i += 1 chosen += take prev = cur_max return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, k) result = sorted(result) out = [] for v in result: out.append(str(v)) if out: sys.stdout.write("" "".join(out))","sort,data_structures,other",easy 83,"You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, n, m): pass # write your code here``` Example 1: Input: steps = 3, arrLen = 2 Output: 4 Example 2: Input: steps = 3, arrLen = 2 Output: 4 Constraints: 1 <= steps <= @data 1 <= arrLen <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, steps, arrLen): MOD = 10**9 + 7 arrLen = min(arrLen, steps) dp = [0] * arrLen prevDp = [0] * arrLen prevDp[0] = 1 for remain in range(1, steps + 1): dp = [0] * arrLen for curr in range(arrLen - 1, -1, -1): ans = prevDp[curr] if curr > 0: ans = (ans + prevDp[curr - 1]) % MOD if curr < arrLen - 1: ans = (ans + prevDp[curr + 1]) % MOD dp[curr] = ans prevDp = dp return dp[0] def solve2(self, steps, arrLen): MOD = 10**9 + 7 if steps == 0: return 1 if arrLen == 1: return 1 limit = 3 ** steps count = 0 for code in range(limit): temp = code pos = 0 s = steps valid = True while s: d = temp % 3 temp //= 3 if d == 1: pos -= 1 elif d == 2: pos += 1 if pos < 0 or pos >= arrLen: valid = False break s -= 1 if valid and pos == 0: count += 1 if count >= MOD: count -= MOD return count % MOD ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result) + ""\n"")",dp,medium 84,"Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique. Return the result in ascending order. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Constraints: 1 <= nums1.length, nums2.length <= @data 0 <= nums1[i], nums2[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections class Solution: def solve(self, nums1, nums2): result = [] n = len(nums1) m = len(nums2) nums1.sort() nums2.sort() for i in range(n): for j in range(m): if nums1[i] == nums2[j]: if nums1[i] not in result: result.append(nums1[i]) break return result ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, m + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) out = [] for it_val in result: out.append(str(it_val)) sys.stdout.write("" "".join(out))","binary,sort,two_pointers",medium 85,"You are given a 0-indexed string array words. Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2: isPrefixAndSuffix(str1, str2) returns true if str1 is both a prefix and a suffix of str2, and false otherwise. For example, isPrefixAndSuffix(""aba"", ""ababa"") is true because ""aba"" is a prefix of ""ababa"" and also a suffix, but isPrefixAndSuffix(""abc"", ""abcd"") is false. Return an integer denoting the number of index pairs (i, j) such that i < j, and isPrefixAndSuffix(words[i], words[j]) is true. solution main function ```python class Solution: def solve(self, str_list): pass # write your code here``` Example 1: Input: words = [""a"",""aba"",""ababa"",""aa""] Output: 4 Example 2: Input: words = [""pa"",""papa"",""ma"",""mama""] Output: 2 Constraints: 1 <= words.length <= @data 1 <= words[i].length <= @data words[i] consists only of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 50, 100]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, words): n = len(words) count = 0 for i in range(n): for j in range(i + 1, n): str1 = words[i] str2 = words[j] if len(str1) > len(str2): continue if str2.startswith(str1) and str2.endswith(str1): count += 1 return count def solve2(self, words): n = len(words) count = 0 for i in range(n): s1 = words[i] m = len(s1) for j in range(i + 1, n): s2 = words[j] n2 = len(s2) if m > n2: continue k = 0 while k < m: if s1[k] != s2[k]: break k += 1 if k != m: continue k = 1 while k <= m: if s1[m - k] != s2[n2 - k]: break k += 1 if k == m + 1: count += 1 return count ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) str_list = [] for i in range(1, n + 1): s = next(it) str_list.append(s) solution = Solution() result = solution.solve(str_list) sys.stdout.write(str(result))",string,easy 86,"Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Example 2: Input: arr = [1,1] Output: 1 Constraints: 1 <= arr.length <= @data 0 <= arr[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import bisect class Solution: def solve1(self, arr): n = len(arr) if n == 0: return -1 candidates = [arr[n // 4], arr[n // 2], arr[3 * n // 4]] target = n // 4 for candidate in candidates: left = bisect.bisect_left(arr, candidate) right = bisect.bisect_right(arr, candidate) - 1 if right - left + 1 > target: return candidate return -1 def solve2(self, arr): n = len(arr) if n == 0: return -1 threshold = n // 4 curr = arr[0] count = 1 for i in range(1, n): if arr[i] == curr: count += 1 else: if count > threshold: return curr curr = arr[i] count = 1 if count > threshold: return curr return -1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(a) sys.stdout.write(str(result) + ""\n"")",math,easy 87,"# Problem Statement: Given an array $a$ of $n$ elements, return the minimum value that appears at least three times, or return -1 if there is no such value. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` Where: - return the minimum value that appears at least three times, or -1 if there is no such value. # Example 1: - Input: n = 5 a = [1, 2, 3, 2, 2] - Output: 2 # Constraints: - $0 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): a.sort() cnt = 1 for i in range(1, n): if a[i] == a[i - 1]: cnt += 1 else: cnt = 1 if cnt == 3: return a[i] return -1 def solve2(self, n, a): if n < 3: return -1 best_found = False best_val = 0 for i in range(n): v = a[i] is_first = True for k in range(i): if a[k] == v: is_first = False break if not is_first: continue if best_found and v >= best_val: continue cnt = 1 for j in range(i + 1, n): if a[j] == v: cnt += 1 if cnt == 3: best_val = v best_found = True break if best_found: return best_val return -1","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","sort,greedy",easy 88,"Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Example 2: Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Constraints: 1 <= arr1.length, arr2.length <= @data 0 <= arr1[i], arr2[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 600]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import bisect class Solution: def solve1(self, arr1, arr2): arr1.insert(0, -1) arr1.append(int(2e9)) arr2 = sorted(list(set(arr2))) n = len(arr1) dp = [int(1e9)] * n dp[0] = 0 m = len(arr2) for i in range(1, n): if arr1[i] > arr1[i - 1]: dp[i] = dp[i - 1] for j in range(i): idx = bisect.bisect_left(arr2, arr1[j] + 1) cnt = i - j - 1 if (idx + cnt <= m and idx + cnt > 0 and arr2[idx + cnt - 1] < arr1[i] and arr1[i] > arr1[j]): dp[i] = min(dp[j] + cnt, dp[i]) if dp[n - 1] == int(1e9): return -1 else: return dp[n - 1] def solve2(self, arr1, arr2): n = len(arr1) m = len(arr2) arr2.sort() if m == 0: prev = -1 for v in arr1: if v <= prev: return -1 prev = v return 0 w = 1 for r in range(1, m): if arr2[r] != arr2[w - 1]: arr2[w] = arr2[r] w += 1 if w < m: del arr2[w:] m = w def feasible(mask): prev = -1 for i in range(n): if (mask >> i) & 1: idx = bisect.bisect_right(arr2, prev) if idx >= m: return False prev = arr2[idx] else: v = arr1[i] if v <= prev: return False prev = v return True if feasible(0): return 0 limit = 1 << n for k in range(1, n + 1): mask = (1 << k) - 1 while mask < limit: if feasible(mask): return k c = mask & -mask r = mask + c mask = (((r ^ mask) >> 2) // c) | r return -1","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] b = [] i = 1 while i <= n: x = int(next(it)) a.append(x) i += 1 i = 1 while i <= m: x = int(next(it)) b.append(x) i += 1 solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result))","sort,binary",hard 89,"You are given an integer array nums. The adjacent integers in nums will perform the float division. For example, for nums = [2,3,4], we will evaluate the expression ""2/3/4"". However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return the corresponding expression that has the maximum value in string format. Note: your expression should not contain redundant parenthesis. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: nums = [1000,100,10,2] Output: ""1000/(100/10/2)"" Example 2: Input: nums = [2,3,4] Output: ""2/(3/4)"" Constraints: 1 <= nums.length <= @data 2 <= nums[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[20, 100, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 500], [320000, 32000, 4000]]","class Solution: def solve1(self, nums): s = str(nums[0]) if len(nums) == 1: return s if len(nums) == 2: s += ""/"" + str(nums[1]) return s s += ""/("" + str(nums[1]) for i in range(2, len(nums)): s += ""/"" + str(nums[i]) s += "")"" return s def solve2(self, nums): n = len(nums) s = str(nums[0]) if n == 1: return s if n == 2: return s + ""/"" + str(nums[1]) s += ""/("" + str(nums[1]) for i in range(2, n): s += ""/"" + str(nums[i]) s += "")"" return s ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(a) sys.stdout.write(str(result) + ""\n"")","math,sort,string",medium 90,"# Problem Statement Matryoshka is a wooden toy in the form of a painted doll, inside which you can put a similar doll of a smaller size. A set of nesting dolls contains one or more nesting dolls, their sizes are consecutive positive integers. Thus, a set of nesting dolls is described by two numbers: $s$ — the size of a smallest nesting doll in a set and $m$ — the number of dolls in a set. In other words, the set contains sizes of $s, s + 1, \dots, s + m - 1$ for some integer $s$ and $m$ ($s,m > 0$). You had one or more sets of nesting dolls. Recently, you found that someone mixed all your sets in one and recorded a sequence of doll sizes — integers $a_1, a_2, \dots, a_n$. You do not remember how many sets you had, so you want to find the **minimum** number of sets that you could initially have. For example, if a given sequence is $a=[2, 2, 3, 4, 3, 1]$. Initially, there could be $2$ sets: - the first set consisting of $4$ nesting dolls with sizes $[1, 2, 3, 4]$; - a second set consisting of $2$ nesting dolls with sizes $[2, 3]$. According to a given sequence of sizes of nesting dolls $a_1, a_2, \dots, a_n$, determine the minimum number of nesting dolls that can make this sequence. Each set is completely used, so all its nesting dolls are used. Each element of a given sequence must correspond to exactly one doll from some set. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the minimum possible number of matryoshkas sets. # Example 1: - Input: n = 6 a = [2, 2, 3, 4, 3, 1] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, a): a.sort() ans = 0 L = 0 R = 0 last = 0 last_count = 0 while L < n: while R < n and a[L] == a[R]: R += 1 if a[L] != last + 1: ans += R - L else: ans += R - L - min(last_count, R - L) last = a[L] last_count = R - L L = R return ans def solve2(self, n, a): for i in range(n - 1): swapped = False for j in range(n - 1 - i): if a[j] > a[j + 1]: t = a[j] a[j] = a[j + 1] a[j + 1] = t swapped = True if not swapped: break ans = 0 L = 0 last = 0 last_count = 0 while L < n: R = L + 1 v = a[L] while R < n and a[R] == v: R += 1 count = R - L if v != last + 1: ans += count else: if last_count < count: ans += count - last_count last = v last_count = count L = R return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","sort,two_pointers",hard 91,"# Problem Statement Sasha found an array $a$ consisting of $n$ integers and asked you to paint elements. You have to paint each element of the array. You can use as many colors as you want, but each element should be painted into exactly one color, and for each color, there should be at least one element of that color. The cost of one color is the value of $\max(S) - \min(S)$, where $S$ is the sequence of elements of that color. The cost of the whole coloring is the **sum** of costs over all colors. For example, suppose you have an array $a = [\color{red}{1}, \color{red}{5}, \color{blue}{6}, \color{blue}{3}, \color{red}{4}]$, and you painted its elements into two colors as follows: elements on positions $1$, $2$ and $5$ have color $1$; elements on positions $3$ and $4$ have color $2$. Then: - the cost of the color $1$ is $\max([1, 5, 4]) - \min([1, 5, 4]) = 5 - 1 = 4$; - the cost of the color $2$ is $\max([6, 3]) - \min([6, 3]) = 6 - 3 = 3$; - the total cost of the coloring is $7$. For the given array $a$, you have to calculate the **maximum** possible cost of the coloring. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: return the maximum possible cost of the coloring # Example 1: - Input: n = 5 a = [1, 5, 6, 3, 4] - Output: 7 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): a.sort() ans = 0 for i in range(n // 2): ans += a[n - 1 - i] - a[i] return ans def solve2(self, n, a): k = n // 2 ans = 0 left = 0 right = n - 1 for _ in range(k): min_idx = left max_idx = left i = left + 1 while i <= right: if a[i] < a[min_idx]: min_idx = i if a[i] > a[max_idx]: max_idx = i i += 1 ans += a[max_idx] - a[min_idx] if min_idx != left: a[min_idx], a[left] = a[left], a[min_idx] if max_idx == left: max_idx = min_idx if max_idx != right: a[max_idx], a[right] = a[right], a[max_idx] left += 1 right -= 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,greedy,sort",medium 92,"Given a positive integer n, return the punishment number of n. The punishment number of n is defined as the sum of the squares of all integers i such that: 1 <= i <= n The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 10 Output: 182 Example 2: Input: n = 37 Output: 1478 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import bisect class Solution: def solve1(self, n): arr = [1, 9, 10, 36, 45, 55, 82, 91, 99, 100, 235, 297, 369, 370, 379, 414, 657, 675, 703, 756, 792, 909, 918, 945, 964, 990, 991, 999, 1000] prefix = [0] for i in arr: prefix.append(prefix[-1] + i * i) i = bisect.bisect_right(arr, n) return prefix[i] def solve2(self, n): total = 0 for i in range(1, n + 1): m = i * i s = str(m) L = len(s) target = i found = False for mask in range(1 << (L - 1)): sumv = 0 cur = ord(s[0]) - 48 ok = True for j in range(L - 1): d = ord(s[j + 1]) - 48 if (mask >> j) & 1: sumv += cur if sumv > target: ok = False break cur = d else: cur = cur * 10 + d if ok and sumv + cur == target: found = True break if found: total += m return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))","math,other",medium 93,"# Problem Statement In Berland, a bus consists of a row of $n$ seats numbered from $1$ to $n$. Passengers are advised to always board the bus following these rules: - If there are no occupied seats in the bus, a passenger can sit in any free seat; - Otherwise, a passenger should sit in any free seat that has at least one occupied neighboring seat. In other words, a passenger can sit in a seat with index $i$ ($1 \le i \le n$) only if at least one of the seats with indices $i-1$ or $i+1$ is occupied. Today, $n$ passengers boarded the bus. The array $a$ chronologically records the seat numbers they occupied. That is, $a_1$ contains the seat number where the first passenger sat, $a_2$ — the seat number where the second passenger sat, and so on. You know the contents of the array $a$. Determine whether all passengers followed the recommendations. For example, if $n = 5$, and $a$ = $[5, 4, 2, 1, 3]$, then the recommendations were not followed, as the $3$-rd passenger sat in seat number $2$, while the neighboring seats with numbers $1$ and $3$ were free. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - If all passengers followed the recommendations, return ""YES"", otherwise return ""NO"" # Example 1: - Input: n = 5 a = [5, 4, 2, 1, 3] - Output: NO # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - All seat numbers are unique - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): if n <= 1: return ""YES"" l = a[0] r = a[0] ok = True for i in range(1, n): if a[i] == l - 1: l -= 1 elif a[i] == r + 1: r += 1 else: ok = False break return ""YES"" if ok else ""NO"" def solve2(self, n, a): if n <= 1: return ""YES"" l = a[0] r = a[0] for i in range(1, n): x = a[i] if x == l - 1: l -= 1 elif x == r + 1: r += 1 else: return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",two_pointers,easy 94,"# Problem Statement You are given a sequence $a$ consisting of $n$ positive integers. You can perform the following operation any number of times. - Select an index $i$ ($1 \le i < n$), and subtract $\min(a_i,a_{i+1})$ from both $a_i$ and $a_{i+1}$. Determine if it is possible to make the sequence **non-decreasing** by using the operation any number of times. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - If it is possible to make the sequence non-decreasing, return ""YES"". Otherwise, return ""NO"". # Example 1: - Input: n = 5, a = [1, 2, 3, 4, 5] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys from typing import List class Solution: def solve1(self, n: int, a: List[int]) -> str: for i in range(1, n): if a[i - 1] > a[i]: return ""NO"" a[i] -= a[i - 1] return ""YES"" def solve2(self, n: int, a: List[int]) -> str: for i in range(1, n): if a[i - 1] > a[i]: return ""NO"" a[i] -= a[i - 1] return ""YES"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",greedy,medium 95,"Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [3,4,5,2] Output: 12 Example 2: Input: nums = [1,5,4,5] Output: 16 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, nums): n = len(nums) nums.sort() result = (nums[n - 1] - 1) * (nums[n - 2] - 1) return result def solve2(self, nums): n = len(nums) best = (nums[0] - 1) * (nums[1] - 1) for i in range(n): a = nums[i] - 1 for j in range(i + 1, n): val = a * (nums[j] - 1) if val > best: best = val return best ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result) + ""\n"")",math,easy 96,"# Problem Statement Sakurako really loves alternating strings. She calls a string $s$ of lowercase Latin letters an alternating string if characters in the even positions are the same, if characters in the odd positions are the same, and the length of the string is **even**. For example, the strings 'abab' and 'gg' are alternating, while the strings 'aba' and 'ggwp' are not. As a good friend, you decided to gift such a string, but you couldn't find one. Luckily, you can perform two types of operations on the string: 1. Choose an index $i$ and delete the $i$-th character from the string, which will reduce the length of the string by $1$. This type of operation can be performed **no more than $1$ time**; 2. Choose an index $i$ and replace $s_i$ with any other letter. Since you are in a hurry, you need to determine the minimum number of operations required to make the string an alternating one. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - `n`: the length of the string, `s`: a string of lowercase Latin letters - return: the minimum number of operations required to make the string an alternating one # Example 1: - Input: n = 2 s = ""ca"" - Output: 0 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): minans = 1000000000 for j in range(26): for t in range(26): cans = 0 limit = (n // 2) * 2 for i in range(limit): if i % 2 == 0: if ord(s[i]) - ord('a') != j: cans += 1 else: if ord(s[i]) - ord('a') != t: cans += 1 minans = min(minans, cans) if n % 2 == 0: continue for i in range(n - 2, -1, -1): if i % 2 == 0: if ord(s[i]) - ord('a') != j: cans -= 1 else: if ord(s[i]) - ord('a') != t: cans -= 1 if i % 2 == 0: if ord(s[i+1]) - ord('a') != j: cans += 1 else: if ord(s[i+1]) - ord('a') != t: cans += 1 minans = min(minans, cans) if n % 2 == 0: return minans else: return minans + 1 def solve2(self, n, s): minans = 10**9 base = ord('a') if n % 2 == 0: for j in range(26): for t in range(26): cans = 0 for i in range(n): c = ord(s[i]) - base if (i & 1) == 0: if c != j: cans += 1 else: if c != t: cans += 1 if cans < minans: minans = cans return minans else: limit = n - 1 for j in range(26): for t in range(26): cans = 0 for i in range(limit): c = ord(s[i]) - base if (i & 1) == 0: if c != j: cans += 1 else: if c != t: cans += 1 if cans < minans: minans = cans for i in range(n - 2, -1, -1): ci = ord(s[i]) - base ci1 = ord(s[i + 1]) - base if (i & 1) == 0: if ci != j: cans -= 1 else: if ci != t: cans -= 1 if (i & 1) == 0: if ci1 != j: cans += 1 else: if ci1 != t: cans += 1 if cans < minans: minans = cans return minans + 1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","dp,greedy,data_structures,string",hard 97,"# Problem Statement After receiving yet another integer array $a_1, a_2, \ldots, a_n$ at her birthday party, Index decides to perform some operations on it. Formally, there are $m$ operations that she is going to perform in order. Each of them belongs to one of the two types: - $\texttt{1 l r}$. Given two integers $l$ and $r$, for all $1 \leq i \leq n$ such that $l \leq a_i \leq r$, set $a_i := a_i + 1$. - $\texttt{2 l r}$. Given two integers $l$ and $r$, for all $1 \leq i \leq n$ such that $l \leq a_i \leq r$, set $a_i := a_i - 1$. For example, if the initial array $a = [7, 1, 3, 4, 3]$, after performing the operation $\texttt{+} \space 2 \space 4$, the array $a = [7, 1, 4, 5, 4]$. Then, after performing the operation $\texttt{-} \space 1 \space 10$, the array $a = [6, 0, 3, 4, 3]$. Index is curious about the maximum value in the array $a$. Please help her find it after each of the $m$ operations. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, a, ops): pass # write your code here``` where: - `ops` is the array of operations, each element is an array of length 3, representing an operation - return an array, where the elements are the maximum value after each operation # Example 1: - Input: n = 5, m = 5 a = [1, 2, 3, 2, 1] ops = [[1, 1, 3], [2, 2, 3], [1, 1, 2], [1, 2, 4], [2, 6, 8]] - Output: [4, 4, 4, 5, 5] # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq a[i] \leq 10^9$ - $1 \leq l \leq r \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 100, 64], [4000, 800, 400], [32000, 6400, 3200]]","import math class Solution: def solve1(self, n, m, a, ops): res = [] mx = max(a) for op, l, r in ops: if l <= mx <= r: mx += 1 if op == 1 else -1 res.append(mx) return res def solve2(self, n, m, a, ops): res = [] for op, l, r in ops: mx = None if op == 1: for i in range(n): ai = a[i] if l <= ai <= r: ai += 1 a[i] = ai if mx is None or ai > mx: mx = ai else: for i in range(n): ai = a[i] if l <= ai <= r: ai -= 1 a[i] = ai if mx is None or ai > mx: mx = ai res.append(mx) return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) ops = [[0, 0, 0] for _ in range(m)] for i in range(m): ops[i][0] = int(next(it)) ops[i][1] = int(next(it)) ops[i][2] = int(next(it)) solution = Solution() result = solution.solve(n, m, a, ops) out = [] for x in result: out.append(str(x)) sys.stdout.write("" "".join(out) + ""\n"")","greedy,data_structures",easy 98,"You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: It is the empty string, or It can be written as AB, where both A and B are balanced strings, or It can be written as [C], where C is a balanced string. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""][]["" Output: 1 Example 2: Input: s = ""[]"" Output: 0 Constraints: n == s.length 2 <= n <= @data n is even. s[i] is either '[' or ']'. The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, s): stackSize = 0 n = len(s) for i in range(n): ch = s[i] if ch == '[': stackSize += 1 else: if stackSize > 0: stackSize -= 1 return (stackSize + 1) // 2 def solve2(self, s): balance = 0 swaps = 0 for ch in s: if ch == '[': balance += 1 else: if balance > 0: balance -= 1 else: swaps += 1 balance = 1 return swaps ","import sys def main(): data = sys.stdin.read().split() s = """" if len(data) > 0: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","two_pointers,string,greedy",medium 99,"# Problem Statement There is a strip divided into cells, numbered from 0 to m from left to right. You control a chip initially placed at cell 0. There is a trap in each cell; they are activated according to the following rules: - At the end of turns 1, (1 + n), (1 + 2n), …, traps are activated in cells x where x mod a1 = b1. - At the end of turns 2, (2 + n), (2 + 2n), …, traps are activated in cells x where x mod a2 = b2. - … - At the end of turns n, (n + n), (n + 2n), …, traps are activated in cells x where x mod an = bn. In one turn, you can either move from the current cell to the next or stay in place. Then all the traps for this turn are activated. If the chip is in a cell with an activated trap at the beginning of the turn, the game ends. Your task is to calculate the minimum number of turns to reach cell m, or report that it is impossible. If the chip reaches cell m and at the end of the same turn a trap in cell m activates, it is not considered a valid way to reach cell m. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, a, b): pass # write your code here``` where: - `n`: number of trap patterns (turn periodicity) - `m`: target cell index to reach - `a`: array of size `n`, where `2 ≤ a[i] ≤ 10` - `b`: array of size `n`, where `0 ≤ b[i] < a[i]` - return: the minimum number of turns to reach cell `m`, or `-1` if impossible. # Example: - Input: ``` n = 2, m = 5 a = [2, 2] b = [0, 1] ``` - Output: ``` 5 ``` # Constraints: - $1 \leq n \leq 10$ - $1 \leq m \leq @data$ - $2 \leq a[i] \leq 10$ - $0 \leq b[i] < a[i]$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000000, 1000000000, 1000000000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, m, a, b): l = 1 for i in range(n): l = l * a[i] // math.gcd(l, a[i]) limit = l * n cap = min(limit, m) v = [10**9] * (int(cap) + 1) w = [-1] * n v[0] = 0 w[0] = 0 x = 0 i = 0 s, e, d = 0, 0, 0 while x < limit and x < m: if (x + 1) % a[i % n] != b[i % n]: x += 1 i += 1 v[x] = min(v[x], i) if x % l == 0: if w[i % n] != -1 and w[i % n] != x: s = w[i % n] e = x d = (i - v[s]) // n * n break w[i % n] = x if i - v[x] > n: return -1 if x == m: return v[m] else: return v[(m - s - 1) % (e - s) + s + 1] + d * ((m - s - 1) // (e - s)) def solve2(self, n, m, a, b): x = 0 t = 0 stay = 0 if m <= 0: return 0 while x < m: idx = t % n bad_next = ((x + 1) % a[idx] == b[idx]) bad_cur = (x % a[idx] == b[idx]) if bad_cur and bad_next: return -1 if bad_next: stay += 1 else: x += 1 stay = 0 t += 1 if stay >= n: return -1 return t ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [0] * n b = [0] * n for i in range(n): a[i] = int(next(it)) for i in range(n): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, a, b) sys.stdout.write(str(result) + ""\n"")",dp,hard 100,"You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge. The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i]. The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i. Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index. solution main function ```python class Solution: def solve(self, edge): pass # write your code here``` Example 1: Input: edges = [1,0,0,0,0,7,7,5] Output: 7 Example 2: Input: edges = [2,0,0,2] Output: 0 Constraints: n == edges.length 2 <= n <= @data 0 <= edges[i] < n edges[i] != i Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, edges): score = [0] * len(edges) for i in range(len(edges)): score[edges[i]] += i maxi = -1 val = -1 for i in range(len(edges)): if score[i] > maxi: val = i maxi = score[i] return val def solve2(self, edges): n = len(edges) best_node = 0 best_score = -1 for i in range(n): s = 0 for j in range(n): if edges[j] == i: s += j if s > best_score or (s == best_score and i < best_node): best_score = s best_node = i return best_node ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) edge = [] i = 1 while i <= n: x = int(next(it)) edge.append(x) i += 1 solution = Solution() result = solution.solve(edge) sys.stdout.write(str(result))",graph,medium 101,"# Problem Statement There are $n$ block towers, numbered from $1$ to $n$. The $i$-th tower consists of $a_i$ blocks. In one move, you can move one block from tower $i$ to tower $j$, but only if $a_i > a_j$. That move increases $a_j$ by $1$ and decreases $a_i$ by $1$. You can perform as many moves as you would like (possibly, zero). What's the largest amount of blocks you can have on the tower $1$ after the moves? The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): if n > 1: sub_array = sorted(a[1:]) for i in range(1, n): a[i] = sub_array[i - 1] for i in range(1, n): if a[i] > a[0]: a[0] = (a[0] + a[i] + 1) // 2 return a[0] def solve2(self, n, a): cur = a[0] while True: min_val = None min_idx = -1 for i in range(1, n): ai = a[i] if ai > cur and (min_val is None or ai < min_val): min_val = ai min_idx = i if min_idx == -1: break cur = (cur + min_val + 1) // 2 a[min_idx] = cur return cur ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,sort",hard 102,"You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. solution main function ```python class Solution: def solve(self, num, wid): pass # write your code here``` Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6 Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4 Constraints: 1 <= books.length <= @data 1 <= thicknessi <= shelfWidth <= 100 1 <= heighti <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, books, shelfWidth): n = len(books) table = [math.inf] * (n + 1) table[0] = 0 for i in range(1, n + 1): total_width = 0 mx_height = 0 for j in range(i, 0, -1): total_width += books[j - 1][0] if total_width > shelfWidth: break mx_height = max(mx_height, books[j - 1][1]) if table[j - 1] != math.inf: table[i] = min(table[i], mx_height + table[j - 1]) return table[n] def solve2(self, books, shelfWidth): INF = 10**18 W = shelfWidth best = [INF] * (W + 1) height = [0] * (W + 1) best[0] = 0 height[0] = 0 for t, h in books: new_best = [INF] * (W + 1) new_height = [0] * (W + 1) for w in range(W + 1): bw = best[w] if bw == INF: continue nw = w + t if nw <= W: if h > height[w]: nb = bw + (h - height[w]) nh = h else: nb = bw nh = height[w] if nb < new_best[nw]: new_best[nw] = nb new_height[nw] = nh elif nb == new_best[nw] and nh < new_height[nw]: new_height[nw] = nh nw = t nb = bw + h nh = h if nb < new_best[nw]: new_best[nw] = nb new_height[nw] = nh elif nb == new_best[nw] and nh < new_height[nw]: new_height[nw] = nh best = new_best height = new_height ans = INF for w in range(W + 1): if best[w] < ans: ans = best[w] return 0 if ans == INF else ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) wid = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) num.append(temp) solution = Solution() result = solution.solve(num, wid) sys.stdout.write(str(result))",dp,medium 103,"Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Example 2: Input: arr = [5,4,3,2,1] Output: 4 Constraints: 1 <= arr.length <= @data 0 <= arr[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, arr): n = len(arr) right = n - 1 while right > 0 and arr[right] >= arr[right - 1]: right -= 1 ans = right left = 0 while left < right and (left == 0 or arr[left - 1] <= arr[left]): while right < n and arr[left] > arr[right]: right += 1 ans = min(ans, right - left - 1) left += 1 return ans def solve2(self, arr): n = len(arr) if n <= 1: return 0 right = n - 1 while right > 0 and arr[right] >= arr[right - 1]: right -= 1 if right == 0: return 0 ans = right i = 1 prefix_ok = True while i <= right and prefix_ok: if i >= 2 and arr[i - 2] > arr[i - 1]: prefix_ok = False break t = right while t < n and arr[i - 1] > arr[t]: t += 1 if t - i < ans: ans = t - i i += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary",medium 104,"A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [0,1,0,1,1,0,0] Output: 1 Example 2: Input: nums = [0,1,1,1,0,0,1,1,0] Output: 2 Constraints: 1 <= nums.length <= @data nums[i] is either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums): minimumSwaps = float('inf') totalOnes = sum(nums) n = len(nums) if n == 0: return 0 if totalOnes == 0: return 0 onesCount = nums[0] end = 0 for start in range(n): if start != 0: onesCount -= nums[start - 1] while end - start + 1 < totalOnes: end += 1 onesCount += nums[end % n] minimumSwaps = min(minimumSwaps, totalOnes - onesCount) return minimumSwaps def solve2(self, nums): n = len(nums) if n == 0: return 0 total_ones = 0 for v in nums: total_ones += v if total_ones <= 1: return 0 min_swaps = n for start in range(n): ones = 0 k = 0 while k < total_ones: ones += nums[(start + k) % n] k += 1 swaps = total_ones - ones if swaps < min_swaps: min_swaps = swaps if min_swaps == 0: break return min_swaps ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))",greedy,easy 105,"You are given an m * n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid. solution main function ```python class Solution: def solve(self, g): pass # write your code here``` Example 1: Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]] Output: 2 Example 2: Input: grid = [[1,1]] Output: 2 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data grid[i][j] is either 0 or 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 30, 50]",4000,"[[2000, 200, 78], [16000, 1600, 625], [128000, 12800, 5000]]","import sys from collections import deque sys.setrecursionlimit(1_000_000) class Solution: dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] def bfs_mark(self, sx, sy, grid, n, m): queue = deque() queue.append((sx, sy)) grid[sx][sy] = 2 while queue: x, y = queue.popleft() for i in range(4): tx = x + self.dx[i] ty = y + self.dy[i] if 0 <= tx < n and 0 <= ty < m and grid[tx][ty] == 1: grid[tx][ty] = 2 queue.append((tx, ty)) def count(self, grid, n, m): cnt = 0 for i in range(n): for j in range(m): if grid[i][j] == 1: cnt += 1 self.bfs_mark(i, j, grid, n, m) for i in range(n): for j in range(m): if grid[i][j] == 2: grid[i][j] = 1 return cnt def has_articulation_point(self, grid): n = len(grid) m = len(grid[0]) index_of = {} nodes = [] for i in range(n): for j in range(m): if grid[i][j] == 1: index_of[(i, j)] = len(nodes) nodes.append((i, j)) total = len(nodes) if total <= 1: return True adj = [[] for _ in range(total)] for u_idx, (x, y) in enumerate(nodes): for k in range(4): tx = x + self.dx[k] ty = y + self.dy[k] v_idx = index_of.get((tx, ty)) if v_idx is not None: adj[u_idx].append(v_idx) disc = [-1] * total low = [0] * total parent = [-1] * total ap = [False] * total time = [0] def dfs(u: int) -> None: disc[u] = low[u] = time[0] time[0] += 1 children = 0 for v in adj[u]: if disc[v] == -1: parent[v] = u children += 1 dfs(v) low[u] = low[u] if low[u] < low[v] else low[v] if parent[u] == -1 and children > 1: ap[u] = True if parent[u] != -1 and low[v] >= disc[u]: ap[u] = True elif v != parent[u]: low[u] = low[u] if low[u] < disc[v] else disc[v] for u in range(total): if disc[u] == -1: dfs(u) return any(ap) def solve1(self, grid): n = len(grid) m = len(grid[0]) if self.count(grid, n, m) != 1: return 0 if self.has_articulation_point(grid): return 1 return 2 def solve2(self, grid): n = len(grid) m = len(grid[0]) def count_islands(): cnt = 0 for i in range(n): for j in range(m): if grid[i][j] == 1: cnt += 1 grid[i][j] = 2 changed = True while changed: changed = False for x in range(n): for y in range(m): if grid[x][y] == 1: if (x > 0 and grid[x - 1][y] == 2) or (x + 1 < n and grid[x + 1][y] == 2) or (y > 0 and grid[x][y - 1] == 2) or (y + 1 < m and grid[x][y + 1] == 2): grid[x][y] = 2 changed = True for i in range(n): for j in range(m): if grid[i][j] == 2: grid[i][j] = 1 return cnt if count_islands() != 1: return 0 for i in range(n): for j in range(m): if grid[i][j] == 1: grid[i][j] = 0 c = count_islands() if c != 1: grid[i][j] = 1 return 1 grid[i][j] = 1 return 2 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) g = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) g.append(temp) solution = Solution() result = solution.solve(g) sys.stdout.write(str(result))",graph,hard 106,"# Problem Statement One winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician, Rudolf came up with a mathematical model of a snowflake. He defined a snowflake as an undirected graph constructed according to the following rules: - Initially, the graph has only one vertex. - Then, more vertices are added to the graph. The initial vertex is connected by edges to $k$ new vertices ($k > 1$). - Each vertex that is connected to only one other vertex is connected by edges to $k$ more new vertices. This step should be done **at least once**. After some mathematical research, Rudolf realized that such snowflakes may not have any number of vertices. Help Rudolf check if a snowflake with $n$ vertices can exist. The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - return ""YES"" if a snowflake with $n$ vertices can exist, otherwise return ""NO"". # Example 1: - Input: n = 15 - Output: ""YES"" # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): ok = 0 for i in range(2, n + 1): sum_val = 1 + i + i * i p = i * i if sum_val > n: break while sum_val < n: p *= i sum_val += p if sum_val == n: ok = 1 break return ""YES"" if ok else ""NO"" def solve2(self, n): if n < 7: return ""NO"" for k in range(2, n + 1): s = 1 + k + k * k if s > n: break p = k * k while s < n: p *= k s += p if s == n: return ""YES"" return ""NO"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")",math,medium 107,"# Problem Statement Alice got a permutation $a_1, a_2, \ldots, a_n$ of $[1,2,\ldots,n]$, and Bob got another permutation $b_1, b_2, \ldots, b_n$ of $[1,2,\ldots,n]$. They are going to play a game with these arrays. In each turn, the following events happen in order: - Alice chooses either the first or the last element of her array and removes it from the array; - Bob chooses either the first or the last element of his array and removes it from the array. The game continues for $n-1$ turns, after which both arrays will have exactly one remaining element: $x$ in the array $a$ and $y$ in the array $b$. If $x=y$, Bob wins; otherwise, Alice wins. Find which player will win if both players play optimally. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, b): pass # write your code here``` where: - return Alice if Alice wins; otherwise, return Bob. # Example 1: - Input: n = 2 a = [1, 2] b = [1, 2] - Output: Bob # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], b[i] \leq n$ - a[i] is distinct. - b[i] is distinct. - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, a, b): if a == b: return ""Bob"" if a == b[::-1]: return ""Bob"" return ""Alice"" def solve2(self, n, a, b): for i in range(n - 2): u = a[i] v = a[i + 1] w = a[i + 2] j = 0 while j < n and b[j] != v: j += 1 if j == 0 or j == n - 1: return ""Alice"" if not ((b[j - 1] == u and b[j + 1] == w) or (b[j - 1] == w and b[j + 1] == u)): return ""Alice"" return ""Bob"" ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) b = [0] * n for i in range(n): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, a, b) sys.stdout.write(str(result) + ""\n"")",game,hard 108,"# Problem Statement Slavic has an array of length $n$ consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array. What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to $s$ after performing all the operations? In case the sum $s$ can't be obtained after any amount of operations, you should output \-1. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s, a): pass # write your code here``` where: - return: the minimum amount of operations required to have the total sum of the array equal to s, or -1 if obtaining an array with sum s isn't possible. # Example 1: - Input: n = 3, s = 1 a = [1, 0, 0] - Output: 0 # Constraints: - $1 \leq n, s \leq @data$ - $a[i] \in \{0, 1\}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s, a): ans = n + 1 cur = 0 j = 0 for i in range(n): while j < n and cur + a[j] <= s: cur += a[j] j += 1 if cur == s: ans = min(ans, n - (j - i)) cur -= a[i] if ans > n: ans = -1 return ans def solve2(self, n, s, a): best_len = 0 if s == 0 else -1 for i in range(n): cur = 0 for j in range(i, n): cur += a[j] if cur == s: length = j - i + 1 if length > best_len: best_len = length elif cur > s: break if best_len == -1: return -1 return n - best_len ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) s = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, s, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary",hard 109,"You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1. A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]: nums[i + k + 1] > nums[i + k] if pattern[k] == 1. nums[i + k + 1] == nums[i + k] if pattern[k] == 0. nums[i + k + 1] < nums[i + k] if pattern[k] == -1. Return the count of subarrays in nums that match the pattern. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: nums = [1,2,3,4,5,6], pattern = [1,1] Output: 4 Example 2: Input: nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] Output: 2 Constraints: 2 <= n == nums.length <= @data 1 <= nums[i] <= 10^9 1 <= m == pattern.length < n -1 <= pattern[i] <= 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 500, 1000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, nums, pattern): n = len(nums) m = len(pattern) count = 0 for i in range(n): for j in range(i, n): if j - i + 1 == m + 1: l = i flag = 0 for k in range(m): if pattern[k] == 1 and nums[l + 1] > nums[l]: pass elif pattern[k] == 0 and nums[l + 1] == nums[l]: pass elif pattern[k] == -1 and nums[l + 1] < nums[l]: pass else: flag = 1 break l += 1 if flag == 0: count += 1 return count def solve2(self, nums, pattern): n = len(nums) m = len(pattern) if m >= n: return 0 count = 0 limit = n - m for i in range(limit): prev = nums[i] ok = True for k in range(m): cur = nums[i + k + 1] p = pattern[k] if p == 1: if cur <= prev: ok = False break elif p == 0: if cur != prev: ok = False break else: if cur >= prev: ok = False break prev = cur if ok: count += 1 return count ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) m = int(next(it)) b = [] for i in range(1, m + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result))",other,medium 110,"Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: nums = [4,3,10,9,8] Output: [10,9] Example 2: Input: nums = [4,4,7,6,7] Output: [7,7,6] Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import heapq import math from typing import List class Solution: def solve1(self, nums: List[int]) -> List[int]: res = [] sub_sum = 0 half_sum = sum(nums) // 2 pq = [-n for n in nums] heapq.heapify(pq) while sub_sum <= half_sum: val = -heapq.heappop(pq) res.append(val) sub_sum += val return res def solve2(self, nums: List[int]) -> List[int]: total = 0 for x in nums: total += x res = [] sub = 0 while sub * 2 <= total: max_val = 0 max_idx = -1 for i in range(len(nums)): if nums[i] > max_val: max_val = nums[i] max_idx = i res.append(max_val) sub += max_val nums[max_idx] = 0 return res","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(a) out = [] for it2 in result: out.append(str(it2)) out.append(' ') sys.stdout.write(''.join(out))","greedy,sort",easy 111,"# Problem Statement Alice and Bob are playing a game. They have a permutation $p$ of size $n$ (a permutation of size $n$ is an array of size $n$ where each element from $1$ to $n$ occurs exactly once). They also have a chip, which can be placed on any element of the permutation. Alice and Bob make alternating moves: Alice makes the first move, then Bob makes the second move, then Alice makes the third move, and so on. During the first move, Alice chooses any element of the permutation and places the chip on that element. During each of the next moves, the current player **has to** move the chip to any element that is simultaneously to the left and strictly less than the current element (i. e. if the chip is on the $i$-th element, it can be moved to the $j$-th element if $j < i$ and $p_j < p_i$). If a player cannot make a move (it is impossible to move the chip according to the rules of the game), that player **wins** the game. Let's say that the $i$-th element of the permutation is **lucky** if the following condition holds: - if Alice places the chip on the $i$-th element during her first move, she can win the game no matter how Bob plays (i. e. she has a winning strategy). You have to calculate the number of lucky elements in the permutation. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of lucky elements in the permutation. # Example 1: - Input: n = 3 p = [2, 1, 3] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq p[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, p): for i in range(n): p[i] -= 1 minlose = n mn = n ans = 0 for i in range(n): win = 0 if p[i] < mn: mn = p[i] win = 1 else: win = int(minlose < p[i]) if not win: ans += 1 minlose = min(minlose, p[i]) return ans def solve2(self, n, p): for i in range(n): p[i] -= 1 ans = 0 for i in range(n): mn = n minlose = n win = 0 for j in range(i + 1): if p[j] < mn: mn = p[j] win = 1 else: win = 1 if minlose < p[j] else 0 if not win: if p[j] < minlose: minlose = p[j] if not win: ans += 1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy",hard 112,"You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, num, n, l, r): pass # write your code here``` Example 1: Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 Output: 13 Example 2: Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 Output: 6 Constraints: n == nums.length 1 <= nums.length <= @data 1 <= nums[i] <= 100 1 <= left <= right <= n * (n + 1) / 2 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums, n, left, right): mod = 10**9 + 7 result = (self.sumOfFirstK(nums, n, right) - self.sumOfFirstK(nums, n, left - 1)) return (result + mod) % mod def solve2(self, nums, n, left, right): MOD = 10**9 + 7 def count_and_sum(target): count = 0 total = 0 curr = 0 win = 0 i = 0 for j in range(n): v = nums[j] curr += v win += v * (j - i + 1) while curr > target and i <= j: win -= curr curr -= nums[i] i += 1 count += j - i + 1 total += win return count, total def sum_first_k(k): if k <= 0: return 0 low = min(nums) high = sum(nums) l, r = low, high while l <= r: mid = (l + r) // 2 cnt, _ = count_and_sum(mid) if cnt >= k: r = mid - 1 else: l = mid + 1 cnt, tot = count_and_sum(l) return tot - l * (cnt - k) ans = sum_first_k(right) - sum_first_k(left - 1) return ans % MOD def countAndSum(self, nums, n, target): count = 0 totalSum = 0 currentSum = 0 windowSum = 0 i = 0 for j in range(n): currentSum += nums[j] windowSum += nums[j] * (j - i + 1) while currentSum > target: windowSum -= currentSum currentSum -= nums[i] i += 1 count += j - i + 1 totalSum += windowSum return count, totalSum def sumOfFirstK(self, nums, n, k): if k == 0: return 0 minSum = min(nums) maxSum = sum(nums) low = minSum high = maxSum while low <= high: mid = low + (high - low) // 2 count, _ = self.countAndSum(nums, n, mid) if count >= k: high = mid - 1 else: low = mid + 1 count, total_sum = self.countAndSum(nums, n, low) return total_sum - low * (count - k) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) l = int(next(it)) r = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num, n, l, r) sys.stdout.write(str(result))","two_pointers,sort,binary",hard 113,"You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. solution main function ```python class Solution: def solve(self, n, s): pass # write your code here``` Example 1: Input: n = 2, batteries = [3,3,3] Output: 4 Example 2: Input: n = 2, batteries = [1,1,1,1] Output: 2 Constraints: 1 <= n <= batteries.length <= @data 1 <= batteries[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def check(self, n, batteries, mid): target = n * mid current_sum = 0 for battery in batteries: current_sum += min(battery, mid) if current_sum >= target: return True return False def solve1(self, n, batteries): low = 1 high = sum(batteries) // n result = 0 while low <= high: mid = low + (high - low) // 2 if self.check(n, batteries, mid): result = mid low = mid + 1 else: high = mid - 1 return result def solve2(self, n, batteries): low = 0 high = sum(batteries) // n ans = 0 while low <= high: mid = (low + high) // 2 target = n * mid cur = 0 for b in batteries: if b >= mid: cur += mid else: cur += b if cur >= target: break if cur >= target: ans = mid low = mid + 1 else: high = mid - 1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, m + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,sort,binary",medium 114,"# Problem Statement: Given an array $a=[a_1,a_2,\dots,a_n]$ of $n$ positive integers, you can do operations of two types on it: 1. Add $1$ to **every** element with an **odd** index. In other words change the array as follows: $a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \dots$. 2. Add $1$ to **every** element with an **even** index. In other words change the array as follows: $a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \dots$. Determine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations. Note that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` Where: - The return value is ""YES"" if it is possible to make all elements of the array have the same parity after any number of operations, and ""NO"" otherwise. # Example 1: - Input: n = 5 a = [1000, 1, 1000, 1, 1000] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[10, 1000, 100000]",4000,"[[250, 64, 64], [2000, 200, 64], [16000, 1600, 320]]","import sys from typing import List class Solution: def solve1(self, n: int, a: List[int]) -> str: for i in range(2, n): if a[i] % 2 != a[i - 2] % 2: return ""NO"" return ""YES"" def solve2(self, n: int, a: List[int]) -> str: for odd_t in (0, 1): for even_t in (0, 1): p = (a[0] + odd_t) & 1 ok = True for i in range(1, n): cur = (a[i] + (odd_t if (i % 2 == 0) else even_t)) & 1 if cur != p: ok = False break if ok: return ""YES"" return ""NO"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [] for i in range(n): a.append(int(next(it))) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,math",medium 115,"You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti]. You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other. Return the minimum number of groups you need to make. Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]] Output: 3 Example 2: Input: intervals = [[1,3],[5,6],[8,10],[11,13]] Output: 1 Constraints: 1 <= intervals.length <= @data intervals[i].length == 2 1 <= lefti <= righti <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 100, 64], [4000, 800, 400], [32000, 6400, 3200]]","import heapq class Solution: def solve1(self, intervals): intervals.sort() group = [] for interval in intervals: start, end = interval[0], interval[1] if not group: heapq.heappush(group, end) else: if group[0] < start: heapq.heapreplace(group, end) else: heapq.heappush(group, end) return len(group) def solve2(self, intervals): n = len(intervals) if n == 0: return 0 ans = 0 for i in range(n): p = intervals[i][0] cnt = 0 for j in range(n): a, b = intervals[j][0], intervals[j][1] if a <= p <= b: cnt += 1 if cnt > ans: ans = cnt p = intervals[i][1] cnt = 0 for j in range(n): a, b = intervals[j][0], intervals[j][1] if a <= p <= b: cnt += 1 if cnt > ans: ans = cnt return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) num.append(temp) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))","sort,greedy",medium 116,"Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 5 Output: 12 Example 2: Input: n = 100 Output: 682289015 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def prime(self, n): if n == 1: return 0 i = 2 while i * i <= n: if n % i == 0: return 0 i += 1 return 1 def solve1(self, n): count = 0 for i in range(1, n + 1): if self.prime(i) == 1: count += 1 perm = 1 MOD = 1000000007 for i in range(1, count + 1): perm = (perm * i) % MOD for i in range(1, n - count + 1): perm = (perm * i) % MOD return perm def solve2(self, n): MOD = 1000000007 count = 0 i = 2 while i <= n: isprime = True j = 2 while j * j <= i: if i % j == 0: isprime = False break j += 1 if isprime: count += 1 i += 1 res = 1 i = 2 while i <= count: res = (res * i) % MOD i += 1 k = n - count i = 2 while i <= k: res = (res * i) % MOD i += 1 return res ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return solution = Solution() result = solution.solve(n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",math,easy 117,"You are given an integer array nums with the following properties: nums.length == 2 * n. nums contains n + 1 unique elements. Exactly one element of nums is repeated n times. Return the element that is repeated n times. solution main function ```python class Solution: def solve(self, str_list): pass # write your code here``` Example 1: Input: nums = [1,2,3,3] Output: 3 Example 2: Input: nums = [2,1,2,5,3,2] Output: 2 Constraints: 2 <= n <= @data nums.length == 2 * n 0 <= nums[i] <= 10^4 nums contains n + 1 unique elements and one of them is repeated exactly n times. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve(self, nums): for i in range(len(nums) - 2): if nums[i] == nums[i + 1] or nums[i] == nums[i + 2]: return nums[i] return nums[-1] ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) str_list = [] i = 1 while i <= 2 * n: s = int(next(it)) str_list.append(s) i += 1 solution = Solution() result = solution.solve(str_list) sys.stdout.write(str(result))",greedy,easy 118,"You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: values = [8,1,5,2,6] Output: 11 Example 2: Input: values = [1,2] Output: 2 Constraints: 2 <= values.length <= @data 1 <= values[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, values): n = len(values) maxLeftScore = values[0] maxScore = 0 for i in range(1, n): currentRightScore = values[i] - i maxScore = max(maxScore, maxLeftScore + currentRightScore) currentLeftScore = values[i] + i maxLeftScore = max(maxLeftScore, currentLeftScore) return maxScore def solve2(self, values): n = len(values) max_score = values[0] + values[1] - 1 for i in range(n - 1): for j in range(i + 1, n): s = values[i] + values[j] + i - j if s > max_score: max_score = s return max_score ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [] i = 1 while i <= n: x = int(next(it)) a.append(x) i += 1 solution = Solution() result = solution.solve(a) sys.stdout.write(str(result) + ""\n"")",greedy,easy 119,"Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time. solution main function ```python class Solution: def solve(self, s, d): pass # write your code here``` Example 1: Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 Output: 4 Example 2: Input: arr = [3,3,3,3,3], d = 3 Output: 1 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 10^5 1 <= d <= arr.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, arr, d): arr.append(float('inf')) sz = len(arr) score = [0] * sz st = [] for i in range(sz): duplicates = [] while st and (arr[i] > arr[st[-1]] or i - st[-1] > d): j = st.pop() if st: if arr[st[-1]] > arr[j]: score[st[-1]] = max(score[st[-1]], 1 + score[j]) while duplicates: dup_idx = duplicates.pop() if dup_idx - st[-1] <= d: score[st[-1]] = max(score[st[-1]], 1 + score[dup_idx]) else: duplicates.append(j) if i - j <= d: score[i] = max(score[i], score[j] + 1) st.append(i) score.pop() arr.pop() return max(score) + 1 def solve2(self, arr, d): n = len(arr) if n == 0: return 0 B = max(arr) + 1 P = n + 7 for i in range(n): arr[i] += B ans = 1 for _ in range(n): min_i = -1 min_v = 0 for i in range(n): q = arr[i] // B if q >= P: continue v = arr[i] % B if min_i == -1 or v < min_v: min_v = v min_i = i i = min_i v0 = min_v dpi = 1 steps = 0 j = i - 1 while steps < d and j >= 0: vj = arr[j] % B if vj >= v0: break qj = arr[j] // B if qj >= P: dpj = qj - P else: dpj = qj if dpj + 1 > dpi: dpi = dpj + 1 j -= 1 steps += 1 steps = 0 j = i + 1 while steps < d and j < n: vj = arr[j] % B if vj >= v0: break qj = arr[j] // B if qj >= P: dpj = qj - P else: dpj = qj if dpj + 1 > dpi: dpi = dpj + 1 j += 1 steps += 1 arr[i] = v0 + B * (dpi + P) if dpi > ans: ans = dpi return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) d = int(next(it)) s = [] i = 1 while i <= n: x = int(next(it)) s.append(x) i += 1 solution = Solution() result = solution.solve(s, d) sys.stdout.write(str(result))","dynamic_programming,sort",hard 120,"You are given a positive integer array nums. Partition nums into two arrays, nums1 and nums2, such that: Each element of the array nums belongs to either the array nums1 or the array nums2. Both arrays are non-empty. The value of the partition is minimized. The value of the partition is |max(nums1) - min(nums2)|. Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2. Return the integer denoting the value of such partition. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [1,3,2,4] Output: 1 Example 2: Input: nums = [100,1,10] Output: 9 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, nums): ans = float('inf') nums.sort() for i in range(1, len(nums)): ans = min(ans, nums[i] - nums[i - 1]) return ans def solve2(self, nums): n = len(nums) ans = None for i in range(n): ai = nums[i] for j in range(i + 1, n): d = nums[j] - ai if d < 0: d = -d if ans is None or d < ans: ans = d if ans == 0: return 0 return ans if ans is not None else 0 ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","sort,other",medium 121,"There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person initially at position k (0-indexed) to finish buying tickets. solution main function ```python class Solution: def solve(self, num, k): pass # write your code here``` Example 1: Input: tickets = [2,3,2], k = 2 Output: 6 Example 2: Input: tickets = [5,1,1,1], k = 0 Output: 8 Constraints: n == tickets.length 1 <= n <= @data 1 <= tickets[i] <= 100 0 <= k < n Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 10000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, tickets, k): time = 0 for i in range(len(tickets)): if i <= k: time += min(tickets[k], tickets[i]) else: time += min(tickets[k] - 1, tickets[i]) return time def solve2(self, tickets, k): time = 0 n = len(tickets) i = 0 while True: if tickets[i] > 0: tickets[i] -= 1 time += 1 if i == k and tickets[i] == 0: return time i += 1 if i == n: i = 0 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num, k) sys.stdout.write(str(result))",data_structures,easy 122,"# Problem Statement While exploring the jungle, you have bumped into a rare orangutan with a bow tie! You shake hands with the orangutan and offer him some food and water. In return... The orangutan has gifted you an array $a$ of length $n$. Using $a$, you will construct two arrays $b$ and $c$, both containing $n$ elements, in the following manner: - $b_i = \min(a_1, a_2, \ldots, a_i)$ for each $1 \leq i \leq n$. - $c_i = \max(a_1, a_2, \ldots, a_i)$ for each $1 \leq i \leq n$. Define the score of $a$ as $\sum_{i=1}^n c_i - b_i$ (i.e. the sum of $c_i - b_i$ over all $1 \leq i \leq n$). Before you calculate the score, you can **shuffle** the elements of $a$ however you want. Find the maximum score that you can get if you shuffle the elements of $a$ optimally. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum score that you can get. # Example 1: - Input: n = 1 a = [69] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, n: int, a: List[int]) -> int: if not a: return 0 mx = max(a) mn = min(a) return (mx - mn) * (n - 1) def solve2(self, n: int, a: List[int]) -> int: if not a: return 0 mn = a[0] mx = a[0] for x in a[1:]: if x < mn: mn = x elif x > mx: mx = x return (mx - mn) * (n - 1)","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",sort,easy 123,"# Problem Statement Given a rooted tree T with n vertices (rooted at 1) and an integer array a of length n, count the number of permutations p of [1..n] that satisfy: For every vertex u (1 ≤ u ≤ n), there are exactly a_u ancestors v of u in T such that p_v < p_u. Output the answer modulo 998244353. It is guaranteed that the input is chosen so that at least one valid permutation exists. The main function of the solution is defined as: ```python class Solution: def solve(self, n, fa, a): pass # write your code here``` where: - n: number of vertices in the tree (root is 1) - fa: array of length n-1, where fa[i-2] is the parent of vertex i for i=2..n - a: array of length n, a[u-1] is a_u - return: the number of valid permutations modulo 998244353 # Example 1: - Input: ``` n = 5 fa = [1, 2, 3, 4] a = [0, 1, 2, 3, 4] ``` - Output: ``` 1 ``` # Constraints: - $2 \leq n \leq @data$ - $0 \leq a_i < n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 5000]",4000,"[[500, 125, 64], [4000, 1000, 200], [32000, 8000, 1600]]","import sys sys.setrecursionlimit(200005) class Solution: def solve1(self, n, fa, a): MOD = 998244353 g = [[] for _ in range(n + 1)] for i in range(n - 1): p = fa[i] c = i + 2 g[p].append(c) fac = [1] * (n + 1) ifac = [1] * (n + 1) for i in range(1, n + 1): fac[i] = (fac[i - 1] * i) % MOD ifac[n] = pow(fac[n], MOD - 2, MOD) for i in range(n - 1, -1, -1): ifac[i] = (ifac[i + 1] * (i + 1)) % MOD def C(N, K): if K < 0 or K > N: return 0 res = fac[N] res = (res * ifac[K]) % MOD res = (res * ifac[N - K]) % MOD return res ans_wrapper = [1] dep = [0] * (n + 1) def dfs(u): cnt = [0] * (dep[u] + 2) for v in g[u]: dep[v] = dep[u] + 1 cv = dfs(v) if cv and cv[0] == -1: return [-1] if len(cnt) < len(cv): cnt.extend([0] * (len(cv) - len(cnt))) for i in range(len(cv)): ans_wrapper[0] = (ans_wrapper[0] * C(cnt[i] + cv[i], cnt[i])) % MOD cnt[i] += cv[i] au = a[u - 1] if au > dep[u]: return [-1] nextCnt = [] nextCnt.extend(cnt[:au]) valA = cnt[au] if au < len(cnt) else 0 valA1 = cnt[au + 1] if au + 1 < len(cnt) else 0 nextCnt.append(valA + valA1 + 1) if au + 2 < len(cnt): nextCnt.extend(cnt[au + 2:]) return nextCnt res = dfs(1) if not res or res[0] == -1: return 0 if len(res) != 1: return 0 return ans_wrapper[0] def solve2(self, n, fa, a): MOD = 998244353 if n == 0: return 0 if a[0] != 0: return 0 for u in range(2, n + 1): depth = 0 v = fa[u - 2] while v != 0: depth += 1 v = 0 if v == 1 else fa[v - 2] if a[u - 1] > depth: return 0 p = list(range(1, n + 1)) ans = 0 fa_arr = fa a_arr = a n_local = n while True: valid = True for u in range(1, n_local + 1): pu = p[u - 1] cnt = 0 if u == 1: v = 0 else: v = fa_arr[u - 2] while v != 0: if p[v - 1] < pu: cnt += 1 v = 0 if v == 1 else fa_arr[v - 2] if cnt != a_arr[u - 1]: valid = False break if valid: ans += 1 if ans >= MOD: ans -= MOD i = n_local - 2 while i >= 0 and p[i] >= p[i + 1]: i -= 1 if i < 0: break j = n_local - 1 while p[j] <= p[i]: j -= 1 p[i], p[j] = p[j], p[i] l = i + 1 r = n_local - 1 while l < r: p[l], p[r] = p[r], p[l] l += 1 r -= 1 return ans % MOD ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) fa = [0] * (n - 1) for i in range(n - 1): fa[i] = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, fa, a) sys.stdout.write(str(result) + ""\n"")","dp,graph,math",hard 124,"# Problem Statement Given an array $a$ consisting of $n$ elements, find the maximum possible sum the array can have after performing the following operation **any number of times**: - Choose $2$ **adjacent** elements and flip both of their signs. In other words choose an index $i$ such that $1 \leq i \leq n - 1$ and assign $a_i = -a_i$ and $a_{i+1} = -a_{i+1}$. Note that the answer may be large, so use a 64-bit integer type. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` Where: - `n` is the length of the array. - `a` is an array of length $n$. - The function should return a 64-bit integer representing the maximum sum of the array after performing the above operation any number of times. # Example 1 - Input: n = 3 a = [-1, -1, -1] - Output: 1 # Constraints - $2 \leq n \leq @data$ - $-10^9 \leq a_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): total_sum = 0 neg_count = 0 for i in range(n): if a[i] < 0: neg_count += 1 a[i] = -a[i] total_sum += a[i] if neg_count % 2 == 1: min_val = min(a) total_sum -= 2 * min_val return total_sum def solve2(self, n, a): total = 0 neg_parity = 0 min_abs = None for i in range(n): x = a[i] if x < 0: neg_parity ^= 1 x = -x total += x if min_abs is None or x < min_abs: min_abs = x if neg_parity == 1: total -= 2 * min_abs return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy,sort",medium 125,"You are given a string s. You can perform the following process on s any number of times: Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i]. Delete the closest character to the left of index i that is equal to s[i]. Delete the closest character to the right of index i that is equal to s[i]. Return the minimum length of the final string s that you can achieve. solution main function ```python class Solution: def solve(self, str_arg): pass # write your code here``` Example 1: Input: s = ""abaacbcbb"" Output: 5 Example 2: Input: s = ""aa"" Output: 2 Constraints: 1 <= s.length <= @data s consists only of lowercase English letters Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, s): charFrequency = [0] * 26 totalLength = 0 for currentChar in s: charFrequency[ord(currentChar) - ord('a')] += 1 for frequency in charFrequency: if frequency == 0: continue if frequency % 2 == 0: totalLength += 2 else: totalLength += 1 return totalLength def solve2(self, s): total = 0 base = ord('a') for i in range(26): cnt = 0 ch = chr(base + i) for c in s: if c == ch: cnt += 1 if cnt == 0: continue if cnt % 2 == 0: total += 2 else: total += 1 return total ","import sys def main(): data = sys.stdin.read().split() if not data: return str_arg = data[0] solution = Solution() result = solution.solve(str_arg) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()",string,hard 126,"# Problem Statement You are given an array of positive integers $a_1, a_2, \ldots, a_n$. Make the product of all the numbers in the array (that is, $a_1 \cdot a_2 \cdot \ldots \cdot a_n$) divisible by $2^n$. You can perform the following operation as many times as you like: - select an arbitrary index $i$ ($1 \leq i \leq n$) and replace the value $a_i$ with $a_i=a_i \cdot i$. You cannot apply the operation repeatedly to a single index. In other words, all selected values of $i$ must be different. Find the smallest number of operations you need to perform to make the product of all the elements in the array divisible by $2^n$. Note that such a set of operations does not always exist. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` Where: - `n` is an integer representing the size of the array. - `a` is a vector of integers, representing the given array. - The function should return an integer, representing the minimum number of operations required to make the product divisible by $2^n$, or $-1$ if it is not possible. # Example 1: - Input: n = 2 a = [3, 2] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): cur = 0 for i in range(n): x = a[i] cur += (x & -x).bit_length() - 1 cnt = [0] * 20 for i in range(1, n + 1): cnt[(i & -i).bit_length() - 1] += 1 ans = 0 for i in range(19, -1, -1): while cur < n and cnt[i] > 0: cur += i cnt[i] -= 1 ans += 1 if cur < n: ans = -1 return ans def solve2(self, n, a): cur = 0 for i in range(n): x = a[i] cur += (x & -x).bit_length() - 1 if cur >= n: return 0 ans = 0 while cur < n: best_v = 0 best_i = -1 for i in range(1, n + 1): if a[i - 1] != 0: v = (i & -i).bit_length() - 1 if v > best_v: best_v = v best_i = i if best_v == 0: return -1 cur += best_v ans += 1 a[best_i - 1] = 0 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","math,greedy,sort",medium 127,"In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root ""help"" is followed by the word ""ful"", we can form a derivative ""helpful"". Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length. Return the sentence after the replacement. solution main function ```python class Solution: def solve(self, words, text): pass # write your code here``` Example 1: Input: dictionary = [""cat"",""bat"",""rat""], sentence = ""the cattle was rattled by the battery"" Output: ""the cat was rat by the bat"" Example 2: Input: dictionary = [""a"",""b"",""c""], sentence = ""aadsfasf absbs bbab cadsfafs"" Output: ""a a b c"" Constraints: 1 <= dictionary.length <= @data 1 <= dictionary[i].length <= 100 dictionary[i] consists of only lower-case letters. 1 <= sentence.length <= 10^6 sentence consists of only lower-case letters and spaces. The number of words in sentence is in the range [1, 1000] The length of each word in sentence is in the range [1, 1000] Every two consecutive words in sentence will be separated by exactly one space. sentence does not have leading or trailing spaces. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[16000, 8000, 4000], [128000, 64000, 32000], [1024000, 512000, 256000]]","import collections class Solution: def solve1(self, dictionary, sentence): trie = {} for word in dictionary: cur = trie for c in word: if c not in cur: cur[c] = {} cur = cur[c] cur['#'] = {} words = sentence.split(' ') for i in range(len(words)): words[i] = self.findRoot(words[i], trie) ans = "" "".join(words) return ans def solve2(self, dictionary, sentence): from io import StringIO n = len(sentence) out = StringIO() i = 0 while i < n: if sentence[i] == ' ': out.write(' ') i += 1 continue s = i while i < n and sentence[i] != ' ': i += 1 e = i best_root = None best_len = 1 << 30 for r in dictionary: L = len(r) if L <= e - s: j = 0 match = True while j < L: if sentence[s + j] != r[j]: match = False break j += 1 if match and L < best_len: best_len = L best_root = r if best_len == 1: break if best_root is not None: out.write(best_root) else: k = s while k < e: out.write(sentence[k]) k += 1 return out.getvalue() def findRoot(self, word, trie): root = [] cur = trie for c in word: if '#' in cur: return """".join(root) if c not in cur: return word root.append(c) cur = cur[c] return word ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) words = [] text = """" for i in range(1, n + 1): s = next(it) words.append(s) for i in range(1, m + 1): s = next(it) text += s if i != m: text += "" "" solution = Solution() result = solution.solve(words, text) sys.stdout.write(str(result))","string,data_structures",medium 128,"Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1. Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: nums1 = [1,2,3], nums2 = [2,4] Output: 2 Example 2: Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5] Output: 2 Constraints: 1 <= nums1.length, nums2.length <= @data 1 <= nums1[i], nums2[j] <= 10^9 Both nums1 and nums2 are sorted in non-decreasing order. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import math class Solution: def solve1(self, nums1, nums2): if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1 for num in nums1: if self._binarySearch(num, nums2): return num return -1 def solve2(self, nums1, nums2): i = 0 j = 0 n = len(nums1) m = len(nums2) while i < n and j < m: if nums1[i] == nums2[j]: return nums1[i] if nums1[i] < nums2[j]: i += 1 else: j += 1 return -1 def _binarySearch(self, target, nums): left = 0 right = len(nums) - 1 while left <= right: mid = left + (right - left) // 2 if nums[mid] > target: right = mid - 1 elif nums[mid] < target: left = mid + 1 else: return True return False ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, m + 1): x = int(next(it)) b.append(x) a.sort() b.sort() solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result))","two_pointers,binary",easy 129,"# Problem Statement You are given a list of $n$ integers. You can perform the following operation: you choose an element $x$ from the list, erase $x$ from the list, and subtract the value of $x$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $1$. Given an integer $k$ ($k>0$), find if there is some sequence of $n-1$ operations such that, after applying the operations, the only remaining element of the list is equal to $k$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a): pass # write your code here``` where: - return ""YES"" if there is a sequence of operations that results in the only remaining element of the list being equal to $k$, otherwise return ""NO"". # Example 1: - Input: n = 4, k = 5 a = [4, 2, 2, 7] - Output: YES # Constraints: - $2 \leq n \leq @data$ - $1 \leq k \leq 10^9$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import bisect class Solution: def solve1(self, n, k, a): a.sort() ok = False for i in range(n): x = a[i] + k it = bisect.bisect_left(a, x) if it != len(a) and a[it] == x: ok = True break return ""YES"" if ok else ""NO"" def solve2(self, n, k, a): for i in range(n): ai = a[i] for j in range(n): if i != j and ai - a[j] == k: return ""YES"" return ""NO"" ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a) sys.stdout.write(str(result) + ""\n"")","data_structures,greedy,math,two_pointers",hard 130,"# Problem Statement There is a row of $n$ towers with heights $a_1, a_2, \dots, a_n$. If you look at this row from the left, you see all towers that are strictly higher than all the towers before them. Similarly, if you look from the right, you see all towers that are strictly higher than all towers after them. Let $L(a)$ be the set of heights you see from the left, and $R(a)$ be the set of heights you see from the right, when the sequence of heights is $a$. You are to count the number of subsequences $a'$ of $a$ such that $L(a)=L(a')$ and $R(a)=R(a')$. Since the answer can be large, output it modulo $998244353$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: length of the array - `a`: array of tower heights - return: the number of valid subsequences modulo 998244353 # Example: - Input: ``` n = 9 a = [3, 5, 5, 7, 4, 6, 7, 2, 4] ``` - Output: ``` 51 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 125, 64], [4000, 1000, 400], [32000, 8000, 3200]]","import sys import bisect class Solution: def solve1(self, n, a): MOD = 998244353 leftMax = [] last = 0 for i in range(n): if a[i] > last: leftMax.append(a[i]) last = a[i] rightMax = [] last = 0 for i in range(n - 1, -1, -1): if a[i] > last: rightMax.append(a[i]) last = a[i] class SegmentTree: def __init__(self, size): self.size = size self.val = [0] * (4 * max(1, size)) self.tag = [1] * (4 * max(1, size)) def pushdown(self, p): cur = self.tag[p] if cur != 1: p_left = p << 1 p_right = p << 1 | 1 self.tag[p_left] = self.tag[p_left] * cur % MOD self.tag[p_right] = self.tag[p_right] * cur % MOD self.val[p_left] = self.val[p_left] * cur % MOD self.val[p_right] = self.val[p_right] * cur % MOD self.tag[p] = 1 def pushup(self, p): self.val[p] = (self.val[p << 1] + self.val[p << 1 | 1]) % MOD def rangeMul(self, L, R, p, l, r, mul): if L > R: return if L <= l and r <= R: self.val[p] = self.val[p] * mul % MOD self.tag[p] = self.tag[p] * mul % MOD return self.pushdown(p) mid = (l + r) // 2 if L <= mid: self.rangeMul(L, R, p << 1, l, mid, mul) if R > mid: self.rangeMul(L, R, p << 1 | 1, mid + 1, r, mul) self.pushup(p) def pointAdd(self, idx, v, p, l, r): if l == r: self.val[p] += v if self.val[p] >= MOD: self.val[p] -= MOD return self.pushdown(p) mid = (l + r) // 2 if idx <= mid: self.pointAdd(idx, v, p << 1, l, mid) else: self.pointAdd(idx, v, p << 1 | 1, mid + 1, r) self.pushup(p) def pointQuery(self, idx, p, l, r): if l == r: return self.val[p] self.pushdown(p) mid = (l + r) // 2 if idx <= mid: return self.pointQuery(idx, p << 1, l, mid) else: return self.pointQuery(idx, p << 1 | 1, mid + 1, r) dpL = [0] * n m = len(leftMax) seg = SegmentTree(m) for i in range(n): pos = bisect.bisect_left(leftMax, a[i]) if pos < m and leftMax[pos] == a[i]: val = 1 if pos == 0 else seg.pointQuery(pos - 1, 1, 0, m - 1) dpL[i] = val if pos <= m - 1: seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2) if m > 0: seg.pointAdd(pos, dpL[i], 1, 0, m - 1) else: if pos <= m - 1: seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2) dpR = [0] * n m = len(rightMax) seg = SegmentTree(m) for i in range(n - 1, -1, -1): pos = bisect.bisect_left(rightMax, a[i]) if pos < m and rightMax[pos] == a[i]: val = 1 if pos == 0 else seg.pointQuery(pos - 1, 1, 0, m - 1) dpR[i] = val if pos <= m - 1: seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2) if m > 0: seg.pointAdd(pos, dpR[i], 1, 0, m - 1) else: if pos <= m - 1: seg.rangeMul(pos, m - 1, 1, 0, m - 1, 2) pow2 = [1] * (n + 1) invpow2 = [1] * (n + 1) for i in range(1, n + 1): pow2[i] = (pow2[i - 1] * 2) % MOD inv2 = pow(2, MOD - 2, MOD) for i in range(1, n + 1): invpow2[i] = (invpow2[i - 1] * inv2) % MOD mx = 0 for x in a: mx = max(mx, x) pack = [] sum_rp = 0 for i in range(n): if a[i] == mx: Lp = (dpL[i] * invpow2[i]) % MOD Rp = (dpR[i] * pow2[i]) % MOD pack.append([Lp, Rp]) sum_rp = (sum_rp + Rp) % MOD ans = 0 for Lp, Rp in pack: ans = (ans + Lp * Rp) % MOD sum_rp = (sum_rp - Rp + MOD) % MOD ans = (ans + Lp * sum_rp % MOD * inv2) % MOD if ans < 0: ans += MOD return ans def solve2(self, n, a): MOD = 998244353 last = 0 countL = 0 for i in range(n): if a[i] > last: last = a[i] countL += 1 last = 0 countR = 0 for i in range(n - 1, -1, -1): if a[i] > last: last = a[i] countR += 1 def getLeftK(k): last = 0 cnt = 0 for i in range(n): if a[i] > last: if cnt == k: return a[i] last = a[i] cnt += 1 return None def getRightK(k): last = 0 cnt = 0 for i in range(n - 1, -1, -1): if a[i] > last: if cnt == k: return a[i] last = a[i] cnt += 1 return None ans = 0 total = 1 << n for mask in range(total): left_last = 0 kL = 0 ok = True for i in range(n): if (mask >> i) & 1: x = a[i] if x > left_last: e = getLeftK(kL) if e is None or x != e: ok = False break left_last = x kL += 1 if not ok or kL != countL: continue right_last = 0 kR = 0 for i in range(n - 1, -1, -1): if (mask >> i) & 1: x = a[i] if x > right_last: e = getRightK(kR) if e is None or x != e: ok = False break right_last = x kR += 1 if not ok or kR != countR: continue ans += 1 if ans >= MOD: ans -= MOD return ans % MOD ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,dp",hard 131,"There is a row of $N$coins on the table, and each coin is heads up. Now to flip all the coins tails up, the rule is that you can flip any $N- $1 coin at a time (heads up are flipped tails up and vice versa). Find the shortest sequence of operations (turning each flip of $N-1 coin into one operation). solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Pass in parameters: An even natural number $n$. Return parameters: An integer represents the minimum number of operations required. A vector array that stores the state of the coins on the table after each operation (a row containing $N$integers $0$or $1$, representing the state of each coin, $0$representing heads up and $1$representing tails up). The output of redundant Spaces is not allowed. In cases where there are multiple operation options, only the lexicographic order of the operation needs to output a minimum of one. The lexicographic order of operations means that for each position in an operation, $1$means flip and $0$means no flip. But what you need to output is the state after each operation, $0$means heads up, $1$means tails up. Example 1: Input: n=4 Output: (4,[""0111"", ""1100"", ""0001"", ""1111""]) Constraints: 0 0: w[i] -= 1 if w[i] == 0 and t < n: w[i] = w[t] t += 1 ans += 1 if t >= n: all_zero = True for i in range(m): if w[i] > 0: all_zero = False break if all_zero: break return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) w = [] i = 1 while i <= n: x = int(next(it)) w.append(x) i += 1 solution = Solution() result = solution.solve(n, m, w) sys.stdout.write(str(result) + ""\n"")",greedy,medium 133,"Xuan Xuan and Kai Kai are playing a game called ""Dragon Tiger Fight"", the game board is a line segment, there are $n$barracks on the line segment (numbered $1 \sim n$from left to right), and the adjacent numbered barracks are separated by $1$cm, that is, the board is a line segment with a length of $n-1$cm. There are $c_i$engineers in the $i$barracks. Xuan Xuan is on the left, representing ""dragon""; Kai Kai is on the right, representing ""Tiger"". They use barracks $m$as a demarcation line, the sappers on the left belong to the Dragon force, the sappers on the right belong to the tiger force, and the sappers in barracks $m$are very tangled, they don't belong to either side. The momentum of a barracks is: the number of engineers in the barracks $\times $the distance between the barracks and the $m$barracks; The power of a party participating in the game is defined as the sum of the momentum of all the barracks belonging to that party. During the game, at some point, a total of $s_1$engineers suddenly appeared in the $p_1$barracks. As a friend of Xuan Xuan and Kai Kai, you know that if the gap between the two sides is too great, Xuan Xuan and Kai Kai are not willing to continue to play. In order for the game to continue, you need to select a barracks $p_2$and send all your $s_2$engineers to the barracks $p_2$, making the momentum gap between the two sides as small as possible. Note: The sengineer you hold in the barracks has the same power as the other Sengineers in that barracks (if you fall in the $m$barracks, you don't belong to any power). solution main function ```python class Solution: def solve(self, n, m, p1, s1, s2, c): pass # write your code here``` Pass in parameters: 5 integers: $n,m,p_1,s_1,s_2$. 1 array, c contains $n$positive integers, the first positive integer represents the number of engineers in the barracks numbered $i$at the beginning of $c_i$. Return parameters: An integer $p_2$indicates the barracks number you selected. If multiple numbers are optimal, the smallest number is used. Example 1: Input: n=6,m=4,p1=6,s1=5,s2=2,c=[2, 3, 2, 3, 2, 3] Output: 2 Example 2: Input: n = 6, m = 5, p = 4, s1 = 1, s2 = 1, c = [1, 1, 1, 1, 1, 16] Output: 1 Constraints: 1= n: ans = n elif where <= 1: ans = 1 else: iwhere = int(where) if iwhere == where: ans = iwhere else: ans1 = abs(gap + (m - iwhere) * s2) ans2 = abs(gap + (m - (iwhere + 1)) * s2) if ans1 <= ans2: ans = iwhere else: ans = iwhere + 1 return ans def solve2(self, n, m, p1, s1, s2, c): gap = 0 for i in range(n): idx = i + 1 gap += (m - idx) * c[i] gap += (m - p1) * s1 best_p2 = 1 best_val = abs(gap + (m - 1) * s2) for p2 in range(2, n + 1): val = abs(gap + (m - p2) * s2) if val < best_val: best_val = val best_p2 = p2 return best_p2 ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) c = [] i = 1 while i <= n: x = int(next(it)) c.append(x) i += 1 m = int(next(it)) p1 = int(next(it)) s1 = int(next(it)) s2 = int(next(it)) solution = Solution() result = solution.solve(n, m, p1, s1, s2, c) sys.stdout.write(str(result) + ""\n"")",greedy,hard 134,"Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: piles = [5,3,4,5] Output: 1 Example 2: Input: piles = [3,7,2,3] Output: 1 Constraints: 2 <= piles.length <= @data piles.length is even. 1 <= piles[i] <= 500 sum(piles[i]) is odd. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections import heapq import functools import itertools import re import sys import math from typing import * class Solution: def solve(self, piles: List[int]) -> bool: return True ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num) sys.stdout.write(""1"" if result else ""0"")",math,easy 135,"# Problem Statement: The score of a sequence $[s_1, s_2, \ldots, s_d]$ is defined as $\displaystyle \frac{s_1\cdot s_2\cdot \ldots \cdot s_d}{d!}$, where $d!=1\cdot 2\cdot \ldots \cdot d$. In particular, the score of an empty sequence is $1$. For a sequence $[s_1, s_2, \ldots, s_d]$, let $m$ be the maximum score among all its subsequences. Its cost is defined as the maximum length of a subsequence with a score of $m$. You are given a **non-decreasing** sequence $[a_1, a_2, \ldots, a_n]$ of integers of length $n$. In other words, the condition $a_1 \leq a_2 \leq \ldots \leq a_n$ is satisfied. For each $k=1, 2, \ldots , n$, find the cost of the sequence $[a_1, a_2, \ldots , a_k]$. A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` Where: - `n` is an integer representing the size of the array. - `a` is a vector of integers, representing the given non-decreasing array. - The function should return a vector of integers, where the k-th element represents the cost of the subsequence $[a_1, a_2, \ldots, a_k]$. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: [1, 1, 2] # Constraints: - $1 \leq n \leq @data$ - $1 \leq a_i \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 100, 64], [4000, 800, 400], [32000, 6400, 3200]]","import collections class Solution: def solve(self, n, a): ans = [] k = 0 for i in range(n): while k <= i and a[i - k] >= k + 1: k += 1 ans.append(k) return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) out = [] for x in result: out.append(str(x)) sys.stdout.write("" "".join(out) + ""\n"")","two_pointers,binary,math",hard 136,"In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: label = 14 Output: [1,3,4,14] Example 2: Input: label = 26 Output: [1,2,6,10,26] Constraints: 1 <= label <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 10000, 1000000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, label): ans = [] ans.append(label) level = int(math.log2(label)) if label == 1: return ans while level > 0: parent = label // 2 start = 1 << (level - 1) end = 2 * start - 1 complement = start + end - parent ans.append(complement) label = complement level -= 1 ans.reverse() return ans def solve2(self, label): res = [] x = label while True: res.append(x) if x == 1: break l = x.bit_length() - 1 x = (3 * (1 << (l - 1)) - 1) - (x >> 1) res.reverse() return res ","import sys data = sys.stdin.read().strip().split() idx = 0 if idx < len(data): n = int(data[idx]) idx += 1 else: n = 0 solution = Solution() result = solution.solve(n) out = [] for it in result: out.append(str(it)) if out: sys.stdout.write("" "".join(out))","graph,other",medium 137,"You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. If multiple cells have the same distance, sort them by row index and then by column index. The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. solution main function ```python class Solution: def solve(self, a, b, c, d): pass # write your code here``` Example 1: Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] Example 2: Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Constraints: 1 <= rows, cols <= @data 0 <= rCenter < rows 0 <= cCenter < cols Time limit: @time_limit ms Memory limit: @memory_limit KB ","[20, 50, 100]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve(self, rows: int, cols: int, rCenter: int, cCenter: int) -> list[list[int]]: v = [] for i in range(rows): for j in range(cols): dist = abs(i - rCenter) + abs(j - cCenter) v.append((dist, i, j)) v.sort() res = [] for item in v: res.append([item[1], item[2]]) return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) a = int(next(it)) b = int(next(it)) c = int(next(it)) d = int(next(it)) solution = Solution() result = solution.solve(a, b, c, d) out_lines = [] for s in result: line_parts = [] for it_val in s: line_parts.append(str(it_val) + "" "") out_lines.append("""".join(line_parts).rstrip() + ""\n"") sys.stdout.write("""".join(out_lines))","math,sort,other",easy 138,"# Problem Statement Vova really loves the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation (denoted as $\oplus$). Recently, when he was going to sleep, he came up with a fun game. At the beginning of the game, Vova chooses two binary sequences $s$ and $t$ of length $n$ and gives them to Vanya. A binary sequence is a sequence consisting only of the numbers $0$ and $1$. Vanya can choose integers $l, r$ such that $1 \leq l \leq r \leq n$, and for all $l \leq i \leq r$ **simultaneously** replace $s_i$ with $s_i \oplus s_{i - l + 1}$, where $s_i$ is the $i$-th element of the sequence $s$. In order for the game to be interesting, there must be a possibility to win. Vanya wins if, with an **unlimited** number of actions, he can obtain the sequence $t$ from the sequence $s$. Determine if the game will be interesting for the sequences $s$ and $t$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s, t): pass # write your code here``` where: - return ""YES"" if the game will be interesting, otherwise return ""NO"". # Example 1: - Input: n = 1, s = ""0"", t = ""1"" - Output: NO # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, s, t): for i in range(n): if s[i] == '0' and t[i] == '1': return ""NO"" if s[i] == '1': return ""YES"" return ""YES"" def solve2(self, n, s, t): p = -1 for i in range(n): if s[i] == '1': p = i break if p == -1: for i in range(n): if t[i] == '1': return ""NO"" return ""YES"" for i in range(p): if t[i] == '1': return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) t = next(it) solution = Solution() result = solution.solve(n, s, t) sys.stdout.write(str(result) + ""\n"")","bit_manipulation,constructive_algorithms",hard 139,"Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""(1)+((2))+(((3)))"" Output: 3 Example 2: Input: s = ""()(())((()()))"" Output: 3 Constraints: 1 <= s.length <= @data s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'. It is guaranteed that parentheses expression s is a VPS. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, s: str) -> int: ans = 0 openBrackets = 0 for c in s: if c == '(': openBrackets += 1 elif c == ')': openBrackets -= 1 ans = max(ans, openBrackets) return ans def solve2(self, s: str) -> int: max_depth = 0 depth = 0 for c in s: if c == '(': depth += 1 if depth > max_depth: max_depth = depth elif c == ')': depth -= 1 return max_depth ","import sys def main(): data = sys.stdin.read().split() if not data: s = """" else: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,easy 140,"# Problem Statement Sakurako's exams are over, and she did excellently. As a reward, she received a permutation $p$. Kosuke was not entirely satisfied because he failed one exam and did not receive a gift. He decided to sneak into her room (thanks to the code for her lock) and spoil the permutation so that it becomes simple. A permutation $p$ is considered simple if for every $i$ $(1\le i \le n)$ one of the following conditions holds: - $p_i=i$ - $p_{p_i}=i$ For example, the permutations $[1, 2, 3, 4]$, $[5, 2, 4, 3, 1]$, and $[2, 1]$ are simple, while $[2, 3, 1]$ and $[5, 2, 1, 4, 3]$ are not. In one operation, Kosuke can choose indices $i,j$ $(1\le i,j\le n)$ and swap the elements $p_i$ and $p_j$. Sakurako is about to return home. Your task is to calculate the minimum number of operations that Kosuke needs to perform to make the permutation simple. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the minimum number of operations needed to make the permutation simple # Example 1: - Input: n = 5 p = [1, 2, 3, 4, 5] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq p[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 160], [32000, 3200, 1280]]","import sys class Solution: def solve1(self, n, p): ans = 0 vis = [False] * n for i in range(n): p[i] -= 1 for i in range(n): if vis[i]: continue j = i length = 0 while not vis[j]: vis[j] = True j = p[j] length += 1 ans += (length - 1) // 2 return ans def solve2(self, n, p): ans = 0 for i in range(n): if p[i] > 0: j = i length = 0 while p[j] > 0: v = p[j] p[j] = -p[j] j = v - 1 length += 1 ans += (length - 1) // 2 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,graph,greedy,search",hard 141,"# Problem Statement Timur initially had a binary string$^{\dagger}$ $s$ (possibly of length $0$). He performed the following operation several (possibly zero) times: - Add $\texttt{0}$ to one end of the string and $\texttt{1}$ to the other end of the string. For example, starting from the string $\texttt{1011}$, you can obtain either $\color{red}{\texttt{0}}\texttt{1011}\color{red}{\texttt{1}}$ or $\color{red}{\texttt{1}}\texttt{1011}\color{red}{\texttt{0}}$. You are given Timur's final string. What is the length of the **shortest** possible string he could have started with? $^{\dagger}$ A binary string is a string (possibly the empty string) whose characters are either $\texttt{0}$ or $\texttt{1}$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return a single nonnegative integer — the shortest possible length of Timur's original string. Note that Timur's original string could have been empty, in which case you should return 0 . # Example 1: - Input: n = 3 s = ""100"" - Output: 1 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, s): i = 0 j = n while i + 2 <= j and s[i] != s[j - 1]: i += 1 j -= 1 return j - i def solve2(self, n, s): i = 0 j = n while i + 1 < j and s[i] != s[j - 1]: i += 1 j -= 1 return j - i ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")",two_pointers,medium 142,"# Problem Statement Alice and Bob are playing a game. There is a list of $n$ booleans, each of which is either true or false, given as a binary string $^{\text{∗}}$ of length $n$ (where $\texttt{1}$ represents true, and $\texttt{0}$ represents false). Initially, there are no operators between the booleans. Alice and Bob will take alternate turns placing and or or between the booleans, with Alice going first. Thus, the game will consist of $n-1$ turns since there are $n$ booleans. Alice aims for the final statement to evaluate to true, while Bob aims for it to evaluate to false. Given the list of boolean values, determine whether Alice will win if both players play optimally. To evaluate the final expression, repeatedly perform the following steps until the statement consists of a single true or false: - If the statement contains an and operator, choose any one and replace the subexpression surrounding it with its evaluation. - Otherwise, the statement contains an or operator. Choose any one and replace the subexpression surrounding the or with its evaluation. For example, the expression true or false and false is evaluated as true or (false and false) $=$ true or false $=$ true. It can be shown that the result of any compound statement is unique. $^{\text{∗}}$A binary string is a string that only consists of characters $\texttt{0}$ and $\texttt{1}$ The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return ""YES"" (without quotes) if Alice wins, and ""NO"" (without quotes) otherwise. # Example 1: - Input: n = 2, s = ""11"" - Output: YES # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): s = '1' + s + '1' if ""11"" in s: return ""YES"" else: return ""NO"" def solve2(self, n, s): v0_next = False v1_next = True for p in range(n - 2, -1, -1): b_is_one = s[p + 1] == '1' if p % 2 == 0: v0_curr = ((v1_next if b_is_one else v0_next) or v0_next) v1_curr = True else: v0_curr = ((v1_next if b_is_one else v0_next) and v0_next) v1_curr = (v1_next if b_is_one else v0_next) v0_next, v1_next = v0_curr, v1_curr initial_is_one = s[0] == '1' res = v1_next if initial_is_one else v0_next return ""YES"" if res else ""NO"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")",game,medium 143,"Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that: nums[a] + nums[b] + nums[c] == nums[d], and a < b < c < d solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [1,2,3,6] Output: 1 Example 2: Input: nums = [3,3,6,4,5] Output: 0 Constraints: 4 <= nums.length <= @data 1 <= nums[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[30, 40, 50]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, nums): cnt = 0 n = len(nums) for i in range(n - 3): for j in range(i + 1, n - 2): for k in range(j + 1, n - 1): for l in range(k + 1, n): if nums[i] + nums[j] + nums[k] == nums[l]: cnt += 1 return cnt def solve2(self, nums): cnt = 0 n = len(nums) for i in range(n - 3): for j in range(i + 1, n - 2): for k in range(j + 1, n - 1): s = nums[i] + nums[j] + nums[k] for l in range(k + 1, n): if s == nums[l]: cnt += 1 return cnt ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))",other,easy 144,"Given an array of strings, return the first palindromic string in the array. If there is no such string, return an empty string """". ```python class Solution: def solve(self, words): pass # write your code here``` Example 1: Input: words = [""abc"",""car"",""ada"",""racecar"",""cool""] Output: ""ada"" Example 2: Input: words = [""notapalindrome"",""racecar""] Output: ""racecar"" Constraints: 1 <= words.length <= @data 1 <= words[i].length <= @data words[i] consists only of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections class Solution: def isPalindrome(self, s: str) -> bool: start = 0 end = len(s) - 1 while start <= end: if s[start] != s[end]: return False start += 1 end -= 1 return True def solve1(self, words: list[str]) -> str: for s in words: if self.isPalindrome(s): return s return """" def solve2(self, words: list[str]) -> str: for s in words: i = 0 j = len(s) - 1 ok = True while i < j: if s[i] != s[j]: ok = False break i += 1 j -= 1 if ok: return s return """" ","import sys def main(): data = sys.stdin.read().split() it = iter(data) try: n = int(next(it)) except StopIteration: return s = [] i = 1 while i <= n: try: t = next(it) except StopIteration: t = """" s.append(t) i += 1 solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,easy 145,"You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once). Return the bitwise XOR of all integers in nums3. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: nums1 = [2,1,3], nums2 = [10,2,5,0] Output: 13 Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 0 Constraints: 1 <= nums1.length, nums2.length <= @data 0 <= nums1[i], nums2[j] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import functools import itertools import re import sys import math from typing import * class Solution: def solve1(self, nums1, nums2): xor1 = 0 xor2 = 0 len1 = len(nums1) len2 = len(nums2) if len2 % 2 != 0: for num in nums1: xor1 ^= num if len1 % 2 != 0: for num in nums2: xor2 ^= num return xor1 ^ xor2 def solve2(self, nums1, nums2): ans = 0 for a in nums1: for b in nums2: ans ^= a ^ b return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) b = [] for i in range(1, m + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result))",bit_manipulation,medium 146,"Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [2,3,-1,8,4] Output: 3 Example 2: Input: nums = [1,-1,4] Output: 2 Constraints: 1 <= nums.length <= @data -1000 <= nums[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math from typing import List class Solution: def solve1(self, nums: List[int]) -> int: n = len(nums) if n == 1: return 0 if n == 0: return -1 leftsum = 0 totalsum = sum(nums) for i in range(n): rightsum = totalsum - leftsum - nums[i] if rightsum == leftsum: return i leftsum += nums[i] return -1 def solve2(self, nums: List[int]) -> int: n = len(nums) for i in range(n): leftsum = 0 j = 0 while j < i: leftsum += nums[j] j += 1 rightsum = 0 k = i + 1 while k < n: rightsum += nums[k] k += 1 if leftsum == rightsum: return i return -1","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))",other,easy 147,"Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Example 2: Input: arr = [400] Output: [-1] Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 500, 1000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math from typing import List class Solution: def solve1(self, arr: List[int]) -> List[int]: n = len(arr) mx = -1 p = 0 for i in range(n - 1, -1, -1): p = arr[i] arr[i] = mx if p > mx: mx = p return arr def solve2(self, arr: List[int]) -> List[int]: n = len(arr) if n == 0: return arr for i in range(n - 1): m = arr[i + 1] for j in range(i + 2, n): if arr[j] > m: m = arr[j] arr[i] = m arr[n - 1] = -1 return arr","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return s = [] i = 1 while i <= n: try: x = int(next(it)) except StopIteration: break s.append(x) i += 1 solution = Solution() result = solution.solve(s) out = [] for val in result: out.append(str(val)) out.append(' ') sys.stdout.write(''.join(out)) if __name__ == ""__main__"": main()",other,easy 148,"You are given two integers numBottles and numExchange. numBottles represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations: Drink any number of full water bottles turning them into empty bottles. Exchange numExchange empty bottles with one full water bottle. Then, increase numExchange by one. Note that you cannot exchange multiple batches of empty bottles for the same value of numExchange. For example, if numBottles == 3 and numExchange == 1, you cannot exchange 3 empty water bottles for 3 full bottles. Return the maximum number of water bottles you can drink. solution main function ```python class Solution: def solve(self, n, d): pass # write your code here``` Example 1: Input: numBottles = 13, numExchange = 6 Output: 15 Example 2: Input: numBottles = 10, numExchange = 3 Output: 13 Constraints: 1 <= numBottles <= @data 1 <= numExchange <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[20, 50, 100]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, numBottles, numExchange): b = numBottles e = numExchange return int(b + (((-2*e) + 3 + math.sqrt(4*e*e + 8*b - 12*e + 1)) / 2)) def solve2(self, numBottles, numExchange): total = 0 full = numBottles empty = 0 k = numExchange while True: if full > 0: total += full empty += full full = 0 while empty >= k: empty -= k full += 1 k += 1 if full == 0: break return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) d = int(next(it)) solution = Solution() result = solution.solve(n, d) sys.stdout.write(str(result))","math,other",medium 149,"You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters. Return the score of s. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""hello"" Output: 13 Example 2: Input: s = ""zaz"" Output: 50 Constraints: 2 <= s.length <= @data s consists only of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s: str) -> int: score = 0 for i in range(len(s) - 1): score += abs(ord(s[i]) - ord(s[i + 1])) return score def solve2(self, s: str) -> int: score = 0 for i in range(len(s) - 1): score += abs(ord(s[i]) - ord(s[i + 1])) return score ","import sys def main(): data = sys.stdin.read().split() if not data: return s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()",string,easy 150,"# Problem Statement A club plans to hold a party and will invite some of its $n$ members. The $n$ members are identified by the numbers $1, 2, \dots, n$. If member $i$ is not invited, the party will gain an unhappiness value of $a_i$. There are $m$ pairs of friends among the $n$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited. However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number. What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even? The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, a, p): pass # write your code here``` where: - `p` represents that p.first and p.second are friends. - return the minimum unhappiness value. # Example 1: - Input: n = 3, m = 1 a = [2, 1, 3] p = [(1, 3)] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $0 \leq m \leq \frac{n(n-1)}{2}$ - $0 \leq a[i] \leq 10^4$ - $1 \leq p[i].first, p[i].second \leq n$ - $p[i].first \neq p[i].second$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 153, 64], [4000, 1225, 400], [32000, 9800, 3200]]","import math class Solution: def solve1(self, n, m, a, p): if m % 2 == 0: return 0 ans = float('inf') deg = [0] * n for i in range(m): u, v = p[i] u -= 1 v -= 1 deg[u] += 1 deg[v] += 1 ans = min(ans, a[u] + a[v]) for i in range(n): if deg[i] % 2 != 0: ans = min(ans, a[i]) return ans def solve2(self, n, m, a, p): if m % 2 == 0: return 0 total = 0 for i in range(n): total += a[i] for i in range(m): u, v = p[i] p[i] = (u - 1, v - 1) best = total limit = 1 << n for mask in range(limit): parity = 0 for i in range(m): u, v = p[i] if ((mask >> u) & 1) and ((mask >> v) & 1): parity ^= 1 if parity == 0: s = 0 for i in range(n): if (mask >> i) & 1: s += a[i] unhappiness = total - s if unhappiness < best: best = unhappiness return best ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) p = [] for i in range(m): first = int(next(it)) second = int(next(it)) p.append((first, second)) solution = Solution() result = solution.solve(n, m, a, p) sys.stdout.write(str(result) + ""\n"")",graph,hard 151,"Give an integer N and K transformation rules. Rules: - Change one digit to another. - The right part of the rule cannot be zero. Find out how many different integers can be produced by any number of transformations (0 or more). Only the number of outputs is required. solution main function ```python class Solution: def solve(self, N, K, rules): pass # write your code here``` Example 1: Input: N = 234, K = 2, rules = [ [2, 5], [3, 6] ] Output: 4 Constraints: 0 0: sum += BIT[x] x -= (x & -x) return sum def update(self, BIT, x, val): while x < len(BIT): BIT[x] += val x += (x & -x) def solve1(self, queries, m): if m == 1: return [0] n = len(queries) ans = [] tree = [0] * (m + n + 1) hash = [0] * (m + 1) for i in range(1, m + 1): hash[i] = n + i self.update(tree, n + i, 1) for q in queries: ans.append(self.querySum(tree, hash[q] - 1)) self.update(tree, hash[q], -1) self.update(tree, n, 1) hash[q] = n n -= 1 return ans def solve2(self, queries, m): n = len(queries) res = [0] * n for i in range(n): q = queries[i] last = -1 j = i - 1 while j >= 0: if queries[j] == q: last = j break j -= 1 if last != -1: cnt = 0 t = i - 1 while t > last: v = queries[t] dup = False k = t + 1 while k <= i - 1: if queries[k] == v: dup = True break k += 1 if not dup: cnt += 1 t -= 1 res[i] = cnt else: s_len = 0 t = i - 1 while t >= 0: v = queries[t] dup = False k = t + 1 while k <= i - 1: if queries[k] == v: dup = True break k += 1 if not dup: s_len += 1 t -= 1 less = 0 t = i - 1 while t >= 0: v = queries[t] dup = False k = t + 1 while k <= i - 1: if queries[k] == v: dup = True break k += 1 if not dup and v < q: less += 1 t -= 1 res[i] = s_len + (q - 1) - less return res ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, m) out = [] for v in result: out.append(str(v)) out.append(' ') sys.stdout.write(''.join(out))",other,medium 153,"There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]: arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order. timei is the time needed to prepare the order of the ith customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input. Return the average waiting time of all customers. The generated output is printed with four digits after the decimal point. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: customers = [[1,2],[2,5],[4,3]] Output: 5.0000 Example 2: Input: customers = [[5,2],[5,4],[10,3],[20,1]] Output: 3.2500 Constraints: 1 <= customers.length <= @data 1 <= arrivali, timei <= 10^4 arrivali <= arrivali+1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, customers): nextIdleTime = 0 netWaitTime = 0 for i in range(len(customers)): nextIdleTime = max(customers[i][0], nextIdleTime) + customers[i][1] netWaitTime += nextIdleTime - customers[i][0] averageWaitTime = float(netWaitTime) / len(customers) return averageWaitTime def solve2(self, customers): current_time = 0 total_wait = 0 for a, t in customers: if current_time < a: current_time = a current_time += t total_wait += current_time - a return total_wait / len(customers) ","import sys def main(): data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(f""{result:.4f}"") if __name__ == ""__main__"": main()",greedy,medium 154,"You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 1 Output: 12 Example 2: Input: n = 5000 Output: 30228214 Constraints: n == grid.length 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","class Solution: def solve1(self, n): mod = 10**9 + 7 twoC = 6 threeC = 6 for i in range(2, n + 1): oldTwo = twoC oldThree = threeC twoC = (3 * oldTwo + 2 * oldThree) % mod threeC = (2 * oldTwo + 2 * oldThree) % mod return (twoC + threeC) % mod def solve2(self, n): mod = 10**9 + 7 two = 6 three = 6 i = 2 while i <= n: old_two = two old_three = three two = (3 * old_two + 2 * old_three) % mod three = (2 * old_two + 2 * old_three) % mod i += 1 return (two + three) % mod ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return solution = Solution() result = solution.solve(n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",dynamic_programming,hard 155,"You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions: The sum of the grades of students in the ith group is less than the sum of the grades of students in the (i + 1)th group, for all groups (except the last). The total number of students in the ith group is less than the total number of students in the (i + 1)th group, for all groups (except the last). Return the maximum number of groups that can be formed. solution main function ```python class Solution: def solve(self, nums): pass # write your code here``` Example 1: Input: grades = [10,6,12,7,3,5] Output: 3 Example 2: Input: grades = [8,8] Output: 1 Constraints: 1 <= grades.length <= @data 1 <= grades[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, A): return int(math.sqrt(len(A) * 2 + 0.25) - 0.5) def solve2(self, A): n = len(A) k = 0 s = 0 while s + (k + 1) <= n: k += 1 s += k return k ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) nums = [] for i in range(1, n + 1): x = int(next(it)) nums.append(x) solution = Solution() result = solution.solve(nums) sys.stdout.write(str(result))","math,search,greedy",medium 156,"# Problem Statement You are given a string $s$ consisting of the characters 0, 1, and ?. Let's call a string **unstable** if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...). Let's call a string **beautiful** if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes **unstable**. For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not. Calculate the number of beautiful contiguous substrings of the string $s$. The main function of the solution is defined as: ```python class Solution: def solve(self, s): pass # write your code here``` where: - return:the number of beautiful substrings of the string s. # Example 1: - Input: s = ""0?10"" - Output: 8 # Constraints: - $1 \leq |s| \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, s): type = 0 cnt = 0 ans = 0 j = 0 n = len(s) for i in range(n): while j < n: if s[j] == '?': j += 1 elif cnt == 0 or type == (int(s[j]) ^ (j % 2)): cnt += 1 type = int(s[j]) ^ (j % 2) j += 1 else: break ans += j - i if s[i] != '?': cnt -= 1 return ans def solve2(self, s): n = len(s) ans = 0 for l in range(n): forced = -1 for r in range(l, n): ch = s[r] if ch != '?': need = (ord(ch) - 48) ^ ((r - l) & 1) if forced == -1: forced = need elif forced != need: break ans += 1 return ans ","import sys def main(): s = sys.stdin.buffer.readline().decode().strip() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","search,string,dp,two_pointers",hard 157,"Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",4000,"[[10000, 5000, 500], [80000, 40000, 4000], [640000, 320000, 32000]]","import math class Solution: def floorMod(self, x, y): return ((x % y) + y) % y def solve1(self, n): result = [[0] * n for _ in range(n)] cnt = 1 dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]] d = 0 row = 0 col = 0 while cnt <= n * n: result[row][col] = cnt cnt += 1 r = self.floorMod(row + dirs[d][0], n) c = self.floorMod(col + dirs[d][1], n) if result[r][c] != 0: d = (d + 1) % 4 row += dirs[d][0] col += dirs[d][1] return result def solve2(self, n): result = [[0] * n for _ in range(n)] num = 1 top, bottom, left, right = 0, n - 1, 0, n - 1 while left <= right and top <= bottom: for c in range(left, right + 1): result[top][c] = num num += 1 for r in range(top + 1, bottom + 1): result[r][right] = num num += 1 if top < bottom and left < right: for c in range(right - 1, left - 1, -1): result[bottom][c] = num num += 1 for r in range(bottom - 1, top, -1): result[r][left] = num num += 1 top += 1 bottom -= 1 left += 1 right -= 1 return result ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) out_lines = [] for str_item in result: line_parts = [] for it_item in str_item: line_parts.append(str(int(it_item))) out_lines.append("" "".join(line_parts) + "" "") sys.stdout.write(""\n"".join(out_lines) + (""\n"" if out_lines else """"))",math,easy 158,"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. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [5,6,2,7,4] Output: 34 Example 2: Input: nums = [4,2,5,9,7,4,8] Output: 64 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= 10^3 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums): biggest = 0 secondBiggest = 0 smallest = float('inf') secondSmallest = float('inf') for num in nums: if num > biggest: secondBiggest = biggest biggest = num else: secondBiggest = max(secondBiggest, num) if num < smallest: secondSmallest = smallest smallest = num else: secondSmallest = min(secondSmallest, num) return biggest * secondBiggest - smallest * secondSmallest def solve2(self, nums): n = len(nums) ans = None for i in range(n - 1): for j in range(i + 1, n): p = nums[i] * nums[j] for k in range(n - 1): if k == i or k == j: continue for l in range(k + 1, n): if l == i or l == j: continue diff = p - nums[k] * nums[l] if ans is None or diff > ans: ans = diff if ans is None: return 0 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))",sort,easy 159,"You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] Output: 3 Example 2: Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] Output: 3 Constraints: 1 <= rectangles.length <= @data rectangles[i].length == 2 1 <= li, wi <= 10^9 li != wi Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math from typing import List class Solution: def solve1(self, v: List[List[int]]) -> int: maxSqr = 0 ans = 0 for i in range(len(v)): temp = min(v[i][0], v[i][1]) if temp == maxSqr: ans += 1 elif temp > maxSqr: maxSqr = temp ans = 1 return ans def solve2(self, v: List[List[int]]) -> int: maxSqr = 0 ans = 0 for i in range(len(v)): a = v[i][0] b = v[i][1] m = a if a < b else b if m > maxSqr: maxSqr = m ans = 1 elif m == maxSqr: ans += 1 return ans","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return s = [] for i in range(1, n + 1): temp = [] x = int(next(it)) temp.append(x) x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",sort,easy 160,"# Problem Statement There are $n$ candies put from left to right on a table. The candies are numbered from left to right. The $i$-th candy has weight $w_i$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row). Of course, if Alice ate a candy, Bob can't eat it (and vice versa). They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total? The main function of the solution is defined as: ```python class Solution: def solve(self, n, w): pass # write your code here``` where: - return: the maximum number of candies Alice and Bob can eat in total while satisfying the condition. # Example 1: - Input: n = 3 w = [10,20,10] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq w[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, w): ans = 0 i, j = 0, n - 1 L, R = 0, 0 while i <= j: L += w[i] i += 1 while R < L and j >= i: R += w[j] j -= 1 if L == R: ans = max(ans, i + n - j - 1) return ans def solve2(self, n, w): ans = 0 prefix = 0 for k in range(0, n + 1): if k > 0: prefix += w[k - 1] s = 0 j = n - 1 while j >= k and s < prefix: s += w[j] j -= 1 if s == prefix: ans = max(ans, k + (n - (j + 1))) return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) w = [0] * n for i in range(0, n): w[i] = int(next(it)) solution = Solution() result = solution.solve(n, w) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary,greedy",medium 161,"A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: cost = [1,2,3] Output: 5 Example 2: Input: cost = [6,5,7,9,2,2] Output: 23 Constraints: 1 <= cost.length <= @data 1 <= cost[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, cost): cost.sort(reverse=True) sum_val = 0 count = 0 for i in range(len(cost)): if count == 2: count = 0 else: sum_val += cost[i] count += 1 return sum_val def solve2(self, cost): n = len(cost) remaining = n total = 0 while remaining > 0: idx = -1 maxv = -1 for i in range(n): v = cost[i] if v > maxv: maxv = v idx = i total += maxv cost[idx] = -1 remaining -= 1 if remaining == 0: break idx = -1 maxv = -1 for i in range(n): v = cost[i] if v > maxv: maxv = v idx = i total += maxv cost[idx] = -1 remaining -= 1 if remaining == 0: break idx = -1 maxv = -1 for i in range(n): v = cost[i] if v > maxv: maxv = v idx = i cost[idx] = -1 remaining -= 1 return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))","sort,greedy",easy 162,"# Problem Statement You are given a string $s$ of length $n$. Let's define two operations you can apply on the string: - remove the first character of the string; - remove the second character of the string. Your task is to find the number of distinct **non-empty** strings that can be generated by applying the given operations on the initial string any number of times (possibly zero), in any order. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return:the number of distinct non-empty strings you can get. # Example 1: - Input: n = 5 s = ""aaaaa"" - Output: 5 # Constraints: - $1 \leq n \leq @data$ - $s[i]$ is a lowercase English letter - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, s): vis = [0] * 26 ans = 0 for i in range(n): char_code = ord(s[i]) - ord('a') if vis[char_code]: continue vis[char_code] = 1 ans += n - i return ans def solve2(self, n, s): ans = 0 for i in range(n): ch = s[i] seen = False j = 0 while j < i: if s[j] == ch: seen = True break j += 1 if not seen: ans += n - i return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","string,dp,data_structures",hard 163,"Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Example 2: Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Constraints: 1 <= nums.length, index.length <= @data nums.length == index.length 0 <= nums[i] <= 100 0 <= index[i] <= i Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, nums, arr): n = len(arr) tar = [] if n == 0: return tar tar.append(nums[0]) for i in range(1, n): tar.insert(arr[i], nums[i]) return tar def solve2(self, nums, arr): n = len(arr) if n == 0: return [] for i in range(n): v = nums[i] j = i idx = arr[i] while j > idx: nums[j] = nums[j - 1] j -= 1 nums[idx] = v return nums ","import sys def main(): data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, n + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) out = [] for it2 in result: out.append(str(it2)) out.append(' ') sys.stdout.write(''.join(out)) if __name__ == ""__main__"": main()",other,easy 164,"# Problem Statement Recall that the sequence $b$ is a a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For example, if $a=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$. You are given a sequence $a$ consisting of $n$ positive and negative elements (there is no zeros in the sequence). Your task is to choose **maximum by size** (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the **maximum sum** of elements. In other words, if the maximum length of alternating subsequence is $k$ then your task is to find the **maximum sum** of elements of some alternating subsequence of length $k$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum sum of the maximum by size alternating subsequence, please use `long long` type for the return value # Example 1: - Input: n = 5 a = [1, 2, 3, -1, -2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): neg = (0, 0) pos = (0, 0) for x in a: if x < 0: neg = max(neg, (pos[0] + 1, pos[1] + x)) else: pos = max(pos, (neg[0] + 1, neg[1] + x)) return max(neg, pos)[1] def solve2(self, n, a): total = 0 cur = a[0] for i in range(1, n): x = a[i] if (x >= 0) == (cur >= 0): if x > cur: cur = x else: total += cur cur = x total += cur return total ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy,two_pointers",hard 165,"# Problem Statement Let's call a number a binary decimal if it is a positive integer and all digits in its decimal notation are either $0$ or $1$. For example, $1\,010\,111$ is a binary decimal, while $10\,201$ and $787\,788$ are not. Given a number $n$, you are asked whether or not it is possible to represent $n$ as a product of some (not necessarily distinct) binary decimals. The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - return ""YES"" if n can be represented as a product of binary decimals, and ""NO"" otherwise. # Example 1: - Input: n = 121 - Output: YES # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 100000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): candidates = [ 10, 11, 100, 101, 110, 111, 1001, 1011, 1101, 1111, 10001, 10011, 10111, 10101, 11101, 11011, 11111, 11001 ] candidates.sort(reverse=True) for value in candidates: while n % value == 0: n //= value return ""YES"" if n == 1 else ""NO"" def solve2(self, n): def is_binary_decimal(x): while x > 0: d = x % 10 if d != 0 and d != 1: return False x //= 10 return True def dec_len(x): l = 0 while x > 0: l += 1 x //= 10 return l if l > 0 else 1 def candidate_by_index(idx): L = 1 while (1 << L) - 1 < idx: L += 1 prev = (1 << (L - 1)) - 1 m = idx - prev s = m - 1 value = 0 for pos in range(L): if pos == 0: digit = 1 else: digit = (s >> (L - 1 - pos)) & 1 value = value * 10 + digit return value if n == 1: return ""YES"" t = n c2 = 0 while t % 2 == 0: c2 += 1 t //= 2 t = n c5 = 0 while t % 5 == 0: c5 += 1 t //= 5 if c2 != c5: return ""NO"" if is_binary_decimal(n): return ""YES"" stack = [[n, 2]] while stack: cur, idx = stack[-1] if cur == 1: return ""YES"" if is_binary_decimal(cur): return ""YES"" local_max_idx = (1 << dec_len(cur)) - 1 if idx > local_max_idx: stack.pop() if not stack: return ""NO"" stack[-1][1] += 1 continue d = candidate_by_index(idx) if d > 1 and cur % d == 0: stack.append([cur // d, 2]) else: stack[-1][1] += 1 return ""NO"" ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","dp,math",hard 166,"# Problem Statement When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book. Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read. The main function of the solution is defined as: ```python class Solution: def solve(self, n, t, a): pass # write your code here``` where: - return: the maximum number of books Valera can read. # Example 1: - Input: n = 4, t = 5, a = [3, 1, 2, 1] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq t \leq 10^9$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, t, a): i = 0 j = 0 k = 0 mx = 0 current_sum = 0 while i < n: if current_sum + a[i] <= t: k += 1 current_sum += a[i] else: i -= 1 k -= 1 current_sum -= a[j] j += 1 i += 1 if mx < k: mx = k return mx def solve2(self, n, t, a): mx = 0 i = 0 while i < n: s = 0 j = i cnt = 0 while j < n: if s + a[j] <= t: s += a[j] cnt += 1 j += 1 else: break if cnt > mx: mx = cnt i += 1 return mx ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) t = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, t, a) sys.stdout.write(str(result) + ""\n"")","search,two_pointers",medium 167,"You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions: 0 <= i < j < k < nums.length nums[i], nums[j], and nums[k] are pairwise distinct. In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k]. Return the number of triplets that meet the conditions. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [4,4,2,4,3] Output: 3 Example 2: Input: nums = [1,1,1,1,1] Output: 0 Constraints: 3 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, nums): freq = collections.Counter(nums) left = 0 right = len(nums) res = 0 for i in freq.values(): value = i right -= value res += left * value * right left += value return res def solve2(self, nums): n = len(nums) res = 0 for i in range(n - 2): ai = nums[i] for j in range(i + 1, n - 1): aj = nums[j] if ai == aj: continue for k in range(j + 1, n): ak = nums[k] if ak != ai and ak != aj: res += 1 return res ","import sys import ctypes data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) result = ctypes.c_int(result).value sys.stdout.write(str(result))","sort,other",easy 168,"You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters. Return the score of s. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""hello"" Output: 13 Example 2: Input: s = ""zaz"" Output: 50 Constraints: 2 <= s.length <= @data s consists only of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, s: str) -> int: score = 0 for i in range(len(s) - 1): score += abs(ord(s[i]) - ord(s[i + 1])) return score def solve2(self, s: str) -> int: score = 0 for i in range(len(s) - 1): score += abs(ord(s[i]) - ord(s[i + 1])) return score ","import sys def main(): data = sys.stdin.read().split() it = iter(data) s = next(it) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,easy 169,"You are given a string s of length n and an integer k, where n is a multiple of k. Your task is to hash the string s into a new string called result, which has a length of n / k. First, divide s into n / k substrings , each with a length of k. Then, initialize result as an empty string. For each substring in order from the beginning: The hash value of a character is the index of that character in the English alphabet (e.g., 'a' → 0, 'b' → 1, ..., 'z' → 25). Calculate the sum of all the hash values of the characters in the substring. Find the remainder of this sum when divided by 26, which is called hashedChar. Identify the character in the English lowercase alphabet that corresponds to hashedChar. Append that character to the end of result. Return result. solution main function ```python class Solution: def solve(self, s, n): pass # write your code here``` Example 1: Input: s = ""abcd"", k = 2 Output: ""bf"" Example 2: Input: s = ""mxz"", k = 3 Output: ""i"" Constraints: 1 <= k <= 100 k <= s.length <= @data s.length is divisible by k. s consists only of lowercase English letter Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, s, k): ans = [] cou = 0 for i in range(len(s)): cou += ord(s[i]) - 97 if (i + 1) % k == 0: ans.append(chr(cou % 26 + 97)) cou = 0 return """".join(ans) def solve2(self, s, k): res = """" n = len(s) i = 0 while i < n: total = 0 end = i + k while i < end: total += ord(s[i]) - 97 i += 1 res += chr(total % 26 + 97) return res ","import sys def main(): data = sys.stdin.read().strip().split() if not data: return it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(s, n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","string,other",medium 170,"# Problem Statement You are given an array `a` of length `n`. You may perform the following operation any number of times (including zero): 1) Choose any integer `k` with `2 ≤ k ≤ n`, and select any set of `k` distinct indices `S = {i1, i2, …, ik}`. 2) Let `x = a[i1] + a[i2] + … + a[ik]`, and set `y = x − floor(x/k) * k` (i.e., `y = x mod k`). 3) Among the selected `k` elements, decrease the `y` smallest values by `1`. - If two elements have different values, the one with smaller value is considered smaller. - If two elements have the same value, the one with the smaller index is considered smaller. - If `y = 0`, nothing is decreased. Your task is to compute the minimum possible sum of the array elements after performing any number of operations, or determine that the sum can be decreased indefinitely. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: the length of the array - `a`: the array of integers - return: the minimum possible sum, or `-1` if it can be decreased indefinitely # Example: - Input: ``` n = 2 a = [2, 1] ``` - Output: ``` 2 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): a.sort() if n == 1: return a[0] if n == 2: s = a[0] + a[1] return s - (s % 2) sum_val = sum(a) ans = sum_val maxv = a[-1] l = 1 for i in range(2, n): g = math.gcd(l, i) tmp = (l // g) * i if tmp > maxv: l = 0 break l = tmp for i in range(2, n): lhs = a[i] % l if l != 0 else a[i] rhs = a[i - 1] % l if l != 0 else a[i - 1] if lhs != rhs: return -1 pref = a[0] lastRem = -1 for i in range(1, n): pref += a[i] r = pref % (i + 1) if r >= 2: return -1 if lastRem == -1: lastRem = r elif lastRem != r: return -1 ans = min(ans, sum_val - r) return ans def solve2(self, n, a): a.sort() if n == 1: return a[0] if n == 2: s = a[0] + a[1] return s - (s % 2) sum_val = 0 for v in a: sum_val += v ans = sum_val maxv = a[-1] l = 1 i = 2 while i < n: g = math.gcd(l, i) tmp = (l // g) * i if tmp > maxv: l = 0 break l = tmp i += 1 i = 2 while i < n: lhs = a[i] % l if l != 0 else a[i] rhs = a[i - 1] % l if l != 0 else a[i - 1] if lhs != rhs: return -1 i += 1 pref = a[0] lastRem = -1 i = 1 while i < n: pref += a[i] r = pref % (i + 1) if r >= 2: return -1 if lastRem == -1: lastRem = r elif lastRem != r: return -1 cur = sum_val - r if cur < ans: ans = cur i += 1 return ans","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","math,sort",hard 171,"# Problem Statement For a permutation $p_1,p_2,\dots,p_n$ of length $n$, the coloring sequence $s$ is produced by the following process: - Initially, there are $n$ white cells indexed $1 \dots n$. At second $0$, all scores are $0$. - At second $i$ ($1 \le i \le n$): - If $i>1$, find the nearest black cell to cell $p_i$ among already colored cells, and increase the score of that black cell by $1$. In case of multiple nearest black cells, choose the one with the lowest index. - Color cell $p_i$ black. After all cells are colored black, let $s_i$ be the score of cell $i$; the vector $s$ is the coloring sequence. You are given an incomplete coloring sequence $s$, where some $s_i$ are fixed and others are unknown (denoted as $-1$). Count the number of permutations $p$ that can produce a coloring sequence consistent with the given $s$. Print the answer modulo $998244353$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - `n`: number of cells - `s`: length-`n` array, with `-1` for unknown entries, otherwise `0..n-1` - return: number of valid permutations modulo `998244353` # Example 1: - Input: ``` n = 3 s = [-1, -1, 1] ``` - Output: ``` 2 ``` # Constraints: - $2 \le n \le @data$ - $-1 \le s_i \le n-1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20, 60, 100]",4000,"[[500, 250, 100], [4000, 2000, 800], [32000, 16000, 6400]]","import sys class Solution: def solve(self, n, s): MOD = 998244353 a = [-1] * (n + 2) for i in range(n): a[i + 1] = s[i] fu = 0 for i in range(1, n + 1): fu += max(0, a[i]) if fu >= n: return 0 fac = [1] * (n + 1) ifac = [1] * (n + 1) for i in range(1, n + 1): fac[i] = (fac[i - 1] * i) % MOD if n >= 0: ifac[n] = pow(fac[n], MOD - 2, MOD) for i in range(n, 0, -1): ifac[i - 1] = (ifac[i] * i) % MOD def Cnk(N, K): if K < 0 or K > N: return 0 res = fac[N] res = (res * ifac[K]) % MOD res = (res * ifac[N - K]) % MOD return res dp = {} def dfs(l, r, pl, pr): if l > r: return 1 if pl <= 1 and pr <= 1 else 0 state = (l, r, pl, pr) if state in dp: return dp[state] if (pl - 1) + (pr - 1) > r - l + 1: return 0 ans = 0 for k in range(l, r + 1): p0 = 1 if l > 1 and (r == n or k - l <= r - k) else 0 p1 = 1 if r < n and (l == 1 or k - l > r - k) else 0 choose_ways = Cnk(r - l, k - l) if pl == 1 and p0: continue if pr == 1 and p1: continue if a[k] == -1: new_pl_left = max(0, pl - p0) new_pr_right = max(0, pr - p1) left_ways = dfs(l, k - 1, new_pl_left, 0) right_ways = dfs(k + 1, r, 0, new_pr_right) term = (choose_ways * left_ways) % MOD term = (term * right_ways) % MOD ans = (ans + term) % MOD else: for o in range(a[k] + 1): new_pl_left = max(0, pl - p0) new_pr_right = max(0, pr - p1) left_ways = dfs(l, k - 1, new_pl_left, o + 1) if left_ways == 0: continue right_ways = dfs(k + 1, r, a[k] - o + 1, new_pr_right) term = (choose_ways * left_ways) % MOD term = (term * right_ways) % MOD ans = (ans + term) % MOD dp[state] = ans return ans return dfs(1, n, 1, 1) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [0] * n for i in range(n): s[i] = int(next(it)) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","dp,math",hard 172,"There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with the maximum number of coins. Your friend Bob will pick the last pile. Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins that you can have. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: piles = [2,4,1,2,7,8] Output: 9 Example 2: Input: piles = [2,4,5] Output: 4 Constraints: 3 <= piles.length <= @data piles.length % 3 == 0 1 <= piles[i] <= 10^4 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve(self, piles): myCoins = 0 piles.sort() l, r = 0, len(piles) - 1 while l < r: l += 1 myCoins += piles[r - 1] r -= 2 return myCoins ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num) sys.stdout.write(str(result) + ""\n"")","math,greedy",hard 173,"# Problem Statement Vanya really likes math. One day when he was solving another math problem, he came up with an interesting tree. This tree is built as follows. Initially, the tree has only one vertex with the number $1$ — the root of the tree. Then, Vanya adds two children to it, assigning them consecutive numbers — $2$ and $3$, respectively. After that, he will add children to the vertices in increasing order of their numbers, starting from $2$, assigning their children the minimum unused indices. As a result, Vanya will have an infinite tree with the root in the vertex $1$, where each vertex will have exactly two children, and the vertex numbers will be arranged sequentially by layers. Vanya wondered what the sum of the vertex numbers on the path from the vertex with number $1$ to the vertex with number $n$ in such a tree is equal to. Since Vanya doesn't like counting, he asked you to help him find this sum. The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - return: the sum of the vertex numbers on the path from the vertex with number $1$ to the vertex with number $n$. # Example 1: - Input: n = 3 - Output: 4 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000000, 1000000000000, 10000000000000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n: int) -> int: ans = 0 while n > 0: ans += n n //= 2 return ans def solve2(self, n: int) -> int: ans = 0 while n > 0: ans += n n //= 2 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")","math,tree,bit_manipulation",easy 174,"You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY). The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1|. There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road goes in one direction from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times. Return the minimum cost required to go from (startX, startY) to (targetX, targetY). solution main function ```python class Solution: def solve(self, start, targe, edge): pass # write your code here``` Example 1: Input: start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]] Output: 5 Example 2: Input: start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]] Output: 7 Constraints: start.length == target.length == 2 1 <= startX <= targetX <= 10^5 1 <= startY <= targetY <= 10^5 1 <= specialRoads.length <= @data specialRoads[i].length == 5 startX <= x1i, x2i <= targetX startY <= y1i, y2i <= targetY 1 <= costi <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[20, 50, 100]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import heapq class Solution: def solve1(self, start, target, specialRoads): INF = float('inf') n = len(specialRoads) d = [INF] * n pq = [] for i in range(n): d[i] = abs(start[0] - specialRoads[i][0]) + abs(start[1] - specialRoads[i][1]) + specialRoads[i][4] heapq.heappush(pq, (d[i], i)) ans = abs(start[0] - target[0]) + abs(start[1] - target[1]) while pq: d_c, c = heapq.heappop(pq) if d_c != d[c]: continue ans = min(ans, d_c + abs(target[0] - specialRoads[c][2]) + abs(target[1] - specialRoads[c][3])) for nxt in range(n): w = abs(specialRoads[c][2] - specialRoads[nxt][0]) + abs(specialRoads[c][3] - specialRoads[nxt][1]) + specialRoads[nxt][4] if d_c + w < d[nxt]: d[nxt] = d_c + w heapq.heappush(pq, (d[nxt], nxt)) return ans def solve2(self, start, target, specialRoads): sx, sy = start tx, ty = target n = len(specialRoads) ans = abs(sx - tx) + abs(sy - ty) if n == 0: return ans i = 0 while i < n: r = specialRoads[i] dse = abs(r[2] - r[0]) + abs(r[3] - r[1]) if r[4] > dse: r[4] = dse i += 1 INF = 10**30 d = [INF] * n i = 0 while i < n: r = specialRoads[i] d[i] = abs(sx - r[0]) + abs(sy - r[1]) + r[4] i += 1 k = 0 while k < n: changed = False c = 0 while c < n: dc = d[c] if dc != INF: rx2 = specialRoads[c][2] ry2 = specialRoads[c][3] tmp = dc + abs(tx - rx2) + abs(ty - ry2) if tmp < ans: ans = tmp nxt = 0 while nxt < n: sxn = specialRoads[nxt][0] syn = specialRoads[nxt][1] costn = specialRoads[nxt][4] w = abs(rx2 - sxn) + abs(ry2 - syn) + costn val = dc + w if val < d[nxt]: d[nxt] = val changed = True nxt += 1 c += 1 if not changed: break k += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) # input x = int(next(it)) y = int(next(it)) x2 = int(next(it)) y2 = int(next(it)) n = int(next(it)) edge = [] start = [] start.append(x) start.append(y) targe = [] targe.append(x2) targe.append(y2) i = 1 while i <= n: temp = [] x = int(next(it)) y = int(next(it)) z = int(next(it)) temp.append(x) temp.append(y) temp.append(z) x = int(next(it)) y = int(next(it)) temp.append(x) temp.append(y) edge.append(temp) i += 1 # solve solution = Solution() result = solution.solve(start, targe, edge) # output sys.stdout.write(str(result))","graph,search",medium 175,"# Problem Statement You are given a sequence of $n$ non-negative integers $a_1, a_2, \ldots, a_n$. Initially, all the elements of the sequence are unpainted. You can paint each number $\RED$ or $\BLUE$ (but not both), or **leave it unpainted**. For a color $c$, $\text{Count}(c)$ is the number of elements in the sequence painted with that color and $\text{Sum}(c)$ is the sum of the elements in the sequence painted with that color. For example, if the given sequence is $[2, 8, 6, 3, 1]$ and it is painted this way: $[\myblue{2}, 8, \myred{6}, \myblue{3}, 1]$ (where $6$ is painted red, $2$ and $3$ are painted blue, $1$ and $8$ are unpainted) then $\text{Sum}(\RED)=6$, $\text{Sum}(\BLUE)=2+3=5$, $\text{Count}(\RED)=1$, and $\text{Count}(\BLUE)=2$. Determine if it is possible to paint the sequence so that $\text{Sum}(\RED) > \text{Sum}(\BLUE)$ and $\text{Count}(\RED) < \text{Count}(\BLUE)$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: NO # Constraints: - $3 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): a.sort() i = 1 j = 0 sumi = a[0] sumj = 0 flag = 0 while i + j <= n: i += 1 sumi += a[i - 1] j += 1 sumj += a[n - j] if sumj > sumi and i + j <= n: flag = 1 break if flag: return ""YES"" else: return ""NO"" def solve2(self, n, a): a.sort() blue_sum = a[0] red_sum = 0 j = 1 max_j = (n - 1) // 2 while j <= max_j: blue_sum += a[j] red_sum += a[n - j] if red_sum > blue_sum: return ""YES"" j += 1 return ""NO"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,sort,two_pointers",hard 176,"# Problem Statement You have an array of integers $a$ of length $n$. You can apply the following operation to the given array: - Swap two elements $a_i$ and $a_j$ such that $i \neq j$, $a_i$ and $a_j$ are either **both** even or **both** odd. Determine whether it is possible to sort the array in non-decreasing order by performing the operation any number of times (possibly zero). For example, let $a$ = $[7, 10, 1, 3, 2]$. Then we can perform $3$ operations to sort the array: 1. Swap $a_3 = 1$ and $a_1 = 7$, since $1$ and $7$ are odd. We get $a$ = $[1, 10, 7, 3, 2]$; 2. Swap $a_2 = 10$ and $a_5 = 2$, since $10$ and $2$ are even. We get $a$ = $[1, 2, 7, 3, 10]$; 3. Swap $a_4 = 3$ and $a_3 = 7$, since $3$ and $7$ are odd. We get $a$ = $[1, 2, 3, 7, 10]$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - Return value: Returns ""YES"" or ""NO"", indicating whether the array can be sorted in non-decreasing order. # Example 1: - Input: n = 5 a = [6, 6, 4, 1, 6] - Output: ""NO"" # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 64], [4000, 2000, 400], [32000, 16000, 3200]]","import collections class Solution: def solve1(self, n, a): b = sorted(a) for i in range(n): if (a[i] % 2) != (b[i] % 2): return ""NO"" return ""YES"" def solve2(self, n, a): i = 0 last_set = False last = 0 while i < n: found = False m = 0 if not last_set: for v in a: if not found or v < m: m = v found = True last_set = True else: for v in a: if v > last and (not found or v < m): m = v found = True if not found: return ""NO"" cnt = 0 for v in a: if v == m: cnt += 1 p = m & 1 end = i + cnt while i < end: if (a[i] & 1) != p: return ""NO"" i += 1 last = m return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,two_pointers,sort",easy 177,"# Problem Statement There are $n$ families travelling to Pénjamo to witness Mexico's largest-ever ""walking a chicken on a leash"" marathon. The $i$-th family has $a_i$ family members. All families will travel using a single bus consisting of $r$ rows with $2$ seats each. A person is considered happy if: - Another family member is seated in the same row as them, or - They are sitting alone in their row (with an empty seat next to them). Determine the maximum number of happy people in an optimal seating arrangement. Note that **everyone** must be seated in the bus. It is guaranteed that all family members will fit on the bus. Formally, it is guaranteed that $\displaystyle\sum_{i=1}^{n}a_i \le 2r$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, r, a): pass # write your code here``` where: - return:the maximum number of happy people in an optimal seating arrangement. # Example 1: - Input: n = 3, r = 3, a = [2, 3, 1] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq r \leq 10^3$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, r, a): s = 0 odd = 0 for i in range(n): s += a[i] odd += a[i] % 2 ans = s - max(0, (s + odd) // 2 - r) * 2 return ans def solve2(self, n, r, a): s = 0 odd = 0 i = 0 while i < n: ai = a[i] s += ai odd += ai & 1 i += 1 rows_no_mix = (s + odd) // 2 d = rows_no_mix - r if d < 0: d = 0 return s - 2 * d ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) r = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, r, a) sys.stdout.write(str(result) + ""\n"")",math,easy 178,"Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. The answer is modulo 998244353. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 1 Output: 5 Example 2: Input: n = 2 Output: 15 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import sys class Solution: mod = 998244353 inv_24 = 291154603 def solve1(self, n): return (n + 1) * (n + 2) % self.mod * (n + 3) % self.mod * (n + 4) % self.mod * self.inv_24 % self.mod def solve2(self, n): x = (n + 1) % self.mod x = x * ((n + 2) % self.mod) % self.mod x = x * ((n + 3) % self.mod) % self.mod x = x * ((n + 4) % self.mod) % self.mod return x * self.inv_24 % self.mod","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","dp,math",hard 179,"# Problem Statement We define the humor value of a string `t` as the length of the longest palindromic string that occurs at least twice in it. Formally, a string `p` is humor with respect to `t` if and only if: 1) `p` is a palindrome, and 2) there exist at least two different indices `i ∈ [1, |t| − |p| + 1]` such that `t[i, i + |p| − 1] = p`. You are given a string `s` of length `n` consisting of lowercase Latin letters, and `q` queries. For each query `(l, r)`, compute the humor value of the substring `s[l, r]`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, q, s, queries): pass # write your code here``` where: - `n`: length of the string `s` - `q`: number of queries - `s`: the string - `queries`: array of pairs `(l, r)` (1-indexed) - return: an array `ans` of size `q`, where `ans[i]` is the humor value for query `i` # Example - Input: ``` 12 6 aaaabbbbaaaa 1 12 2 7 3 10 4 7 5 9 4 5 ``` - Output: ``` 4 2 3 2 3 0 ``` # Constraints - $1 \le n, q \le @data$ - `s` only contains lowercase Latin letters - $1 \le l \le r \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[5000, 2500, 1000], [40000, 20000, 8000], [320000, 160000, 64000]]","import sys class Solution: def solve1(self, n, q, s, queries): if n + 1000 > sys.getrecursionlimit(): sys.setrecursionlimit(n + 1000) K = 4 max_nodes = n + 2 head = [-1] * max_nodes to = [] nxt = [] ec = [] ff = [0] * max_nodes ff_ = [0] * max_nodes len_ = [0] * max_nodes child_head = [-1] * max_nodes child_to = [] child_nxt = [] ta = [0] * max_nodes tb = [0] * max_nodes uu = [0] * (n + 1) node_cnt = 0 def new_node(length_value): nonlocal node_cnt len_[node_cnt] = length_value idx = node_cnt node_cnt += 1 return idx def add_edge(u, c, v): eid = len(to) to.append(v) nxt.append(head[u]) ec.append(c) head[u] = eid def add_child(p, v): cid = len(child_to) child_to.append(v) child_nxt.append(child_head[p]) child_head[p] = cid def go(u, c): e = head[u] while e != -1: if ec[e] == c: return to[e] e = nxt[e] return 0 timer = 0 def dfs(u): nonlocal timer ta[u] = timer timer += 1 e = child_head[u] while e != -1: dfs(child_to[e]) e = child_nxt[e] tb[u] = timer def build_eertree(): new_node(0) new_node(-1) ff[0] = 1 ff_[0] = 1 add_child(1, 0) last = 0 s_ord = [ord(ch) - 97 for ch in s] def get_link(u, i): while i - 1 - len_[u] < 0 or s[i - 1 - len_[u]] != s[i]: u = ff[u] return u for i in range(n): c = s_ord[i] u = get_link(last, i) v = go(u, c) if v == 0: v_idx = new_node(len_[u] + 2) f_node = go(get_link(ff[u], i), c) ff[v_idx] = f_node if f_node == 0 or len_[v_idx] - len_[f_node] != len_[f_node] - len_[ff[f_node]]: ff_[v_idx] = f_node else: ff_[v_idx] = ff_[f_node] add_edge(u, c, v_idx) add_child(f_node, v_idx) v = v_idx uu[i + 1] = last = v dfs(1) build_eertree() eh = [[] for _ in range(n)] left_of = [0] * q ans = [0] * q for h in range(q): l, r = queries[h] l -= 1 r -= 1 left_of[h] = l if 0 <= r < n: eh[r].append(h) ft = [-1] * n def fen_update(i, x): while i < n: if x > ft[i]: ft[i] = x i |= i + 1 def fen_query(i): res = -1 while i >= 0: if ft[i] > res: res = ft[i] i = (i & (i + 1)) - 1 return res n_ = 1 while n_ < n + 2: n_ <<= 1 st1 = [-1] * (n_ * 2) st2 = [-1] * (n_ * 2) def st1_update(i, x): i += n_ if x > st1[i]: st1[i] = x i >>= 1 while i > 0: left = st1[i << 1] right = st1[i << 1 | 1] st1[i] = left if left >= right else right i >>= 1 def st1_query(l, r): if l > r: return -1 x = -1 l += n_ r += n_ while l <= r: if l & 1: if st1[l] > x: x = st1[l] l += 1 if not (r & 1): if st1[r] > x: x = st1[r] r -= 1 l >>= 1 r >>= 1 return x def st2_update(l, r, x): if l > r: return l += n_ r += n_ while l <= r: if l & 1: if x > st2[l]: st2[l] = x l += 1 if not (r & 1): if x > st2[r]: st2[r] = x r -= 1 l >>= 1 r >>= 1 def st2_query(i): x = -1 i += n_ while i > 0: if st2[i] > x: x = st2[i] i >>= 1 return x for j in range(n): u = uu[j + 1] if u != 0: i = st1_query(ta[u], tb[u] - 1) if i != -1: fen_update(n - 1 - (i - len_[u] + 1), len_[u]) v = u while v != 0: fen_update(n - 1 - (j - len_[v] + 1), len_[ff[v]]) w = ff_[v] d = len_[v] - len_[ff[v]] if w != 0: i = st1_query(ta[w], tb[w] - 1) if i != -1: fen_update(n - 1 - (i - len_[w] + 1), len_[w]) k = 1 while k <= K and len_[w] + d * k <= len_[v]: i = j - len_[w] - d * k + 1 fen_update(n - 1 - i, len_[w] + d * (k - 1)) k += 1 if len_[v] - len_[w] >= d * K: i = j - len_[w] - d * K + 1 st2_update(j - len_[v] + 2, i, j) v = w u = uu[j + 1] st1_update(ta[u], j) for h in eh[j]: i0 = left_of[h] x = fen_query(n - 1 - i0) j_ = st2_query(i0) if j_ != -1 and j_ >= i0: u2 = uu[j_ + 1] while j_ - len_[ff_[u2]] + 1 < i0: u2 = ff_[u2] d = len_[u2] - len_[ff[u2]] i_ = j_ - len_[u2] + 1 if d > 0: i_ += ((i0 - i_ + d - 1) // d) * d cand = j_ - i_ + 1 - d if cand > x: x = cand if i_ > i0: cand2 = j_ - i_ - (d - i_ + i0) * 2 + 1 if cand2 > x: x = cand2 ans[h] = x if x >= 0 else 0 return ans def solve2(self, n, q, s, queries): ans = [0] * q for idx in range(q): l, r = queries[idx] l -= 1 r -= 1 m = r - l + 1 found = False L = m while L >= 1 and not found: end_start = r - L + 1 i = l while i <= end_start and not found: a = i b = i + L - 1 pal = True aa = a bb = b while aa < bb: if s[aa] != s[bb]: pal = False break aa += 1 bb -= 1 if pal: j = i + 1 while j <= end_start and not found: match = True k_c = 0 while k_c < L: if s[i + k_c] != s[j + k_c]: match = False break k_c += 1 if match: ans[idx] = L found = True break j += 1 i += 1 if not found: L -= 1 if not found: ans[idx] = 0 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) q = int(next(it)) s = next(it).decode() queries = [] for i in range(q): l = int(next(it)) r = int(next(it)) queries.append((l, r)) solution = Solution() result = solution.solve(n, q, s, queries) out_lines = [] for x in result: out_lines.append(str(x)) sys.stdout.write(""\n"".join(out_lines))","string,data_structures",hard 180,"# Problem Statement Luca is in front of a row of $n$ trees. The $i$-th tree has $a_i$ fruit and height $h_i$. He wants to choose a contiguous subarray of the array $[h_l, h_{l+1}, \dots, h_r]$ such that for each $i$ ($l \leq i < r$), **$h_i$ is divisible$^{\dagger}$ by $h_{i+1}$**. He will collect all the fruit from each of the trees in the subarray (that is, he will collect $a_l + a_{l+1} + \dots + a_r$ fruits). However, if he collects more than $k$ fruits in total, he will get caught. What is the maximum length of a subarray Luca can choose so he doesn't get caught? $^{\dagger}$ $x$ is divisible by $y$ if the ratio $\frac{x}{y}$ is an integer. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a, h): pass # write your code here``` where: - `n` is the number of trees, `k` is the maximum number of fruits - `a` is the array of fruit numbers, `h` is the array of tree heights - Return the maximum length # Example 1: - Input: n = 5, k = 12 a = [3, 2, 4, 1, 8] h = [4, 4, 2, 4, 1] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], h[i] \leq 10^3$ - $1 \leq k \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, k, a, h): for i in range(1, n): a[i] += a[i - 1] ans = 0 j = 0 for i in range(n): if i > 0 and h[i - 1] % h[i] != 0: j = i current_sum_j_to_i = a[i] if j > 0: current_sum_j_to_i -= a[j - 1] while current_sum_j_to_i > k: j += 1 current_sum_j_to_i = a[i] if j > 0: current_sum_j_to_i -= a[j - 1] ans = max(ans, i - j + 1) return ans def solve2(self, n, k, a, h): ans = 0 for l in range(n): s = 0 for r in range(l, n): if r > l and h[r - 1] % h[r] != 0: break s += a[r] if s > k: break length = r - l + 1 if length > ans: ans = length return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n h = [0] * n for i in range(n): a[i] = int(next(it)) for i in range(n): h[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a, h) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary,math,dp",medium 181,"You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed. solution main function ```python class Solution: def solve(self, arr): pass # write your code here``` Example 1: Input: arr = [3,3,3,3,5,5,5,2,2,7] Output: 2 Example 2: Input: arr = [7,7,7,7,7,7] Output: 1 Constraints: 1 <= arr.length <= @data arr.length is even. 1 <= arr[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math import heapq import collections class Solution: def solve1(self, arr): arr.sort() if not arr: return 0 arr_freq = [1] cir_freq = 0 for i in range(len(arr) - 1): if arr[i] != arr[i + 1]: arr_freq.append(1) cir_freq += 1 else: arr_freq[cir_freq] += 1 arr_freq.sort() res = 0 res_size = len(arr) for i in range(len(arr_freq) - 1, -1, -1): if res_size > len(arr) / 2: res += 1 res_size -= arr_freq[i] else: break return res def solve2(self, arr): n = len(arr) if n == 0: return 0 arr.sort() write = 0 i = 0 while i < n: j = i + 1 ai = arr[i] while j < n and arr[j] == ai: j += 1 arr[write] = j - i write += 1 i = j k = write target = n // 2 remaining = target res = 0 while remaining > 0: imax = 0 maxv = arr[0] if k > 0 else 0 for idx in range(1, k): if arr[idx] > maxv: maxv = arr[idx] imax = idx remaining -= maxv arr[imax] = 0 res += 1 return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) arr = [] for i in range(1, n + 1): x = int(next(it)) arr.append(x) solution = Solution() result = solution.solve(arr) sys.stdout.write(str(result))","greedy,sort,data_structures",medium 182,"There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: encoded = [3,1] Output: [1,2,3] Example 2: Input: encoded = [6,5,4,6] Output: [2,4,1,5,3] Constraints: 3 <= n < @data n is odd. encoded.length == n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math import collections import heapq from typing import List, Optional class Solution: def solve(self, encoded: List[int]) -> List[int]: x = 0 n = len(encoded) + 1 for i in range(1, n + 1): x ^= i for i in range(1, len(encoded), 2): x ^= encoded[i] ans = [0] * n ans[0] = x for i in range(1, n): ans[i] = ans[i-1] ^ encoded[i-1] return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) out = [] for it2 in result: out.append(str(it2)) sys.stdout.write("" "".join(out))",other,medium 183,"# Problem Statement We define the weight of an array $b$ consisting of $m$ non-negative integers as the number of indices $i$ ($1 \le i \le m$) satisfying $b_i > \mathrm{mex}(b)$. Here, $\mathrm{mex}(b)$ denotes the minimum excluded (MEX) of the integers in $b$. You are given an array $a$ consisting of $n$ non-negative integers. For its subarray $[a_l, a_{l+1}, \dots, a_r]$, denote the weight of the subarray as $w(l, r)$. For every $1 \le i \le n$, find the maximum weight over all subarrays of $a$ ending at index $i$, i.e., compute $\max_{1 \le l \le i} w(l, i)$ for each $i$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: the length of array `a` - `a`: an array of non-negative integers with `0 <= a[i] <= n` - return: an array of length `n`, where the i-th value is the maximum weight over all subarrays of `a` ending at index `i` (1-indexed in the statement, 0-indexed in implementation). # Example: - Input: `n = 5` `a = [2, 0, 3, 0, 1]` - Output: `[1, 1, 2, 2, 1]` # Constraints: - $1 \le n \le @data$ - $0 \le a[i] \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",4000,"[[1250, 750, 375], [10000, 6000, 3000], [80000, 48000, 24000]]","class Solution: def solve1(self, n, a): class SegTree: def __init__(self, N): self.N = N size = 4 * (N + 1) + 5 self.maxv = [0] * size self.tag = [0] * size def apply(self, p, v): self.maxv[p] += v self.tag[p] += v def push(self, p): if self.tag[p] != 0: t = self.tag[p] self.apply(p << 1, t) self.apply(p << 1 | 1, t) self.tag[p] = 0 def pull(self, p): left = p << 1 right = left | 1 if self.maxv[left] >= self.maxv[right]: self.maxv[p] = self.maxv[left] else: self.maxv[p] = self.maxv[right] def _add(self, p, l, r, ql, qr, v): if ql > qr: return if ql <= l and r <= qr: self.apply(p, v) return self.push(p) m = (l + r) >> 1 if ql <= m: self._add(p << 1, l, m, ql, qr, v) if qr > m: self._add(p << 1 | 1, m + 1, r, ql, qr, v) self.pull(p) def add(self, l, r, v): if l < 0: l = 0 if r > self.N: r = self.N if l > r: return self._add(1, 0, self.N, l, r, v) def _point_set(self, p, l, r, pos, v): if l == r: self.maxv[p] = v self.tag[p] = 0 return self.push(p) m = (l + r) >> 1 if pos <= m: self._point_set(p << 1, l, m, pos, v) else: self._point_set(p << 1 | 1, m + 1, r, pos, v) self.pull(p) def point_set(self, pos, v): if pos < 0 or pos > self.N: return self._point_set(1, 0, self.N, pos, v) def query_max(self): return self.maxv[1] st = SegTree(n) res = [0] * n for i in range(n): x = a[i] if x > 0: st.add(0, x - 1, 1) st.point_set(x, 0) res[i] = st.query_max() return res def solve2(self, n, a): res = [0] * n for i in range(n): best = 0 l = i mex = 0 while True: found = False for k in range(l, i + 1): if a[k] == mex: found = True break if not found: break mex += 1 cnt = 0 for k in range(l, i + 1): if a[k] > mex: cnt += 1 if cnt > best: best = cnt l -= 1 while l >= 0: if a[l] == mex: while True: found = False for k in range(l, i + 1): if a[k] == mex: found = True break if not found: break mex += 1 cnt = 0 for k in range(l, i + 1): if a[k] > mex: cnt += 1 if cnt > best: best = cnt l -= 1 res[i] = best return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) out_lines = [] for i in range(len(result)): out_lines.append(str(result[i])) sys.stdout.write("" "".join(out_lines))",data_structures,hard 184,"# Problem Statement You are given a binary array$^{\dagger}$ of length $n$. You are allowed to perform one operation on it **at most once**. In an operation, you can choose any element and flip it: turn a $0$ into a $1$ or vice-versa. What is the maximum number of inversions$^{\ddagger}$ the array can have after performing **at most one** operation? $^\dagger$ A binary array is an array that contains only zeroes and ones. $^\ddagger$ The number of inversions in an array is the number of pairs of indices $i,j$ such that $i a_j$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` Where: - `n` is an integer representing the length of the array. - `a` is a binary array of length $n$. - The function should return a 64-bit integer, representing the maximum number of inversions in the array after performing at most one operation. # Example 1: - Input: n = 4 a = [1, 0, 1, 0] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a_i \leq 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = 0 c0 = 0 c1 = 0 x0 = -1 x1 = -1 for i in range(n): if a[i] == 0: c0 += 1 ans += c1 if x0 == -1: x0 = i else: c1 += 1 x1 = i res = ans if x0 != -1: ans = max(ans, res + c0 - 1 - x0) if x1 != -1: ans = max(ans, res + c1 - 1 - (n - 1 - x1)) return ans def solve2(self, n, a): inv = 0 ones_seen = 0 total_zeros = 0 for i in range(n): if a[i] == 0: inv += ones_seen total_zeros += 1 else: ones_seen += 1 max_inv = inv ones_seen = 0 zeros_seen = 0 for i in range(n): if a[i] == 0: zeros_after = total_zeros - zeros_seen - 1 delta = zeros_after - ones_seen if inv + delta > max_inv: max_inv = inv + delta zeros_seen += 1 else: zeros_after = total_zeros - zeros_seen delta = ones_seen - zeros_after if inv + delta > max_inv: max_inv = inv + delta ones_seen += 1 return max_inv ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,greedy,math",hard 185,"Given two positive integers n and k, the binary string Sn is formed as follows: S1 = ""0"" Si = Si - 1 + ""1"" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example, the first four strings in the above sequence are: S1 = ""0"" S2 = ""011"" S3 = ""0111001"" S4 = ""011100110110001"" Return the kth bit in Sn. It is guaranteed that k is valid for the given n. solution main function ```python class Solution: def solve(self, n, k): pass # write your code here``` Example 1: Input: n = 3, k = 1 Output: ""0"" Example 2: Input: n = 4, k = 11 Output: ""1"" Constraints: 1 <= n <= @data 1 <= k <= 2^n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 15, 20]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve(self, n, k): positionInSection = k & -k isInInvertedPart = (((k // positionInSection) >> 1) & 1) == 1 originalBitIsOne = (k & 1) == 0 if isInInvertedPart: return '0' if originalBitIsOne else '1' else: return '1' if originalBitIsOne else '0' ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, k) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,hard 186,"# Problem Statement Karel is a salesman in a car dealership. The dealership has $n$ different models of cars. There are $a_i$ cars of the $i$-th model. Karel is an excellent salesperson and can convince customers to buy up to $x$ cars (of Karel's choice), as long as the cars are from different models. Determine the minimum number of customers Karel has to bring in to sell all the cars. The main function of the solution is defined as: ```python class Solution: def solve(self, n, x, a): pass # write your code here``` where: - return: the minimum possible number of customers needed to sell all the cars. # Example 1: - Input: n = 3, x = 2, a = [3, 1, 2] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x \leq 10$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, x, a): sum_val = 0 mx = 0 for i in range(n): sum_val += a[i] mx = max(mx, a[i]) ans = max((sum_val + x - 1) // x, mx) return ans def solve2(self, n, x, a): total = 0 for i in range(n): total += a[i] ans = 0 while total > 0: take = x for i in range(n): if take == 0: break if a[i] > 0: a[i] -= 1 total -= 1 take -= 1 ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) x = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, x, a) sys.stdout.write(str(result) + ""\n"")","search,math",hard 187,"# Problem Statement You are given a string $s$ of length $n > 1$, consisting of digits from $0$ to $9$. You must insert exactly $n - 2$ symbols $+$ (addition) or $\times$ (multiplication) into this string to form a valid arithmetic expression. In this problem, the symbols cannot be placed before the first or after the last character of the string $s$, and two symbols cannot be written consecutively. Also, note that the order of the digits in the string cannot be changed. Let's consider $s = 987009$: - From this string, the following arithmetic expressions can be obtained: $9 \times 8 + 70 \times 0 + 9 = 81$, $98 \times 7 \times 0 + 0 \times 9 = 0$, $9 + 8 + 7 + 0 + 09 = 9 + 8 + 7 + 0 + 9 = 33$. Note that the number $09$ is considered valid and is simply transformed into $9$. - From this string, the following arithmetic expressions cannot be obtained: $+9 \times 8 \times 70 + 09$ (symbols should only be placed between digits), $98 \times 70 + 0 + 9$ (since there are $6$ digits, there must be exactly $4$ symbols). The result of the arithmetic expression is calculated according to the rules of mathematics — first all multiplication operations are performed, then addition. You need to find the minimum result that can be obtained by inserting exactly $n - 2$ addition or multiplication symbols into the given string $s$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return the minimum result of the arithmetic expression that can be obtained by inserting exactly n−2 addition or multiplication symbols into the given string. # Example 1: - Input: n = 2 s = ""10"" - Output: 10 # Constraints: - $2 \leq n \leq @data$ - $s[i] \in [0, 9]$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): cnt = [0] * 2 sum_val = 0 for c in s: digit = int(c) sum_val += digit if digit <= 1: cnt[digit] += 1 first_digit = int(s[0]) sum_val -= first_digit if first_digit <= 1: cnt[first_digit] -= 1 ans = 10**9 for i in range(n - 1): d_i1 = int(s[i + 1]) sum_val -= d_i1 if d_i1 <= 1: cnt[d_i1] -= 1 v = int(s[i:i+2]) sum_val += v if v <= 1: cnt[v] += 1 res = 0 if cnt[0] > 0: res = 0 else: res = max(1, sum_val - cnt[1]) ans = min(ans, res) sum_val -= v if v <= 1: cnt[v] -= 1 d_i = int(s[i]) sum_val += d_i if d_i <= 1: cnt[d_i] += 1 return ans def solve2(self, n, s): op_slots = n - 2 best = None if n == 2: return int(s[0:2]) for merge in range(n - 1): vmerge = int(s[merge:merge + 2]) for mask in range(1 << op_slots): if merge == 0: cur = vmerge else: cur = ord(s[0]) - 48 total = 0 for j in range(op_slots): p = j + 1 if p < merge: nxt = ord(s[p]) - 48 elif p == merge: nxt = vmerge else: nxt = ord(s[p + 1]) - 48 if (mask >> j) & 1: cur *= nxt else: total += cur cur = nxt total += cur if best is None or total < best: best = total return best ","import sys data = sys.stdin.read().split() idx = 0 n = int(data[idx]) idx += 1 s = data[idx] idx += 1 solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")",dp,hard 188,"The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: students = [1,1,0,0], sandwiches = [0,1,0,1] Output: 0 Example 2: Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] Output: 3 Constraints: 1 <= students.length, sandwiches.length <= @data students.length == sandwiches.length sandwiches[i] is 0 or 1. students[i] is 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections from typing import List class Solution: def solve1(self, students: List[int], sandwiches: List[int]) -> int: circleStudentCount = 0 squareStudentCount = 0 for student in students: if student == 0: circleStudentCount += 1 else: squareStudentCount += 1 for sandwich in sandwiches: if sandwich == 0 and circleStudentCount == 0: return squareStudentCount if sandwich == 1 and squareStudentCount == 0: return circleStudentCount if sandwich == 0: circleStudentCount -= 1 else: squareStudentCount -= 1 return 0 def solve2(self, students: List[int], sandwiches: List[int]) -> int: n = len(students) m = n head = 0 s = 0 fail = 0 while s < n and m > 0: if students[head] == sandwiches[s]: head = (head + 1) % n m -= 1 s += 1 fail = 0 else: x = students[head] k = 1 while k < m: prev = (head + k - 1) % n cur = (head + k) % n students[prev] = students[cur] k += 1 end_pos = (head + m - 1) % n students[end_pos] = x fail += 1 if fail == m: break return m","import sys data = sys.stdin.read().strip().split() it = iter(data) a = [] b = [] n = int(next(it)) for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, n + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result))",data_structures,easy 189,"Given an undirected graph with n vertices (numbered 1 to n) and m edges, find the minimum number of strokes needed to draw all the edges in the graph. The `edges` array represents the edges in the graph, where `edges[i] = [a, b]` indicates that there is an undirected edge between node `a` and node `b`. solution main function ```python class Solution: def solve(self, n, edge): pass # write your code here``` Example 1: Input: n = 5, edges = [[2,3],[2,4],[2,5],[3,4],[4,5]] Output: 1 Constraints: 2 <= n <= @data edges.size <=5*@data edges[i].size ==2 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, n, edges): cnt = [0] * (n + 10) for it in edges: for i in it: cnt[i] += 1 ans = 0 for i in range(1, n + 1): if cnt[i] & 1: ans += 1 if ans == 0: return 0 return ans // 2 def solve2(self, n, edges): odd = 0 for v in range(1, n + 1): c = 0 for a, b in edges: if a == v: c += 1 if b == v: c += 1 if c & 1: odd += 1 if odd == 0: return 0 return odd // 2 ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) edge = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) edge.append(temp) solution = Solution() result = solution.solve(n, edge) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()",graph,easy 190,"# Problem Statement: You had $n$ positive integers $a_1, a_2, \dots, a_n$ arranged in a circle. For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, ..., $a_{n - 1}$ and $a_n$, and $a_n$ and $a_1$), you wrote down: are the numbers in the pair equal or not. Unfortunately, you've lost a piece of paper with the array $a$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $a$ which is consistent with information you have about equality or non-equality of corresponding pairs? The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` Where: - `n` is an integer representing the number of elements in the array. - `s` is a string consisting of the characters 'N' and 'E', where: - 'E' indicates the two adjacent numbers are equal. - 'N' indicates the two adjacent numbers are not equal. - The return value is ""YES"" if there exists an array $a$ consistent with the information you have, otherwise, it is ""NO"". # Example 1: - Input: n = 3 s = ""EEE"" - Output: YES # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve(self, n, s): cnt = 0 for x in s: if x == 'N': cnt += 1 if cnt == 1: return ""NO"" else: return ""YES""","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,data_structures",medium 191,"# Problem Statement You are given an $n \times m$ grid $a$ of non-negative integers. The value $a_{i,j}$ represents the depth of water at the $i$-th row and $j$-th column. A lake is a set of cells such that: - each cell in the set has $a_{i,j} > 0$, and - there exists a path between any pair of cells in the lake by going up, down, left, or right a number of times and without stepping on a cell with $a_{i,j} = 0$. The volume of a lake is the sum of depths of all the cells in the lake. Find the largest volume of a lake in the grid. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, a): pass # write your code here``` where: - return value is the largest volume of a lake # Example 1: - Input: n = 3, m = 3 a = [ [1, 2, 0], [3, 4, 0], [0, 0, 5] ] - Output: 10 # Constraints: - $1 \leq n * m \leq @data$ - $0 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[1125, 1000, 750], [9000, 8000, 6000], [72000, 64000, 48000]]","import collections class Solution: def solve1(self, n, m, a): dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] ans = 0 vis = [[False for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if not vis[i][j] and a[i][j] > 0: res = 0 q = collections.deque([(i, j)]) vis[i][j] = True while q: x, y = q.popleft() res += a[x][y] for k in range(4): nx = x + dx[k] ny = y + dy[k] if 0 <= nx < n and 0 <= ny < m and a[nx][ny] > 0 and not vis[nx][ny]: q.append((nx, ny)) vis[nx][ny] = True ans = max(ans, res) return ans def solve2(self, n, m, a): dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] ans = 0 for i in range(n): for j in range(m): if a[i][j] > 0: res = 0 x, y = i, j parent_dir = 4 while True: if a[x][y] > 0: res += a[x][y] a[x][y] = -(parent_dir + 1) moved = False for d in range(4): nx = x + dx[d] ny = y + dy[d] if 0 <= nx < n and 0 <= ny < m and a[nx][ny] > 0: parent_dir = d ^ 1 x, y = nx, ny moved = True break if moved: continue pd = -a[x][y] - 1 if pd == 4: break x += dx[pd] y += dy[pd] if res > ans: ans = res return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [[0] * m for _ in range(n)] for i in range(n): for j in range(m): a[i][j] = int(next(it)) solution = Solution() result = solution.solve(n, m, a) sys.stdout.write(str(result) + ""\n"")","graph,search,data_structures",easy 192,"# Problem Statement You are given a string $s$, consisting of lowercase Latin letters and/or question marks. A tandem repeat is a string of an even length such that its first half is equal to its second half. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Your goal is to replace each question mark with some lowercase Latin letter in such a way that the length of the longest substring that is a tandem repeat is maximum possible. The main function of the solution is defined as: ```python class Solution: def solve(self, s): pass # write your code here``` where: - the return value is the length of the longest substring that is a tandem repeat # Example 1: - Input: s = ""?????"" - Output: 4 # Constraints: - $1 \leq s.length \leq @data$ - s consists of lowercase Latin letters or question marks - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 5000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s): n = len(s) ans = 0 for length in range(n // 2, 0, -1): t = 0 for i in range(n - length): if s[i] == s[i + length] or s[i] == '?' or s[i + length] == '?': t += 1 if t == length: ans = max(ans, length) break else: t = 0 return ans * 2 def solve2(self, s): n = len(s) best = 0 for L in range(n // 2, 0, -1): i = 0 limit = n - 2 * L found = False while i <= limit: j = 0 ok = True while j < L: a = s[i + j] b = s[i + L + j] if a != '?' and b != '?' and a != b: ok = False break j += 1 if ok: best = 2 * L found = True break i += 1 if found: break return best ","import sys def main(): s = sys.stdin.readline().strip() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","dp,two_pointers,string",medium 193,"# Problem Statement You are given a number in binary representation consisting of exactly $n$ bits, possibly, with leading zeroes. For example, for $n = 5$ the number $6$ will be given as $00110$, and for $n = 4$ the number $9$ will be given as $1001$. Let's fix some integer $i$ such that $1 \le i \le n$. In one operation you can swap any two adjacent bits in the binary representation. Your goal is to find the smallest number of operations you are required to perform to make the number divisible by $2^i$, or say that it is impossible. Please note that for each $1 \le i \le n$ you are solving the problem independently. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - `n` is the number of bits in the binary representation - `s` is the binary representation of the number - Return an array, where the $i$-th element of the array represents the smallest number of operations required to make the number divisible by $2^i$, and the answer is large, use a $64$-bit integer type. # Example 1: - Input: n = 2 s = ""01"" - Output: [1, -1] # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 160], [4000, 2000, 1280], [32000, 16000, 10240]]","class Solution: def solve1(self, n, s): ans = 0 res = [] l = n r = n for i in range(1, n + 1): if ans != -1: if l > n - i and s[n - i] == '0': l -= 1 else: while l > 0 and s[l - 1] == '1': l -= 1 if l == 0: ans = -1 else: ans += r - l l -= 1 r -= 1 res.append(ans) return res def solve2(self, n, s): res = [-1] * n ones = 0 acc = 0 k = 0 for idx in range(n - 1, -1, -1): if s[idx] == '1': ones += 1 else: k += 1 acc += ones res[k - 1] = acc return res ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) out = [] for x in result: out.append(str(x)) sys.stdout.write("" "".join(out)) sys.stdout.write(""\n"")","two_pointers,binary,greedy,math",hard 194,"# Problem Statement We call a sequence `b1, b2, …, bk` good if there exists a coloring of each index `i` in red or blue such that for every pair of indices `i < j` with `bi > bj`, the colors assigned to `i` and `j` are different. Given a sequence `a1, a2, …, an`, compute the number of good subsequences of the sequence, including the empty subsequence. Since the answer can be very large, output it modulo `1e9+7`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: length of the sequence - `a`: the sequence values, `1 <= a[i] <= n` - return: the number of good subsequences modulo `1e9+7` # Example 1: - Input: ``` n = 4 a = [4, 2, 3, 1] ``` - Output: ``` 13 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[200, 1000, 2000]",4000,"[[10240, 7500, 5000], [81920, 60000, 40000], [655360, 480000, 320000]]","import sys class Solution: def solve1(self, n, a): MOD = 1000000007 b = [0] * (n + 1) for i in range(n): b[i + 1] = a[i] a_perm = [0] * (n + 1) for i in range(1, n + 1): v = 1 for j in range(1, i): if b[j] <= b[i]: v += 1 for j in range(i + 1, n + 1): if b[j] < b[i]: v += 1 a_perm[i] = v size = n + 5 bit_lin = [[0] * size for _ in range(size)] bit_col = [[0] * size for _ in range(size)] def update_lin(lin, pos, val): pos += 1 i = pos while i <= n + 1: bit_lin[lin][i] += val if bit_lin[lin][i] >= MOD: bit_lin[lin][i] -= MOD i += i & -i def update_col(col, pos, val): pos += 1 i = pos while i <= n + 1: bit_col[col][i] += val if bit_col[col][i] >= MOD: bit_col[col][i] -= MOD i += i & -i def query_lin(lin, pos): pos += 1 rr = 0 i = pos while i > 0: rr += bit_lin[lin][i] if rr >= MOD: rr -= MOD i -= i & -i return rr def query_col(col, pos): pos += 1 rr = 0 i = pos while i > 0: rr += bit_col[col][i] if rr >= MOD: rr -= MOD i -= i & -i return rr update_lin(0, 0, 1) update_col(0, 0, 1) for i in range(1, n + 1): x = a_perm[i] buffs = [] for j in range(x + 1, n + 1): buff = query_lin(j, x - 1) if buff: buffs.append((buff, j, x)) for q in range(x): buff = query_col(q, x - 1) if buff: buffs.append((buff, x, q)) for val, lin, col in buffs: update_lin(lin, col, val) update_col(col, lin, val) ans = 0 for lin in range(n + 1): res = query_lin(lin, n) ans += res if ans >= MOD: ans -= MOD return ans def solve2(self, n, a): MOD = 1000000007 total = 0 for mask in range(1 << n): first = 10**18 second = 10**18 bad = False for i in range(n): if (mask >> i) & 1: x = -a[i] if x <= first: first = x elif x <= second: second = x else: bad = True break if not bad: total += 1 if total >= MOD: total -= MOD return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,data_structures",hard 195,"Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest. Reduce nums[i] to nextLargest. Return the number of operations to make all elements in nums equal. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [5,1,3] Output: 3 Example 2: Input: nums = [1,1,1] Output: 0 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections from typing import List class Solution: def solve1(self, nums: List[int]) -> int: nums.sort(reverse=True) operations = 0 for i in range(1, len(nums)): if nums[i] != nums[i - 1]: operations += i return operations def solve2(self, nums: List[int]) -> int: n = len(nums) if n <= 1: return 0 operations = 0 while True: largest = nums[0] idx = 0 for i in range(1, n): v = nums[i] if v > largest: largest = v idx = i found = False next_largest = 0 for i in range(n): v = nums[i] if v < largest: if not found or v > next_largest: next_largest = v found = True if not found: break nums[idx] = next_largest operations += 1 return operations","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")",sort,medium 196,"Given a positive integer n, find the pivot integer x such that: The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively. Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 8 Output: 6 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): total_sum = (n * (n + 1)) // 2 pivot = int(math.sqrt(total_sum)) return pivot if pivot * pivot == total_sum else -1 def solve2(self, n): total = n * (n + 1) // 2 prefix = 0 for x in range(1, n + 1): left = prefix + x right = total - prefix if left == right: return x prefix += x return -1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")",math,easy 197,"Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 3 Output: 2 Example 2: Input: n = 6 Output: 4 Constraints: 0 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 1000000, 1000000000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, n): ans = n ans ^= ans >> 16 ans ^= ans >> 8 ans ^= ans >> 4 ans ^= ans >> 2 ans ^= ans >> 1 return ans def solve2(self, n): ans = 0 while n: ans ^= n n >>= 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")","dp,bit_manipulation",hard 198,"# Problem Statement You are given two strings $a$ and $b$ of equal length, consisting of only characters 0 and/or 1; both strings start with character 0 and end with character 1. You can perform the following operation any number of times (possibly zero): - choose one of the strings and two **equal** characters in it; then turn all characters between them into those characters. Formally, you choose one of these two strings (let the chosen string be $s$), then pick two integers $l$ and $r$ such that $1 \le l < r \le |s|$ and $s_l = s_r$, then replace every character $s_i$ such that $l < i < r$ with $s_l$. For example, if the chosen string is 010101, you can transform it into one of the following strings by applying one operation: - 010001 if you choose $l = 3$ and $r = 5$; - 010111 if you choose $l = 4$ and $r = 6$; You have to determine if it's possible to make the given strings equal by applying this operation any number of times. The main function of the solution is defined as: ```python class Solution: def solve(self, a, b): pass # write your code here``` where: - return value: ""YES"" or ""NO"" # Example 1: - Input: a = ""01010001"" b = ""01110101"" - Output: YES # Constraints: - $1 \leq a.length \leq @data$ - a.length == b.length - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math import collections import heapq class Solution: def solve1(self, a, b): n = len(a) for i in range(n - 1): if a[i] == '0' and b[i] == '0' and a[i + 1] == '1' and b[i + 1] == '1': return ""YES"" return ""NO"" def solve2(self, a, b): n = len(a) for i in range(n - 1): if a[i] == '0' and b[i] == '0' and a[i + 1] == '1' and b[i + 1] == '1': return ""YES"" return ""NO"" ","import sys data = sys.stdin.read().split() a = data[0] b = data[1] solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result) + ""\n"")","greedy,dp",hard 199,"# Problem Statement You are given an array of positive integers `a` of length `n` and a positive integer `k`. You will play the following game: - At the start of the game, choose an odd integer `x` (`1 ≤ x ≤ n`). - Then do the following at most `k` times (possibly zero times): - Select a subsequence of `a` of length `x`, then replace every value in the subsequence with the median of that subsequence. Note that the integer `x` you choose cannot change between operations. Determine the maximum possible value of the sum of `a` after playing the game. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a): pass # write your code here``` where: - `n`: the length of the array - `k`: the maximum number of operations - `a`: the array of positive integers - return: the maximum achievable sum of the array after the game # Example 1: - Input: `n = 5` `k = 1` `a = [1, 1, 5, 5, 5]` - Output: `25` # Constraints: - $1 \leq n \leq @data$ - $1 \leq k \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 125, 75], [4000, 1000, 600], [32000, 8000, 4800]]","import math class Solution: def solve1(self, n, k, a): a.sort() pre = [0] * (n + 1) for i in range(n): pre[i + 1] = pre[i] + a[i] def get_sum(l, r): if l > r: return 0 return pre[r + 1] - pre[l] base = pre[n] ans = base for i in range(n): hi = min(i, n - 1 - i) if hi <= 0: continue def calc(y): lcnt = min(i, y * k) rcnt = min(n - 1 - i, y) return a[i] * (lcnt + rcnt) - get_sum(0, lcnt - 1) - get_sum(i + 1, i + rcnt) lo = 1 hiY = hi while lo < hiY: mid = (lo + hiY) // 2 if calc(mid) < calc(mid + 1): lo = mid + 1 else: hiY = mid ans = max(ans, base + calc(lo)) return ans def solve2(self, n, k, a): a.sort() base = 0 for v in a: base += v ans = base for i in range(n): hi = i t = n - 1 - i if hi > t: hi = t if hi <= 0: continue s_left = 0 cnt_left = 0 s_right = 0 cnt_right = 0 y = 1 while y <= hi: target_left = y * k if target_left > i: target_left = i target_right = y if target_right > (n - 1 - i): target_right = n - 1 - i while cnt_left < target_left: s_left += a[cnt_left] cnt_left += 1 while cnt_right < target_right: s_right += a[i + 1 + cnt_right] cnt_right += 1 inc = a[i] * (target_left + target_right) - s_left - s_right val = base + inc if val > ans: ans = val y += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a) sys.stdout.write(str(result) + ""\n"")","sort,binary",hard 200,"You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once. You are given an array processorTime representing the time each processor becomes available and an array tasks representing how long each task takes to complete. Return the minimum time needed to complete all tasks. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5] Output: 16 Example 2: Input: processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3] Output: 23 Constraints: 1 <= n == processorTime.length <= @data 0 <= processorTime[i] <= 10^9 1 <= tasks[i] <= 10^9 tasks.length == 4 * n Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","class Solution: def solve1(self, t, v): n = len(v) t.sort() v.sort() j = n - 1 m = len(t) ans = 0 for i in range(m): c = 0 while c < 4: ans = max(ans, t[i] + v[j]) c += 1 j -= 1 return ans def solve2(self, t, v): t.sort() v.sort() j = len(v) - 1 ans = 0 for i in range(len(t)): x = t[i] + v[j] if x > ans: ans = x j -= 4 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, 4 * n + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result))","greedy,sort",medium 201,"# Problem Statement You work at Berflix, the largest streaming service in Berland. The service has n users. For each user i we know two threshold preferences: the required action level ai and the required drama level di. Consider a fixed movie described by action ac and drama dr. If both movie parameters meet a user's thresholds, the user immediately watches the movie. Otherwise, the user hesitates, but may still watch later if the movie becomes popular enough. Let p be the number of users who have already watched the movie (initially p = 0). Define for user i the required popularity $p_i = \max(a_i - ac, 0) + \max(d_i - dr, 0).$ As long as there exists a user who hasn't watched yet and satisfies $p_i \le p$, that user will immediately watch the movie, increasing p by one. This process continues until no more users can join. Your task is to compute the final number of viewers. There are m online updates. Each update changes a single user k to new preferences (na, nd). After each update, recompute and output the final number of viewers. The main function of the solution is defined as: ```python class Solution: def solve(self, ac, dr, n, a, d, m, ops): pass # write your code here``` where: - `ac, dr`: movie parameters, - `n`: number of users, - `a, d`: arrays of length n with user thresholds, - `m`: number of updates, - `ops[j] = {k, na, nd}`: update user k (1-indexed) to (na, nd), - return: an array of length m, answers after each update. # Example Input: ``` 20 25 4 1 22 1 30 1 22 50 30 5 3 1 25 2 23 22 4 10 27 1 21 21 3 20 26 ``` Output: ``` 3 2 4 4 0 ``` # Constraints - $1 \le ac,dr \le 10^6$ - $1 \le n \le @data$ - $1 \le a_i,d_i \le 10^6$ - $1 \le m \le @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[1000, 500, 250], [8000, 4000, 2000], [64000, 32000, 16000]]","import math class Solution: def solve1(self, ac, dr, n, a, d, m, ops): class SegTree: def __init__(self, size): self.N = size self.P = 1 while self.P < self.N: self.P <<= 1 self.add = [0] * (2 * self.P) self.mn = [0] * (2 * self.P) self._build(1, 0, self.P) def _build(self, p, l, r): if l + 1 == r: if l < self.N: self.mn[p] = -l else: self.mn[p] = float('inf') return m = (l + r) >> 1 self._build(p << 1, l, m) self._build(p << 1 | 1, m, r) self.mn[p] = min(self.mn[p << 1], self.mn[p << 1 | 1]) def _apply(self, p, v): self.add[p] += v self.mn[p] += v def _push(self, p): if self.add[p] != 0: self._apply(p << 1, self.add[p]) self._apply(p << 1 | 1, self.add[p]) self.add[p] = 0 def _range_add(self, p, l, r, L, R, v): if L >= R: return if L <= l and r <= R: self._apply(p, v) return self._push(p) m = (l + r) >> 1 if L < m: self._range_add(p << 1, l, m, L, R, v) if R > m: self._range_add(p << 1 | 1, m, r, L, R, v) self.mn[p] = min(self.mn[p << 1], self.mn[p << 1 | 1]) def range_add(self, L, R, v): if L < 0: L = 0 if R > self.N: R = self.N if L >= R: return self._range_add(1, 0, self.P, L, R, v) def _first_negative(self, p, l, r): if l + 1 == r: return l self._push(p) m = (l + r) >> 1 if self.mn[p << 1] < 0: return self._first_negative(p << 1, l, m) return self._first_negative(p << 1 | 1, m, r) def first_negative(self): return self._first_negative(1, 0, self.P) def calcP(ai, di): x = max(ai - ac, 0) y = max(di - dr, 0) s = x + y if s > n: s = n return int(s) st = SegTree(n + 2) for i in range(n): p = calcP(a[i], d[i]) st.range_add(p + 1, n + 2, 1) ans = [] for op in ops: k, na, nd = op k -= 1 oldp = calcP(a[k], d[k]) st.range_add(oldp + 1, n + 2, -1) a[k] = na d[k] = nd newp = calcP(a[k], d[k]) st.range_add(newp + 1, n + 2, 1) firstNeg = st.first_negative() ans.append(firstNeg - 1) return ans def solve2(self, ac, dr, n, a, d, m, ops): ans = [] for op in ops: k, na, nd = op k -= 1 a[k] = na d[k] = nd p = 0 while True: c = 0 for i in range(n): s = 0 x = a[i] - ac if x > 0: s += x y = d[i] - dr if y > 0: s += y if s <= p: c += 1 if c == p: break p = c if p == n: break ans.append(p) return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) ac = int(next(it)) dr = int(next(it)) n = int(next(it)) a = [0] * n d = [0] * n for i in range(n): a[i] = int(next(it)) for i in range(n): d[i] = int(next(it)) m = int(next(it)) ops = [] for i in range(m): k = int(next(it)) na = int(next(it)) nd = int(next(it)) ops.append([k, na, nd]) solution = Solution() res = solution.solve(ac, dr, n, a, d, m, ops) out_lines = [] for i in range(len(res)): out_lines.append(str(res[i]) + ""\n"") sys.stdout.write("""".join(out_lines))",data_structures,hard 202,"You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6. Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: rods = [1,2,3,6] Output: 6 Example 2: Input: rods = [1,2,3,4,5,6] Output: 10 Constraints: 1 <= rods.length <= @data 1 <= rods[i] <= 1000 sum(rods[i]) <= 100*@data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[30, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, rods): s = sum(rods) dp = [-1] * (s + 1) dp[0] = 0 for rod in rods: dp_copy = dp[:] for i in range(s - rod + 1): if dp_copy[i] < 0: continue dp[i + rod] = max(dp[i + rod], dp_copy[i]) dp[abs(i - rod)] = max(dp[abs(i - rod)], dp_copy[i] + min(i, rod)) return dp[0] def solve2(self, rods): n = len(rods) total = 0 for v in rods: total += v pow3 = 1 for _ in range(n): pow3 *= 3 ans = 0 for code in range(pow3): temp = code sumL = 0 sumR = 0 pref = 0 for i in range(n): trit = temp % 3 if trit == 1: sumL += rods[i] elif trit == 2: sumR += rods[i] pref += rods[i] if abs(sumL - sumR) > total - pref: break temp //= 3 else: if sumL == sumR and sumL > ans: ans = sumL return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")",dp,hard 203,"# Problem Statement You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. More formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then: $$ sum_1 = \sum\limits_{1 \le i \le a}d_i, $$ $$ sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i, $$ $$ sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i. $$ The sum of an empty array is $0$. Your task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum possible value of sum1, considering that the condition sum1=sum3 must be met. # Example 1: - Input: n = 5 d = [1, 3, 1, 1, 4] - Output: 5 # Constraints: - $1 \leq n \leq @data$ - $1 \leq d[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections from typing import List class Solution: def solve1(self, n: int, d: List[int]) -> int: x = 0 y = n - 1 sumx = 0 sumy = 0 ans = 0 while x <= y: if sumx < sumy: sumx += d[x] x += 1 else: sumy += d[y] y -= 1 if sumx == sumy: ans = sumx return ans def solve2(self, n: int, d: List[int]) -> int: ans = 0 sum_prefix = 0 for i in range(0, n + 1): if i > 0: sum_prefix += d[i - 1] sum_suffix = 0 j = n - 1 while j >= i: sum_suffix += d[j] if sum_suffix == sum_prefix: if sum_prefix > ans: ans = sum_prefix break j -= 1 return ans","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","binary,data_structures,two_pointers",medium 204,"# Problem Statement One day, Vogons wanted to build a new hyperspace highway through a distant system with $n$ planets. The $i$-th planet is on the orbit $a_i$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed. Vogons have two machines to do that. - The first machine in one operation can destroy any planet at cost of $1$ Triganic Pu. - The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $c$ Triganic Pus. Vogons can use each machine as many times as they want. Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project? The main function of the solution is defined as: ```python class Solution: def solve(self, n, c, a): pass # write your code here``` where: - return: the minimum cost of destroying all planets. # Example 1: - Input: n = 10, c = 1 a = [2, 1, 4, 5, 2, 4, 5, 5, 1, 2] - Output: 4 # Constraints: - $1 \leq n\leq @data$ - $1 \leq c\leq 10$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, c, a): a.sort() ans = 0 i = 0 while i < len(a): cnt = 1 while i + 1 < len(a) and a[i] == a[i + 1]: i += 1 cnt += 1 ans += min(cnt, c) i += 1 return ans def solve2(self, n, c, a): ans = 0 for i in range(n): if a[i] == 0: continue x = a[i] cnt = 0 for j in range(i, n): if a[j] == x: cnt += 1 a[j] = 0 if cnt < c: ans += cnt else: ans += c return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) c = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, c, a) sys.stdout.write(str(result) + ""\n"")","sort,greedy",medium 205,"# Problem Statement On the board Ivy wrote down all integers from $l$ to $r$, inclusive. In an operation, she does the following: - pick two numbers $x$ and $y$ on the board, erase them, and in their place write the numbers $3x$ and $\lfloor \frac{y}{3} \rfloor$. (Here $\lfloor \bullet \rfloor$ denotes rounding down to the nearest integer). What is the minimum number of operations Ivy needs to make all numbers on the board equal $0$? We have a proof that this is always possible. The main function of the solution is defined as: ```python class Solution: def solve(self, l, r): pass # write your code here``` where: the minimum number of operations needed to make all numbers on the board equal 0. - return: # Example 1: - Input: l = 1, r = 3 - Output: 5 # Constraints: - $1 \leq l \leq r \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 1000000, 100000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, l, r): ans = 0 mn = -1 x = 1 t = 1 while x <= r: if l >= x: mn = t ans += max(0, min(r, 3 * x - 1) - max(l, x) + 1) * t if x > r // 3: break x *= 3 t += 1 ans += mn return ans def solve2(self, l, r): total = 0 min_len = 10**18 n = l while n <= r: x = n t = 0 while x: x //= 3 t += 1 total += t if t < min_len: min_len = t n += 1 return total + min_len ","import sys data = sys.stdin.read().strip().split() it = iter(data) l = int(next(it)) r = int(next(it)) solution = Solution() result = solution.solve(l, r) sys.stdout.write(str(result) + ""\n"")","sort,two_pointers",hard 206,"# Problem Statement You are given a full binary tree of `n` nodes (rooted at node `1`). For each node `u (1 ≤ u ≤ n)`, define a function `f_u : R^+ -> R^+`: - If `u` is a leaf, then `f_u(x) = x`; - Otherwise, let its left and right children be `l_u` and `r_u`, then `f_u(x) = (f_{l_u}(x))^{f_{r_u}(x)}`. For two nodes `u` and `v`, define the strict order `u ≺ v` as: - If `f_u(x) < f_v(x)` as `x → ∞`, then `u ≺ v`; - If `f_u(x) = f_v(x)` as `x → ∞`, then break ties by index: `u < v` implies `u ≺ v`. It can be shown that for any two distinct nodes `u` and `v`, exactly one of `u ≺ v` or `v ≺ u` holds. You need to sort all nodes by `≺` and output a permutation `p` of length `n` such that for every `1 ≤ i < n`, `p_i ≺ p_{i+1}`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, L, R): pass # write your code here``` where: - `n`: number of nodes (odd); - `L[i], R[i]`: the left and right child of node `i`, `0` if `i` is a leaf; - return: the nodes in increasing order by `≺`. # Example 1 - Input: ``` n = 3 L,R: 2 3 0 0 0 0 ``` - Output: ``` 2 3 1 ``` # Constraints - $1 \le n \le @data$ (and `n` is odd) - The input is guaranteed to be a full binary tree rooted at `1` - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[10000, 5000, 2500], [80000, 40000, 20000], [640000, 320000, 160000]]","import sys import random import heapq from functools import cmp_to_key class _CmpNode: def __init__(self, u, sol_instance): self.u = u self.sol = sol_instance def __lt__(self, other): h_self = self.sol.h[self.u] h_other = self.sol.h[other.u] if h_self == h_other: return self.u < other.u return self.sol._findDiff(self.sol.rt[other.u], self.sol.rt[self.u], 1, self.sol.N) class Solution: def _add(self, p_ref, pre, Lb, Rb, k, x): self.t.append(list(self.t[pre])) self.cnt += 1 p = self.cnt p_ref[0] = p self.t[p][3] = (self.t[p][3] + x) & ((1 << 64) - 1) self.t[p][2] += 1 if Lb == Rb: return mid = (Lb + Rb) >> 1 if k <= mid: pre_l = self.t[pre][0] new_l_ref = [self.t[p][0]] self._add(new_l_ref, pre_l, Lb, mid, k, x) self.t[p][0] = new_l_ref[0] else: pre_r = self.t[pre][1] new_r_ref = [self.t[p][1]] self._add(new_r_ref, pre_r, mid + 1, Rb, k, x) self.t[p][1] = new_r_ref[0] def _findDiff(self, p, pre, Lb, Rb): if Lb == Rb: return self.t[p][2] > self.t[pre][2] mid = (Lb + Rb) >> 1 p_r_node_idx = self.t[p][1] pre_r_node_idx = self.t[pre][1] p_r_val = self.t[p_r_node_idx][3] pre_r_val = self.t[pre_r_node_idx][3] if p_r_val == pre_r_val: return self._findDiff(self.t[p][0], self.t[pre][0], Lb, mid) else: return self._findDiff(self.t[p][1], self.t[pre][1], mid + 1, Rb) def solve1(self, n, L_param, R_param): sys.setrecursionlimit(max(sys.getrecursionlimit(), 2 * n)) self.N = n L = L_param R = R_param deg = [0] * (self.N + 1) fa = [0] * (self.N + 1) for i in range(1, self.N + 1): if L[i] != 0 and R[i] != 0: deg[i] = 2 if L[i] != 0: fa[L[i]] = i if R[i] != 0: fa[R[i]] = i self.t = [[0, 0, 0, 0]] self.cnt = 0 A = random.getrandbits(64) def shift(x): mask = (1 << 64) - 1 x ^= A x ^= (x << 13) & mask x ^= x >> 7 x ^= (x << 11) & mask x ^= A return x self.h = [0] * (self.N + 1) self.rt = [0] * (self.N + 1) self.rk = [0] * (self.N + 1) def upd(u): self.h[u] = (self.h[L[u]] + shift(self.h[R[u]])) & ((1 << 64) - 1) w = shift(self.h[R[u]]) new_rt_u_ref = [self.rt[u]] self._add(new_rt_u_ref, self.rt[L[u]], 1, self.N, self.rk[R[u]], w) self.rt[u] = new_rt_u_ref[0] q = [] for i in range(1, self.N + 1): if deg[i] == 0: self.h[i] = 1 heapq.heappush(q, _CmpNode(i, self)) ans = [] lst = 0 tot = 0 while q: node_obj = heapq.heappop(q) u = node_obj.u ans.append(u) if lst == 0 or self.h[u] != self.h[lst]: tot += 1 lst = u self.rk[u] = tot f = fa[u] if f != 0: deg[f] -= 1 if deg[f] == 0: upd(f) heapq.heappush(q, _CmpNode(f, self)) return ans def solve2(self, n, L_param, R_param): L = L_param R = R_param def is_leaf(u): return L[u] == 0 and R[u] == 0 def core(u, v): stack = [] while True: while not is_leaf(u) and not is_leaf(v): stack.append((u, v)) u, v = R[u], R[v] if is_leaf(u) and is_leaf(v): res = 0 elif is_leaf(u): res = -1 elif is_leaf(v): res = 1 else: res = 0 while True: if not stack: return res pu, pv = stack.pop() if res != 0: continue u, v = L[pu], L[pv] break def cmp_nodes(u, v): res = core(u, v) if res != 0: return res if u < v: return -1 if u > v: return 1 return 0 arr = list(range(1, n + 1)) arr.sort(key=cmp_to_key(cmp_nodes)) return arr","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) L = [0] * (n + 1) R = [0] * (n + 1) for i in range(1, n + 1): L[i] = int(next(it)) R[i] = int(next(it)) solution = Solution() result = solution.solve(n, L, R) out = [] for i in range(len(result)): if i + 1 == len(result): out.append(str(result[i])) else: out.append(str(result[i]) + "" "") sys.stdout.write("""".join(out))","data_structures,graph",hard 207,"Given two 0-indexed integer arrays nums1 and nums2 with the same length, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1. The integers in each list must be returned in ascending order. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here ``` Example 1: Input: nums1 = [1,2,3], nums2 = [2,4,6] Output: [[1,3],[4,6]] Example 2: Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] Output: [[3],[]] Constraints: 1 <= nums1.length == nums2.length <= @data -@data <= nums1[i], nums2[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[5000, 500, 78], [40000, 4000, 625], [320000, 32000, 5000]]","import collections class Solution: def solve1(self, nums1, nums2): set1 = set(nums1) set2 = set(nums2) temp = [] for item in set1: if item not in set2: temp.append(item) temp2 = [] for item in set2: if item not in set1: temp2.append(item) temp.sort() temp2.sort() return [temp, temp2] def solve2(self, nums1, nums2): ans0 = [] n1 = len(nums1) n2 = len(nums2) for i in range(n1): v = nums1[i] found = False for j in range(n2): if nums2[j] == v: found = True break if not found: dup = False for k in range(len(ans0)): if ans0[k] == v: dup = True break if not dup: ans0.append(v) ans1 = [] for i in range(n2): v = nums2[i] found = False for j in range(n1): if nums1[j] == v: found = True break if not found: dup = False for k in range(len(ans1)): if ans1[k] == v: dup = True break if not dup: ans1.append(v) m0 = len(ans0) for i in range(m0): min_idx = i for j in range(i + 1, m0): if ans0[j] < ans0[min_idx]: min_idx = j if min_idx != i: tmp = ans0[i] ans0[i] = ans0[min_idx] ans0[min_idx] = tmp m1 = len(ans1) for i in range(m1): min_idx = i for j in range(i + 1, m1): if ans1[j] < ans1[min_idx]: min_idx = j if min_idx != i: tmp = ans1[i] ans1[i] = ans1[min_idx] ans1[min_idx] = tmp return [ans0, ans1] ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, n + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) out_lines = [] for it_row in result: line_parts = [] for i in it_row: line_parts.append(str(i)) out_lines.append("" "".join(line_parts)) sys.stdout.write(""\n"".join(out_lines))",STL,medium 208,"You are given an array nums consisting of positive integers. Starting with score = 0, apply the following algorithm: Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index. Add the value of the chosen integer to score. Mark the chosen element and its two adjacent elements if they exist. Repeat until all the array elements are marked. Return the score you get after applying the above algorithm solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [2,1,3,4,5,2] Output: 7 Example 2: Input: nums = [2,3,5,1,3,2] Output: 5 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums): ans = 0 i = 0 n = len(nums) while i < n: currentStart = i while i + 1 < n and nums[i + 1] < nums[i]: i += 1 for currentIndex in range(i, currentStart - 1, -2): ans += nums[currentIndex] i += 2 return ans def solve2(self, nums): n = len(nums) score = 0 remain = n while remain > 0: min_val = None min_idx = -1 for i in range(n): v = nums[i] if v > 0: if min_val is None or v < min_val: min_val = v min_idx = i score += min_val if nums[min_idx] > 0: nums[min_idx] = -nums[min_idx] remain -= 1 j = min_idx - 1 if j >= 0 and nums[j] > 0: nums[j] = -nums[j] remain -= 1 j = min_idx + 1 if j < n and nums[j] > 0: nums[j] = -nums[j] remain -= 1 return score ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))",sort,medium 209,"# Problem Statement: You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $n$ seconds and at the $i$-th second the color $s_i$ is on. That way, the order of the colors is described by a string. For example, if $s=$""rggry"", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on. More formally, you are given a string $s_1, s_2, \ldots, s_n$ of length $n$. At the first second the color $s_1$ is on, at the second — $s_2$, ..., at the $n$-th second the color $s_n$ is on, at the $n + 1$-st second the color $s_1$ is on and so on. You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road. You can assume that you cross the road immediately. For example, with $s=$""rggry"" and the current color r there are two options: either the green color will be on after $1$ second, or after $3$. That way, the answer is equal to $3$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r. The main function of the solution is defined as: ```python class Solution: def solve(self, n, c, s): pass # write your code here``` Where: - `n` is an integer representing the length of the string $s$. - `c` is a character representing the current color of the traffic light. - `s` is a string representing the sequence of colors in the traffic light. - The function should return an integer: the minimum guaranteed time in seconds after which you can cross the road. # Example 1: - Input: n = 5 c = 'r' s = ""rggry"" - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $c, s_i \in \{r, g, y\}$ - Guaranteed solution exists - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, c, s): ans = 0 x = 0 for t in range(2): for i in range(n - 1, -1, -1): if s[i] == 'g': x = 0 else: x += 1 if s[i] == c and t: ans = max(ans, x) return ans def solve2(self, n, c, s): if c == 'g': return 0 ans = 0 for i in range(n): if s[i] == c: dist = 0 j = i while True: j += 1 if j == n: j = 0 dist += 1 if s[j] == 'g': break if dist > ans: ans = dist return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) c = next(it)[0] s = next(it) solution = Solution() result = solution.solve(n, c, s) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary",medium 210,"# Problem Statement You are given an array of integers $a_1,a_2,\dots,a_n$. You may repeatedly perform the following operation: - Choose indices $1 \le i \le j \le n$; - Update $a_j \leftarrow a_j \oplus a_i$ (bitwise XOR). There are $q$ queries. For each query $(l,r)$, you are allowed to use only indices inside $[l,r]$. Determine whether the subarray $a_l,\dots,a_r$ can be transformed into a strictly increasing sequence using any number of such operations. The main function of the solution is defined as: ```python class Solution: def solve(self, n, q, a, queries): pass # write your code here``` where: - `n`: length of the array - `q`: number of queries - `a`: the array - `queries`: list of `{l, r}` (1-based) - return: an array of strings, each is ""YES"" or ""NO"" # Example - Input: ``` n = 4, q = 4 a = [1, 2, 2, 1] queries = [(1,1),(1,2),(1,3),(1,4)] ``` - Output: ``` [""YES"",""YES"",""YES"",""YES""] ``` # Constraints - $1 \le n \le @data$ - $1 \le q \le @data$ - $1 \le a_i < 2^{20}$ - $1 \le l \le r \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",6000,"[[2560, 1000, 500], [20480, 8000, 4000], [163840, 64000, 32000]]","import sys class Solution: def solve1(self, n, q, a, queries): K = 20 vx = [0] * K vy = [0] * K def kth(r, k): if k == -1: return -1 cnt = 0 for i in range(K): if vx[i] != 0 and vy[i] <= r: cnt += 1 ans = 0 for i in range(K - 1, -1, -1): if vx[i] != 0 and vy[i] <= r: cnt -= 1 if ((ans >> i) & 1) != ((k >> cnt) & 1): ans ^= vx[i] return ans def rankv(r, k): if k == -1: return -1 ans = 0 for i in range(K - 1, -1, -1): if vx[i] != 0 and vy[i] <= r: ans = (ans << 1) | ((k >> i) & 1) return ans def calc_best_r(l): pos = [] for i in range(K): if vx[i] != 0: pos.append(vy[i]) pos.sort() curVal = -1 last = l used = 0 for p in pos: if p > last: rk = rankv(last, curVal) cap = (1 << used) - 1 - rk if cap < 0: return last - 1 block = p - last if cap < block: return last + cap rk += block curVal = kth(last, rk) last = p used += 1 rk = rankv(last, curVal) cap = (1 << used) - 1 - rk if cap < 0: return last - 1 tail = n - last return last + min(tail, cap) bestR = [0] * n for i in range(n - 1, -1, -1): x, y = a[i], i for j in range(K - 1, -1, -1): if (x >> j) & 1: if vx[j] == 0: vx[j] = x vy[j] = y break if y < vy[j]: x, vx[j] = vx[j], x y, vy[j] = vy[j], y x ^= vx[j] bestR[i] = calc_best_r(i) res = [] for l_query, r_query in queries: l_idx = l_query - 1 if r_query <= bestR[l_idx]: res.append(""YES"") else: res.append(""NO"") return res def solve2(self, n, q, a, queries): K = 20 def rankv(vx, k): if k == -1: return -1 ans = 0 for i in range(K - 1, -1, -1): if vx[i] != 0: ans = (ans << 1) | ((k >> i) & 1) return ans def kth(vx, idx, d): if idx == -1: return -1 cnt = d ans = 0 for i in range(K - 1, -1, -1): if vx[i] != 0: cnt -= 1 if ((ans >> i) & 1) != ((idx >> cnt) & 1): ans ^= vx[i] return ans res = [] for l, r in queries: vx = [0] * K d = 0 prev = -1 ok = True for j in range(l - 1, r): x = a[j] for i in range(K - 1, -1, -1): if (x >> i) & 1: if vx[i] == 0: vx[i] = x d += 1 break x ^= vx[i] if prev == -1: idx = 0 else: rk = rankv(vx, prev) total = 1 << d idx = rk + 1 if idx >= total: ok = False break prev = kth(vx, idx, d) res.append(""YES"" if ok else ""NO"") return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) q = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) queries = [] for i in range(q): x = int(next(it)) y = int(next(it)) queries.append([x, y]) solution = Solution() result = solution.solve(n, q, a, queries) out_lines = [] for i in range(len(result)): out_lines.append(str(result[i])) sys.stdout.write(""\n"".join(out_lines))",data_structures,hard 211,"You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: flips = [3,2,4,1,5] Output: 2 Example 2: Input: flips = [4,1,2,3] Output: 1 Constraints: n == flips.length 1 <= n <= @data flips is a permutation of the integers in the range [1, n]. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, flips): n = len(flips) s1 = 0 s2 = 0 ans = 0 for i in range(n): s1 += i + 1 s2 += flips[i] if s1 == s2: ans += 1 return ans def solve2(self, flips): n = len(flips) ans = 0 for i in range(1, n + 1): mx = 0 for k in range(i): if flips[k] > mx: mx = flips[k] if mx == i: ans += 1 return ans ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",other,medium 212,"# Problem Statement You are given an array $a$ of length $n$. Start with $c = 0$. Then, for each $i$ from $1$ to $n$ (in increasing order) do **exactly one** of the following: - Option $1$: set $c$ to $c + a_i$. - Option $2$: set $c$ to $|c + a_i|$, where $|x|$ is the absolute value of $x$. Let the maximum final value of $c$ after the procedure described above be equal to $k$. Find $k$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return the value of $k$. # Example 1: - Input: n = 4 a = [10, -9, -3, 4] - Output: 6 # Constraints: - $2 \leq n \leq @data$ - $-10^9 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): c1 = 0 c2 = 0 for i in range(n): pre1 = c1 pre2 = c2 c1 = max(pre1 + a[i], abs(pre2 + a[i])) c2 = pre2 + a[i] return c1 def solve2(self, n, a): max_c = None limit = 1 << n m = 0 while m < limit: c = 0 i = 0 while i < n: if (m >> i) & 1: c = abs(c + a[i]) else: c = c + a[i] i += 1 if max_c is None or c > max_c: max_c = c m += 1 return max_c if max_c is not None else 0 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",dp,medium 213,"# Problem Statement A permutation $b$ is considered a riffle shuffle of a permutation $a$ if $\|a\|=\|b\|$ and there exists $k$ ($1\le k<\|a\|$) such that both $a_1,a_2,\dots,a_k$ and $a_{k+1},a_{k+2},\dots,a_{\|a\|}$ are subsequences of $b$. You are given a permutation $p$ of length $n$ where some values are replaced with $-1$. Determine the number of ways to replace each $-1$ with an integer so that $p$ becomes a riffle shuffle of $[1,2,\dots,n]$ (the sorted permutation). Output the number of ways modulo $998244353$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, p): pass # write your code here``` where: - `n`: the length of the permutation. - `p`: an array of length `n`. Each `p[i]` is either `-1` or an integer in `[1, n]`. All elements different from `-1` are pairwise distinct. - return: the number of valid completions modulo `998244353`. # Example 1: - Input: ``` n = 5 p = [-1, -1, -1, 2, -1] ``` - Output: ``` 6 ``` # Constraints: - $1 \leq n \leq @data$ - $p[i] \in \{-1\} \cup [1,n]$, and all known values are distinct - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 179, 150], [4000, 1437, 1200], [32000, 11500, 9600]]","import sys MOD = 998244353 class Mint: def __init__(self, v=0): v %= MOD if v < 0: v += MOD self.x = int(v) def __iadd__(self, other): self.x += other.x if self.x >= MOD: self.x -= MOD return self def __isub__(self, other): self.x -= other.x if self.x < 0: self.x += MOD return self def __imul__(self, other): self.x = (self.x * other.x) % MOD return self def __add__(self, other): res = Mint(self.x) return res.__iadd__(other) def __sub__(self, other): res = Mint(self.x) return res.__isub__(other) def __mul__(self, other): res = Mint(self.x) return res.__imul__(other) @staticmethod def pow(a, e): a = Mint(a.x) r = Mint(1) while e > 0: if e & 1: r *= a a *= a e >>= 1 return r @staticmethod def inv(a): return Mint.pow(a, MOD - 2) FAC = [Mint(1), Mint(1)] IFAC = [Mint(1), Mint(1)] MAX_DONE = 1 def grow(need): global FAC, IFAC, MAX_DONE m = MAX_DONE if m >= need: return while m < need: m <<= 1 old_size = len(FAC) FAC.extend([Mint(0) for _ in range(m + 1 - old_size)]) IFAC.extend([Mint(0) for _ in range(m + 1 - old_size)]) for i in range(MAX_DONE + 1, m + 1): FAC[i] = FAC[i - 1] * Mint(i) IFAC[m] = Mint.inv(FAC[m]) for i in range(m - 1, MAX_DONE, -1): IFAC[i] = IFAC[i + 1] * Mint(i + 1) MAX_DONE = m def nCr(n, r): if r < 0 or r > n: return Mint(0) grow(n) return FAC[n] * IFAC[r] * IFAC[n - r] class Solution: def solve1(self, n, p): a = [(v - 1 if v != -1 else -1) for v in p] allFixedSorted = True for i in range(n): if a[i] != -1 and a[i] != i: allFixedSorted = False break if allFixedSorted: pow2 = [Mint(0)] * (n + 1) pow2[0] = Mint(1) for i in range(1, n + 1): pow2[i] = pow2[i - 1] * Mint(2) last = -1 ans = Mint(0) for i in range(n + 1): if i == n or a[i] != -1: length = i - last - 1 if length > 0: ans += pow2[length] - Mint(length) - Mint(1) last = i ans += Mint(1) out = ans.x if out < 0: out += MOD return out side = [0] * n seenDiff = False for i in range(n): if a[i] == -1: continue if a[i] < i: side[i] = 0 elif a[i] > i: side[i] = 1 else: side[i] = 1 if seenDiff else 0 if a[i] != i: seenDiff = True last = -1 ranges = [] for i in range(n): if a[i] == -1: continue if last == -1: last = i continue if side[i] and not side[last]: mn = last - a[last] mx = mn + (i - last) L_k = a[i] - mx R_k = a[i] - mn + 1 ranges.append((L_k, R_k)) if not side[i] and side[last]: mx = i - a[i] mn = mx - (i - last) L_k = a[last] - mx R_k = a[last] - mn + 1 ranges.append((L_k, R_k)) last = i L = 0 R = n - 1 for pr in ranges: L = max(L, pr[0]) R = min(R, pr[1]) L = max(L, 0) R = min(R, n - 1) coef = Mint(1) score = [Mint(0)] * n if L <= R: for k in range(L, R + 1): score[k] = Mint(1) last = -1 for i in range(n): if a[i] == -1: continue prevSide = 0 if last == -1 else side[last] spaces = i - last - 1 if (side[i] and prevSide) or (not side[i] and not prevSide): cnt = a[i] if last == -1 else a[i] - a[last] - 1 coef *= nCr(spaces, cnt) elif side[i] and not prevSide: for k in range(L, R + 1): placed = 0 if last == -1 else last - a[last] need = a[i] - (k + placed) score[k] *= nCr(spaces, need) elif not side[i] and prevSide: for k in range(L, R + 1): big = i - a[i] + k - 1 need = big - a[last] score[k] *= nCr(spaces, need) last = i if last != -1: spaces = n - last - 1 if L <= R: for k in range(L, R + 1): if not side[last]: need = k - a[last] - 1 score[k] *= nCr(spaces, need) else: need = n - 1 - a[last] score[k] *= nCr(spaces, need) ans = Mint(0) for i in range(n): ans += score[i] ans *= coef return ans.x def solve2(self, n, p): for i in range(n): if p[i] != -1: p[i] = -(p[i] + n + 1) pos = 0 for v in range(1, n + 1): present = False for i in range(n): w = p[i] if w == -1: continue if w < -1: w = -w - n - 1 if w == v: present = True break if not present: while pos < n and p[pos] != -1: pos += 1 if pos < n: p[pos] = v pos += 1 def is_riffle(): for k in range(1, n): lastR = 0 lastB = k good = True for i in range(n): val = p[i] if val < -1: val = -val - n - 1 if val <= k: if val <= lastR: good = False break lastR = val else: if val <= lastB: good = False break lastB = val if good: return True return False def next_perm(): pivot_idx = -1 have_prev = False prev_val = 0 for i in range(n - 1, -1, -1): if p[i] > 0: if have_prev: if p[i] < prev_val: pivot_idx = i break prev_val = p[i] have_prev = True if pivot_idx == -1: return False pivot_val = p[pivot_idx] succ_idx = -1 for i in range(n - 1, pivot_idx, -1): if p[i] > 0 and p[i] > pivot_val: succ_idx = i break p[succ_idx], p[pivot_idx] = p[pivot_idx], p[succ_idx] left = pivot_idx + 1 while left < n and p[left] <= 0: left += 1 right = n - 1 while right >= 0 and p[right] <= 0: right -= 1 while left < right: p[left], p[right] = p[right], p[left] j = left + 1 while j < n and p[j] <= 0: j += 1 left = j j = right - 1 while j >= 0 and p[j] <= 0: j -= 1 right = j return True ans = 0 while True: if is_riffle(): ans += 1 if ans >= MOD: ans -= MOD if not next_perm(): break return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) p = [0] * n for i in range(0, n): p[i] = int(next(it)) solution = Solution() result = solution.solve(n, p) sys.stdout.write(str(result) + ""\n"")",math,hard 214,"You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right. The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces. Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: start = ""_L__R__R_"", target = ""L______RR"" Output: 1 Example 2: Input: start = ""R_L_"", target = ""__LR"" Output: 0 Constraints: n == start.length == target.length 1 <= n <= @data start and target consist of the characters 'L', 'R', and '_'. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 93], [32000, 3200, 750]]","class Solution: def solve1(self, start, target): startLength = len(start) startIndex = 0 targetIndex = 0 while startIndex < startLength or targetIndex < startLength: while startIndex < startLength and start[startIndex] == '_': startIndex += 1 while targetIndex < startLength and target[targetIndex] == '_': targetIndex += 1 if startIndex == startLength or targetIndex == startLength: return startIndex == startLength and targetIndex == startLength if (start[startIndex] != target[targetIndex] or (start[startIndex] == 'L' and startIndex < targetIndex) or (start[startIndex] == 'R' and startIndex > targetIndex)): return False startIndex += 1 targetIndex += 1 return True def solve2(self, start, target): n = len(start) i = 0 j = 0 while i < n or j < n: while i < n and start[i] == '_': i += 1 while j < n and target[j] == '_': j += 1 if i == n or j == n: return i == n and j == n if start[i] != target[j]: return False if start[i] == 'L': if i < j: return False else: if i > j: return False i += 1 j += 1 return True ","import sys data = sys.stdin.read().split() a = """" b = """" if len(data) > 0: a = data[0] if len(data) > 1: b = data[1] solution = Solution() result = solution.solve(a, b) sys.stdout.write(""1"" if result else ""0"")","two_pointers,string",medium 215,"There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. solution main function ```python class Solution: def solve(self, edge): pass # write your code here``` Example 1: Input: edges = [[1,2],[2,3],[4,2]] Output: 2 Constraints: 2 <= n <= @data edges.length == n - 1 edges[i].length == 2 1 <= ui, vi <= n ui ! = vi Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, edges: List[List[int]]) -> int: return edges[0][0] if edges[0][0] == edges[1][0] or edges[0][0] == edges[1][1] else edges[0][1] def solve2(self, edges: List[List[int]]) -> int: a = edges[0][0] b = edges[0][1] i = 0 n = len(edges) while i < n: e0 = edges[i][0] e1 = edges[i][1] if e0 != a and e1 != a: return b i += 1 return a","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) edge = [] i = 1 while i < n: x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) edge.append(temp) i += 1 solution = Solution() result = solution.solve(edge) sys.stdout.write(str(result) + ""\n"")",graph,easy 216,"You are given two integers n and m that consist of the same number of digits. You can perform the following operations any number of times: Choose any digit from n that is not 9 and increase it by 1. Choose any digit from n that is not 0 and decrease it by 1. The integer n must not be a prime number at any point, including its original value and after each operation. The cost of a transformation is the sum of all values that n takes throughout the operations performed. Return the minimum cost to transform n into m. If it is impossible, return -1. solution main function ```python class Solution: def solve(self, n, m): pass # write your code here``` Example 1: Input: n = 10, m = 12 Output: 85 Example 2: Input: n = 4, m = 8 Output: -1 Constraints: 1 <= n, m <= @data n and m consist of the same number of digits. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import heapq class Solution: isPrime = [] def solve1(self, n, m): if not Solution.isPrime: limit = 100001 Solution.isPrime = [True] * limit Solution.isPrime[0] = Solution.isPrime[1] = False for i in range(2, limit): if Solution.isPrime[i]: for j in range(i * 2, limit, i): Solution.isPrime[j] = False if Solution.isPrime[n] or Solution.isPrime[m]: return -1 q = [] heapq.heappush(q, (n, n)) visited = set() while q: cost, curr = heapq.heappop(q) if curr in visited: continue visited.add(curr) if curr == m: return cost s = str(curr) s_list = list(s) for i in range(len(s_list)): original_char = s_list[i] if original_char < '9': s_list[i] = str(int(original_char) + 1) next_val = int("""".join(s_list)) if not Solution.isPrime[next_val] and next_val not in visited: heapq.heappush(q, (cost + next_val, next_val)) s_list[i] = original_char if original_char > '0' and not (i == 0 and original_char == '1'): s_list[i] = str(int(original_char) - 1) next_val = int("""".join(s_list)) if not Solution.isPrime[next_val] and next_val not in visited: heapq.heappush(q, (cost + next_val, next_val)) s_list[i] = original_char return -1 def solve2(self, n, m): def is_prime(x): if x < 2: return False if x % 2 == 0: return x == 2 i = 3 while i * i <= x: if x % i == 0: return False i += 2 return True if is_prime(n) or is_prime(m): return -1 d = len(str(n)) low = 1 if d == 1 else 10 ** (d - 1) hi = 10 ** d - 1 p10 = [1] * d for i in range(d - 2, -1, -1): p10[i] = p10[i + 1] * 10 INF = 10 ** 30 dist = [INF] * (hi + 1) dist[n] = n pq = [(n, n)] while pq: cost, u = heapq.heappop(pq) if cost != dist[u]: continue if u == m: return cost for i in range(d): w = p10[i] digit = (u // w) % 10 if digit < 9: v = u + w if not is_prime(v) and dist[v] > cost + v: dist[v] = cost + v heapq.heappush(pq, (dist[v], v)) if digit > 0 and not (i == 0 and digit == 1): v = u - w if not is_prime(v) and dist[v] > cost + v: dist[v] = cost + v heapq.heappush(pq, (dist[v], v)) return -1","import sys def main(): data = sys.stdin.buffer.read().split() if len(data) < 2: return n = int(data[0]) m = int(data[1]) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","graph,math",medium 217,"You are given a string s and two integers x and y. You can perform two types of operations any number of times. Remove substring ""ab"" and gain x points. For example, when removing ""ab"" from ""cabxbae"" it becomes ""cxbae"". Remove substring ""ba"" and gain y points. For example, when removing ""ba"" from ""cabxbae"" it becomes ""cabxe"". Return the maximum points you can gain after applying the above operations on s. solution main function ```python class Solution: def solve(self, s, x, y): pass # write your code here``` Example 1: Input: s = ""cdbcbbaaabab"", x = 4, y = 5 Output: 19 Example 2: Input: s = ""aabbaaxybbaabb"", x = 5, y = 4 Output: 20 Constraints: 1 <= s.length <= @data 1 <= x, y <= 10^4 s consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s, x, y): aCount = 0 bCount = 0 lesser = min(x, y) result = 0 for c in s: if c > 'b': result += min(aCount, bCount) * lesser aCount = 0 bCount = 0 elif c == 'a': if x < y and bCount > 0: bCount -= 1 result += y else: aCount += 1 else: if x > y and aCount > 0: aCount -= 1 result += x else: bCount += 1 result += min(aCount, bCount) * lesser return result def solve2(self, s, x, y): def remove_all(s, pattern, val): score = 0 i = s.find(pattern) while i != -1: s = s[:i] + s[i+2:] score += val i = s.find(pattern, i - 1 if i > 0 else 0) return s, score total = 0 if x >= y: s, sc = remove_all(s, ""ab"", x) total += sc s, sc = remove_all(s, ""ba"", y) total += sc else: s, sc = remove_all(s, ""ba"", y) total += sc s, sc = remove_all(s, ""ab"", x) total += sc return total ","import sys data = sys.stdin.read().split() it = iter(data) x = int(next(it)) y = int(next(it)) s = next(it) solution = Solution() result = solution.solve(s, x, y) sys.stdout.write(str(result))","string,greedy",hard 218,"You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: boxes = ""110"" Output: [1,1,3] Example 2: Input: boxes = ""001011"" Output: [11,8,5,4,3,4] Constraints: n == boxes.length 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import functools import itertools import re import sys import math from typing import * class Solution: def solve1(self, boxes): n = len(boxes) answer = [0] * n ballsToLeft = 0 movesToLeft = 0 ballsToRight = 0 movesToRight = 0 for i in range(n): answer[i] += movesToLeft ballsToLeft += int(boxes[i]) movesToLeft += ballsToLeft j = n - 1 - i answer[j] += movesToRight ballsToRight += int(boxes[j]) movesToRight += ballsToRight return answer def solve2(self, boxes): n = len(boxes) res = [0] * n for i in range(n): total = 0 for j in range(n): if boxes[j] == '1': if j >= i: total += j - i else: total += i - j res[i] = total return res ","import sys def main(): data = sys.stdin.read().split() if not data: return s = data[0] solution = Solution() result = solution.solve(s) out = [] for it in result: out.append(str(it)) out.append(' ') sys.stdout.write(''.join(out)) if __name__ == ""__main__"": main()",string,medium 219,"You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi. Return the number of complete connected components of the graph. A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. A connected component is said to be complete if there exists an edge between every pair of its vertices. solution main function ```python class Solution: def solve(self, n, g): pass # write your code here``` Example 1: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] Output: 3 Example 2: Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] Output: 1 Constraints: 1 <= n <= @data 0 <= edges.length <= 3*n edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no repeated edges. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 10000]",4000,"[[500, 64, 64], [4000, 400, 75], [32000, 3200, 600]]","import math class Solution: def find(self, G, n): while G[n] >= 0: n = G[n] return n def solve1(self, n, edges): G = [-1] * n edge = [0] * n cnt = 0 for i in range(len(edges)): r1 = self.find(G, edges[i][0]) r2 = self.find(G, edges[i][1]) t1 = min(r1, r2) t2 = max(r1, r2) r1 = t1 r2 = t2 if r1 != r2: G[r1] += G[r2] G[r2] = r1 edge[r1] += edge[r2] edge[r1] += 1 for i in range(n): if G[i] < 0 and G[i] < 0 and edge[i] == (-G[i] - 1) * (-G[i]) // 2: cnt += 1 return cnt def solve2(self, n, edges): isolated = 0 for i in range(n): found = False for e in edges: if e[0] == i or e[1] == i: found = True break if not found: isolated += 1 count = isolated m = len(edges) while True: idx = -1 for j in range(m): u = edges[j][0] v = edges[j][1] if u != -1 and v != -1: idx = j break if idx == -1: break s = edges[idx][0] if s == -1: s = edges[idx][1] k = 1 changed = True while changed: changed = False for j in range(m): u = edges[j][0] v = edges[j][1] if u == -1 and v == -1: continue if u == s and v != s: x = v for t in range(m): a = edges[t][0] b = edges[t][1] if a == x: edges[t][0] = s if b == x: edges[t][1] = s k += 1 changed = True elif v == s and u != s: x = u for t in range(m): a = edges[t][0] b = edges[t][1] if a == x: edges[t][0] = s if b == x: edges[t][1] = s k += 1 changed = True ecount = 0 for j in range(m): if edges[j][0] == s and edges[j][1] == s: ecount += 1 for j in range(m): if edges[j][0] == s and edges[j][1] == s: edges[j][0] = -1 edges[j][1] = -1 if ecount == k * (k - 1) // 2: count += 1 return count ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) g = [] for i in range(1, m + 1): temp = [] x = int(next(it)) y = int(next(it)) temp.append(x) temp.append(y) g.append(temp) solution = Solution() result = solution.solve(n, g) sys.stdout.write(str(result))","graph,search,data_structures",medium 220,"You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: nums = [90], k = 1 Output: 0 Example 2: Input: nums = [9,4,1,7], k = 2 Output: 2 Constraints: 1 <= k <= nums.length <= @data 0 <= nums[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, nums, k): nums.sort() min_diff = float('inf') l, r = 0, k - 1 while r < len(nums): min_diff = min(min_diff, nums[r] - nums[l]) l += 1 r += 1 return min_diff def solve2(self, nums, k): if k <= 1: return 0 nums.sort() n = len(nums) min_diff = nums[k - 1] - nums[0] l, r = 1, k while r < n: diff = nums[r] - nums[l] if diff < min_diff: min_diff = diff l += 1 r += 1 return min_diff ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = [] i = 1 while i <= n: x = int(next(it)) s.append(x) i += 1 solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result))",math,easy 221,"Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: Every song is played at least once. A song can only be played again only if k other songs have been played. Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, n, goal, k): pass # write your code here``` Example 1: Input: n = 3, goal = 3, k = 1 Output: 6 Example 2: Input: n = 2, goal = 3, k = 0 Output: 6 Constraints: 0 <= k < n <= goal <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import sys class Solution: MOD = 10**9 + 7 factorial = [] invFactorial = [] def power(self, base, exponent): result = 1 while exponent > 0: if exponent & 1: result = (result * base) % self.MOD exponent >>= 1 base = (base * base) % self.MOD return result def precalculateFactorials(self, n): self.factorial = [0] * (n + 1) self.invFactorial = [0] * (n + 1) self.factorial[0] = self.invFactorial[0] = 1 for i in range(1, n + 1): self.factorial[i] = (self.factorial[i - 1] * i) % self.MOD self.invFactorial[i] = self.power(self.factorial[i], self.MOD - 2) def solve1(self, n, goal, k): self.precalculateFactorials(n) sign = 1 answer = 0 for i in range(n, k - 1, -1): temp = self.power(i - k, goal - k) temp = (temp * self.invFactorial[n - i]) % self.MOD temp = (temp * self.invFactorial[i - k]) % self.MOD answer = (answer + sign * temp + self.MOD) % self.MOD sign *= -1 return (self.factorial[n] * answer) % self.MOD def factorial(self, x): result = 1 for i in range(2, x + 1): result = (result * i) % self.MOD return result def inv_factorial(self, x): return self.power(self.factorial(x), self.MOD - 2) def solve2(self, n, goal, k): fact_n = self.factorial(n) answer = 0 sign = 1 t = goal - k for i in range(n, k - 1, -1): temp = self.power(i - k, t) temp = (temp * self.inv_factorial(n - i)) % self.MOD temp = (temp * self.inv_factorial(i - k)) % self.MOD if sign == 1: answer += temp else: answer -= temp answer %= self.MOD sign = -sign return (fact_n * answer) % self.MOD","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) goal = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, goal, k) sys.stdout.write(str(result) + ""\n"")",math,hard 222,"There is an undirected graph of n nodes. You are given a 2D array edges, where edges[i] = [ui, vi, lengthi] describes an edge between node ui and node vi with a traversal time of lengthi units. Additionally, you are given an array disappear, where disappear[i] denotes the time when the node i disappears from the graph and you won't be able to visit it. Note that the graph might be disconnected and might contain multiple edges. Return the array answer, with answer[i] denoting the minimum units of time required to reach node i from node 0. If node i is unreachable from node 0 then answer[i] is -1. solution main function ```python class Solution: def solve(self, n, edge, val): pass # write your code here``` Example 1: Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5] Output: [0,-1,4] Example 2: Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5] Output: [0,2,3] Constraints: 1 <= n <= @data 0 <= edges.length <= 10^5 edges[i] == [ui, vi, lengthi] 0 <= ui, vi <= n - 1 1 <= lengthi <= 10^5 disappear.length == n 1 <= disappear[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import heapq import math class Solution: def solve1(self, n, v, d): adj = [[] for _ in range(n)] for i in range(len(v)): a, b, t = v[i][0], v[i][1], v[i][2] if a == b: continue adj[a].append((b, t)) adj[b].append((a, t)) q = [(0, 0)] dist = [math.inf] * n vis = [False] * n dist[0] = 0 while q: p = heapq.heappop(q) t, s = p[0], p[1] if vis[s]: continue if t >= d[s]: continue vis[s] = True for neighbor_pair in adj[s]: neighbor_node, weight = neighbor_pair[0], neighbor_pair[1] if t + weight < dist[neighbor_node] and t + weight < d[neighbor_node]: dist[neighbor_node] = t + weight heapq.heappush(q, (t + weight, neighbor_node)) ans = [] for i in range(n): if dist[i] < d[i]: ans.append(dist[i]) else: ans.append(-1) return ans def solve2(self, n, v, d): INF = 10**30 ans = [INF] * n if 0 < d[0]: ans[0] = 0 for _ in range(n - 1): updated = False for e in v: a = e[0] b = e[1] w = e[2] t = ans[a] if t < d[a]: t2 = t + w if t2 < d[b] and t2 < ans[b]: ans[b] = t2 updated = True t = ans[b] if t < d[b]: t2 = t + w if t2 < d[a] and t2 < ans[a]: ans[a] = t2 updated = True if not updated: break for i in range(n): if ans[i] >= d[i]: ans[i] = -1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) edge = [] val = [] i = 1 while i <= m: x = int(next(it)) y = int(next(it)) z = int(next(it)) temp = [] temp.append(x) temp.append(y) temp.append(z) edge.append(temp) i += 1 i = 1 while i <= n: x = int(next(it)) val.append(x) i += 1 solution = Solution() result = solution.solve(n, edge, val) out = [] for v in result: out.append(str(v)) sys.stdout.write("" "".join(out))","graph,search",medium 223,"Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. A subarray is a contiguous part of the array. solution main function ```python class Solution: def solve(self, num, goal): pass # write your code here``` Example 1: Input: nums = [1,0,1,0,1], goal = 2 Output: 4 Example 2: Input: nums = [0,0,0,0,0], goal = 0 Output: 15 Constraints: 1 <= nums.length <= @data nums[i] is either 0 or 1. 0 <= goal <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, nums, goal): return self.slidingWindowAtMost(nums, goal) - self.slidingWindowAtMost(nums, goal - 1) def solve2(self, nums, goal): n = len(nums) count = 0 for i in range(n): s = 0 for j in range(i, n): s += nums[j] if s == goal: count += 1 elif s > goal: break return count def slidingWindowAtMost(self, nums, goal): start = 0 currentSum = 0 totalCount = 0 for end in range(len(nums)): currentSum += nums[end] while start <= end and currentSum > goal: currentSum -= nums[start] start += 1 totalCount += end - start + 1 return totalCount ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) goal = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num, goal) sys.stdout.write(str(result))",math,medium 224,"# Problem Statement Turtle thinks a string $s$ is a good string if there exists a sequence of strings $t_1, t_2, \ldots, t_k$ ($k$ is an arbitrary integer) such that: - $k \ge 2$. - $s = t_1 + t_2 + \ldots + t_k$, where $+$ represents the concatenation operation. For example, $\texttt{abc} = \texttt{a} + \texttt{bc}$. - For all $1 \le i < j \le k$, the first character of $t_i$ **isn't equal to** the last character of $t_j$. Turtle is given a string $s$ consisting of lowercase Latin letters. Please tell him whether the string $s$ is a good string! The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return ""YES"" if the string s is a good string, and ""NO"" otherwise. # Example 1: - Input: n = 2 s = ""aa"" - Output: NO # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n: int, s: str) -> str: return ""YES"" if s[0] != s[n - 1] else ""NO"" def solve2(self, n: int, s: str) -> str: return ""YES"" if s[0] != s[n - 1] else ""NO"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,string",medium 225,"Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [2,5,6,9,10] Output: 2 Example 2: Input: nums = [7,5,6,8,3] Output: 1 Constraints: 2 <= nums.length <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def gcd(self, a, b): if b == 0: return a return self.gcd(b, a % b) def solve1(self, nums): min_val = 1e9 + 7 max_val = 0 for e in nums: if e < min_val: min_val = e if e > max_val: max_val = e return self.gcd(min_val, max_val) def solve2(self, nums): min_val = nums[0] max_val = nums[0] for i in range(1, len(nums)): e = nums[i] if e < min_val: min_val = e if e > max_val: max_val = e a = min_val b = max_val if a == b: return abs(a) a = abs(a) b = abs(b) if a == 0 and b == 0: return 0 if a == 0: return b if b == 0: return a d = a if a < b else b while d > 0: if a % d == 0 and b % d == 0: return d d -= 1 return 1 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))",math,easy 226,"# Problem Statement Rudolf and Bernard decided to play a game with their friends. $n$ people stand in a circle and start throwing a ball to each other. They are numbered from $1$ to $n$ in the clockwise order. Let's call a transition a movement of the ball from one player to his neighbor. The transition can be made clockwise or counterclockwise. Let's call the clockwise (counterclockwise) distance from player $y_1$ to player $y_2$ the number of transitions clockwise (counterclockwise) that need to be made to move from player $y_1$ to player $y_2$. For example, if $n=7$ then the clockwise distance from $2$ to $5$ is $3$, and the counterclockwise distance from $2$ to $5$ is $4$. Initially, the ball is with the player number $x$ (players are numbered clockwise). On the $i$-th move the person with the ball throws it at a distance of $r_i$ ($1 \le r_i \le n - 1$) clockwise or counterclockwise. For example, if there are $7$ players, and the $2$nd player, after receiving the ball, throws it a distance of $5$, then the ball will be caught by either the $7$th player (throwing clockwise) or the $4$th player (throwing counterclockwise). The game was interrupted after $m$ throws due to unexpected rain. When the rain stopped, the guys gathered again to continue. However, no one could remember who had the ball. As it turned out, Bernard remembered the distances for each of the throws and the direction for **some** of the throws (clockwise or counterclockwise). Rudolf asks you to help him and based on the information from Bernard, calculate the numbers of the players who could have the ball after $m$ throws. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, x, a): pass # write your code here``` where: - `n`: the number of players, `m`: the number of throws, `x`: the initial player with the ball - `a`: the distance and direction of each throw, `a[i].first` represents the distance of the $i$-th throw, `a[i].second` represents the direction of the $i$-th throw, `a[i].second` is '0' for clockwise, '1' for counterclockwise, '?' for unknown - return: the number of players who could have the ball # Example 1: - Input: n = 6, m = 3, x = 2 a = [(2,'?'), (2,'?'), (2,'?')] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $1 \leq m \leq @data$ - $1 \leq x \leq n$ - $1 \leq a[i].first \leq n - 1$ - $a[i].second is '0' or '1' or '?'$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 5000]",4000,"[[500, 64, 64], [4000, 400, 160], [32000, 3200, 1280]]","import collections class Solution: def solve1(self, n, m, x, a): dp = [0] * n x -= 1 dp[x] = 1 for i in range(m): r, c = a[i] g = [0] * n for j in range(n): if dp[j]: if c != '1': g[(j + r) % n] = 1 if c != '0': g[(j - r + n) % n] = 1 dp = g count = 0 for val in dp: if val == 1: count += 1 return count def solve2(self, n, m, x, a): x -= 1 mask = 1 << x full = (1 << n) - 1 for i in range(m): r, c = a[i] r %= n if r == 0: new_mask0 = mask new_mask1 = mask else: new_mask0 = ((mask << r) | (mask >> (n - r))) & full new_mask1 = ((mask >> r) | (mask << (n - r))) & full if c == '0': mask = new_mask0 elif c == '1': mask = new_mask1 else: mask = new_mask0 | new_mask1 return mask.bit_count() ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) x = int(next(it)) a = [] for i in range(m): first = int(next(it)) second = next(it) if second: c = second[0] else: c = '' a.append([first, c]) solution = Solution() result = solution.solve(n, m, x, a) sys.stdout.write(str(result) + ""\n"")","dp,search",medium 227,"Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [a_i, b_i, weight_i] represents a bidirectional and weighted edge between nodes a_i and b_i. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. solution main function ```python class Solution: def solve(self, n, edge): pass # write your code here``` Example 1: Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] Output: [[0,1],[2,3,4,5]] Example 2: Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] Output: [[],[0,1,2,3]] Constraints: 2 <= n <= @data 1 <= edges.length <= min(4*n, n * (n - 1) / 2) edges[i].length == 3 0 <= from_i < to_i < n 1 <= weight_i <= 1000 All pairs (a_i, b_i) are distinct Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def find(self, a): if self.p[a] != a: self.p[a] = self.find(self.p[a]) return self.p[a] def work1(self, n, edges, k): self.p = list(range(n)) cost = 0 cnt = 0 for e in edges: if e[3] == k: continue f1 = self.find(e[1]) f2 = self.find(e[2]) if f1 != f2: cost += e[0] cnt += 1 if cnt == n - 1: break self.p[f1] = f2 if cnt == n - 1: return cost else: return math.inf def work2(self, n, edges, k): self.p = list(range(n)) cost = 0 cnt = 0 for e in edges: if e[3] == k: cost += e[0] cnt += 1 self.p[e[1]] = e[2] break for e in edges: f1 = self.find(e[1]) f2 = self.find(e[2]) if f1 != f2: cost += e[0] cnt += 1 if cnt == n - 1: break self.p[f1] = f2 if cnt == n - 1: return cost else: return math.inf def solve1(self, n, edges): m = len(edges) for i in range(m): edges[i][0], edges[i][2] = edges[i][2], edges[i][0] edges[i].append(i) edges.sort() min_cost = self.work1(n, edges, -1) ans = [[], []] for i in range(m): if self.work1(n, edges, i) > min_cost: ans[0].append(i) elif self.work2(n, edges, i) == min_cost: ans[1].append(i) return ans def solve2(self, n, edges): m = len(edges) for i in range(m): edges[i].append(i) edges.sort(key=lambda e: e[2]) INF = 10**18 def find(parent, a): while parent[a] != a: parent[a] = parent[parent[a]] a = parent[a] return a def mst_exclude(k): parent = list(range(n)) cost = 0 cnt = 0 for e in edges: if e[3] == k: continue u = e[0] v = e[1] ru = find(parent, u) rv = find(parent, v) if ru != rv: parent[ru] = rv cost += e[2] cnt += 1 if cnt == n - 1: break return cost if cnt == n - 1 else INF def mst_include(k): parent = list(range(n)) cost = 0 cnt = 0 found = False for e in edges: if e[3] == k: u = e[0] v = e[1] ru = find(parent, u) rv = find(parent, v) if ru != rv: parent[ru] = rv cost += e[2] cnt += 1 found = True break if not found: return INF for e in edges: u = e[0] v = e[1] ru = find(parent, u) rv = find(parent, v) if ru != rv: parent[ru] = rv cost += e[2] cnt += 1 if cnt == n - 1: break return cost if cnt == n - 1 else INF base = mst_exclude(-1) critical = [] pseudo = [] for i in range(m): if mst_exclude(i) > base: critical.append(i) elif mst_include(i) == base: pseudo.append(i) return [critical, pseudo] ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) edge = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) z = int(next(it)) temp = [] temp.append(x) temp.append(y) temp.append(z) edge.append(temp) solution = Solution() result = solution.solve(n, edge) out_lines = [] for it_res in result: it_res.sort() line_parts = [] for x in it_res: line_parts.append(str(x)) line_parts.append(' ') if line_parts: if line_parts[-1] == ' ': line_parts[-1] = '\n' else: line_parts.append('\n') out_lines.append(''.join(line_parts)) sys.stdout.write(''.join(out_lines))","graph,tree,data_structures",hard 228,"You are given a 0-indexed m x n matrix grid consisting of positive integers. You can start at any cell in the first column of the matrix, and traverse the grid in the following way: From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell. Return the maximum number of moves that you can perform. solution main function ```python class Solution: def solve(self, mat): pass # write your code here``` Example 1: Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] Output: 3 Example 2: Input: grid = [[3,2,4],[2,1,9],[1,1,7]] Output: 0 Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 1000 4 <= m * n <= @data 1 <= grid[i][j] <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math from typing import List class Solution: def solve1(self, grid: List[List[int]]) -> int: M = len(grid) N = len(grid[0]) dp = [[0] * 2 for _ in range(M)] for i in range(M): dp[i][0] = 1 maxMoves = 0 for j in range(1, N): for i in range(M): if grid[i][j] > grid[i][j - 1] and dp[i][0] > 0: dp[i][1] = max(dp[i][1], dp[i][0] + 1) if i - 1 >= 0 and grid[i][j] > grid[i - 1][j - 1] and \ dp[i - 1][0] > 0: dp[i][1] = max(dp[i][1], dp[i - 1][0] + 1) if i + 1 < M and grid[i][j] > grid[i + 1][j - 1] and \ dp[i + 1][0] > 0: dp[i][1] = max(dp[i][1], dp[i + 1][0] + 1) maxMoves = max(maxMoves, dp[i][1] - 1) for k in range(M): dp[k][0] = dp[k][1] dp[k][1] = 0 return maxMoves def solve2(self, grid: List[List[int]]) -> int: M = len(grid) N = len(grid[0]) SHIFT = 21 MASK = (1 << SHIFT) - 1 for i in range(M): grid[i][0] = (grid[i][0] & MASK) + (1 << SHIFT) max_moves = 0 for j in range(1, N): for i in range(M): val = grid[i][j] & MASK best_len = 0 prev = grid[i][j - 1] if val > (prev & MASK): prev_len = prev >> SHIFT if prev_len > 0: cand = prev_len + 1 if cand > best_len: best_len = cand if i - 1 >= 0: prev = grid[i - 1][j - 1] if val > (prev & MASK): prev_len = prev >> SHIFT if prev_len > 0: cand = prev_len + 1 if cand > best_len: best_len = cand if i + 1 < M: prev = grid[i + 1][j - 1] if val > (prev & MASK): prev_len = prev >> SHIFT if prev_len > 0: cand = prev_len + 1 if cand > best_len: best_len = cand grid[i][j] = val + (best_len << SHIFT) if best_len > 0: moves = best_len - 1 if moves > max_moves: max_moves = moves return max_moves","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) mat = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) mat.append(temp) solution = Solution() result = solution.solve(mat) sys.stdout.write(str(result) + ""\n"")",dp,medium 229,"# Problem Statement Given an array $a$ of $n$ integers. Choose as many elements as possible such that the difference between the largest and the smallest chosen elements is at most $5$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum possible number of chosen elements. # Example 1: - Input: n = 6 a = [100, 4, 200, 1, 3, 2] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): ans = 0 a.sort() j = 0 for i in range(n): while j < n and a[j] <= a[i] + 5: j += 1 ans = max(ans, j - i) return ans def solve2(self, n, a): ans = 0 for i in range(n): mn = a[i] hi = mn + 5 cnt = 0 for j in range(n): v = a[j] if v >= mn and v <= hi: cnt += 1 if cnt > ans: ans = cnt return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","sort,two_pointers",hard 230,"You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k. The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket. Return the maximum tastiness of a candy basket. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: price = [13,5,1,8,21,2], k = 3 Output: 8 Example 2: Input: price = [1,3,1], k = 2 Output: 2 Constraints: 2 <= k <= price.length <= @data 1 <= price[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def canweplace(self, stalls, dis, k): cntcows = 1 lastcow = stalls[0] for i in range(len(stalls)): if stalls[i] - lastcow >= dis: cntcows += 1 lastcow = stalls[i] if cntcows == k: return True return False def solve1(self, prices, k): n = len(prices) prices.sort() low = 1 high = prices[n - 1] - prices[0] ans = -1 while low <= high: mid = low + (high - low) // 2 if self.canweplace(prices, mid, k) == True: ans = mid low = mid + 1 else: high = mid - 1 return high def solve2(self, prices, k): n = len(prices) if k <= 1: return 0 prices.sort() best = 0 for i in range(n - 1): if prices[n - 1] - prices[i] <= best: break for j in range(i + 1, n): d = prices[j] - prices[i] if d <= best: continue cnt = 1 last = prices[0] for idx in range(1, n): p = prices[idx] if p - last >= d: cnt += 1 last = p if cnt >= k: break if cnt >= k: best = d return best ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = [] i = 1 while i <= n: x = int(next(it)) s.append(x) i += 1 solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","search,other",medium 231,"You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""aababbab"" Output: 2 Example 2: Input: s = ""bbaaaaabb"" Output: 2 Constraints: 1 <= s.length <= @data s[i] is 'a' or 'b'​​. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, s): n = len(s) min_deletions = 0 b_count = 0 for i in range(n): if s[i] == 'b': b_count += 1 else: min_deletions = min(min_deletions + 1, b_count) return min_deletions def solve2(self, s): n = len(s) best = n for k in range(n + 1): b_left = 0 for i in range(k): if s[i] == 'b': b_left += 1 a_right = 0 for j in range(k, n): if s[j] == 'a': a_right += 1 cost = b_left + a_right if cost < best: best = cost return best ","import sys def main(): data = sys.stdin.read().split() if data: s = data[0] else: s = """" solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","two_pointers,string",medium 232,"# Problem Statement To celebrate his recovery, k1o0n has baked an enormous $n$ metres long potato casserole. Turns out, Noobish\_Monk just can't stand potatoes, so he decided to ruin k1o0n's meal. He has cut it into $k$ pieces, of lengths $a_1, a_2, \dots, a_k$ meters. k1o0n wasn't keen on that. Luckily, everything can be fixed. In order to do that, k1o0n can do one of the following operations: - Pick a piece with length $a_i \ge 2$ and divide it into two pieces with lengths $1$ and $a_i - 1$. As a result, the number of pieces will increase by $1$; - Pick a slice $a_i$ and another slice with length $a_j=1$ ($i \ne j$) and merge them into one piece with length $a_i+1$. As a result, the number of pieces will decrease by $1$. Help k1o0n to find the minimum number of operations he needs to do in order to merge the casserole into one piece with length $n$. For example, if $n=5$, $k=2$ and $a = [3, 2]$, it is optimal to do the following: 1. Divide the piece with length $2$ into two pieces with lengths $2-1=1$ and $1$, as a result $a = [3, 1, 1]$. 2. Merge the piece with length $3$ and the piece with length $1$, as a result $a = [4, 1]$. 3. Merge the piece with length $4$ and the piece with length $1$, as a result $a = [5]$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a): pass # write your code here``` where: - return: the minimum number of operations K1o0n needs to restore his pie after the terror of Noobish_Monk. # Example 1: - Input: n = 5, k = 3, a = [3, 1, 1] - Output: 2 # Constraints: - $2 \leq k \leq @data$ - $1 \leq n \leq 10^9$ - $1 \leq a[i] \leq n - 1$ - $\sum_{i=1}^k a[i] = n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, k, a): max_val = max(a) ans = 2 * (n - max_val) - (k - 1) return ans def solve2(self, n, k, a): max_val = a[0] for v in a: if v > max_val: max_val = v return 2 * (n - max_val) - (k - 1) ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * k for i in range(k): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a) sys.stdout.write(str(result) + ""\n"")",sort,easy 233,"There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The answer is modulus 998244353. solution main function ```python class Solution: def solve(self, n, m): pass # write your code here``` Example 1: Input: m = 3, n = 7 Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Constraints: 1 <= m, n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 1000000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: mod = 998244353 def power(self, x, y): temp = 1 while y: if y & 1: temp = temp * x % self.mod x = x * x % self.mod y >>= 1 return temp def solve1(self, m, n): tx = 1 ty = 1 x = n y_iter = 1 while y_iter < m: tx = tx * x % self.mod ty = ty * y_iter % self.mod x += 1 y_iter += 1 return tx * self.power(ty, self.mod - 2) % self.mod def solve2(self, m, n): t = m + n - 2 b = m - 1 if b > n - 1: b = n - 1 if b <= 0: return 1 num = 1 den = 1 start = t - b + 1 for i in range(b): num = (num * (start + i)) % self.mod den = (den * (i + 1)) % self.mod return (num * pow(den, self.mod - 2, self.mod)) % self.mod","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result))",math,medium 234,"# Problem Statement Turtle and Piggy are playing a game on a sequence. They are given a sequence $a_1, a_2, \ldots, a_n$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.). The game goes as follows: - Let the current length of the sequence be $m$. If $m = 1$, the game ends. - If the game does not end and it's Turtle's turn, then Turtle must choose an integer $i$ such that $1 \le i \le m - 1$, set $a_i$ to $\max(a_i, a_{i + 1})$, and remove $a_{i + 1}$. - If the game does not end and it's Piggy's turn, then Piggy must choose an integer $i$ such that $1 \le i \le m - 1$, set $a_i$ to $\min(a_i, a_{i + 1})$, and remove $a_{i + 1}$. Turtle wants to **maximize** the value of $a_1$ in the end, while Piggy wants to **minimize** the value of $a_1$ in the end. Find the value of $a_1$ in the end if both players play optimally. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the value of a1 in the end if both players play optimally. # Example 1: - Input: n = 2, a = [1, 2] - Output: 2 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): a.sort() return a[n // 2] def solve2(self, n, a): k = n // 2 l = 0 r = n - 1 while l < r: pivot = a[(l + r) // 2] i = l - 1 j = r + 1 while True: i += 1 while a[i] < pivot: i += 1 j -= 1 while a[j] > pivot: j -= 1 if i >= j: break a[i], a[j] = a[j], a[i] if k <= j: r = j else: l = j + 1 return a[k] ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",game,medium 235,"# Problem Statement In the snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\ldots$, $n-2$ and $n-1$, $n-1$ and $0$ are connected with conveyor belts. The $i$-th conveyor belt is in one of three states: - If it is clockwise, snakes can only go from room $i$ to $(i+1) \bmod n$. - If it is anticlockwise, snakes can only go from room $(i+1) \bmod n$ to $i$. - If it is off, snakes can travel in either direction. Each snake wants to leave its room and come back to it later. A room is **returnable** if the snake there can leave the room, and later come back to it using the conveyor belts. How many such **returnable** rooms are there? The main function of the solution is: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - `n` is the number of rooms, - `s` is a string of length $n$ that represents the state of each conveyor belt. If the $i$-th conveyor belt is clockwise, `s[i] = '>'`; if it is counterclockwise, `s[i] = '<'`; if it is off, `s[i] = '-'`. - The return value is the number of returnable rooms. # Example 1 - Input: n = 5 s = "">>>>>"" - Output: 5 # Constraints - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): ans = 0 flaga = True flagb = True for i in range(n): if s[i] != '-': if s[i] == '>': flaga = False if s[i] == '<': flagb = False if flaga or flagb: return n else: for i in range(n): if s[i] == '-' or s[(i + 1) % n] == '-': ans += 1 return ans def solve2(self, n, s): has_right = False has_left = False for i in range(n): if s[i] == '>': has_right = True elif s[i] == '<': has_left = True if not has_right or not has_left: return n ans = 0 for i in range(n): if s[i] == '-' or s[(i + 1) % n] == '-': ans += 1 return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")",graph,hard 236,"Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""zzazz"" Output: 0 Example 2: Input: s = ""mbadm"" Output: 2 Constraints: 1 <= s.length <= @data s consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections import heapq import math class Solution: def lcs(self, s1, s2, m, n): dp = [0] * (n + 1) dpPrev = [0] * (n + 1) for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: dp[j] = 0 elif s1[i - 1] == s2[j - 1]: dp[j] = 1 + dpPrev[j - 1] else: dp[j] = max(dpPrev[j], dp[j - 1]) dpPrev = list(dp) return dp[n] def solve1(self, s): n = len(s) sReverse = s[::-1] return n - self.lcs(s, sReverse, n, n) def solve2(self, s): n = len(s) best = 0 limit = 1 << n for mask in range(limit): cnt = 0 m = mask while m: m &= m - 1 cnt += 1 if cnt <= best: continue i = 0 j = n - 1 ok = True pairs = 0 while i < j: while i < j and ((mask >> i) & 1) == 0: i += 1 while i < j and ((mask >> j) & 1) == 0: j -= 1 if i < j: if s[i] != s[j]: ok = False break pairs += 2 i += 1 j -= 1 if ok: length = pairs if i == j and ((mask >> i) & 1): length += 1 if length > best: best = length return n - best ","import sys def main(): data = sys.stdin.read().split() if not data: s = """" else: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",string,medium 237,"Given a permutation of length n, find the MTH permutation after it solution main function ```python class Solution: def solve(self, n, m, num): pass # write your code here``` Pass in parameters: 2 integers n,m and an array num Return parameters: Modify `num` in place to become the m-th next permutation after the given permutation. The returned array is not used by the runner. Example 1: Input: n=5,m=3,num=[1, 2, 3, 4, 5] Output: [1, 2, 4, 5, 3] Constraints: 0= 0 and num[i] >= num[i + 1]: i -= 1 if i < 0: num.reverse() continue j = n - 1 while j > i and num[j] <= num[i]: j -= 1 num[i], num[j] = num[j], num[i] left, right = i + 1, n - 1 while left < right: num[left], num[right] = num[right], num[left] left += 1 right -= 1 return num def solve2(self, n, m, num): for _ in range(m): i = n - 2 while i >= 0 and num[i] >= num[i + 1]: i -= 1 if i < 0: left, right = 0, n - 1 while left < right: num[left], num[right] = num[right], num[left] left += 1 right -= 1 continue j = n - 1 while j > i and num[j] <= num[i]: j -= 1 num[i], num[j] = num[j], num[i] left, right = i + 1, n - 1 while left < right: num[left], num[right] = num[right], num[left] left += 1 right -= 1 return num ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(n, m, num) out = [] for v in num: out.append(str(v)) sys.stdout.write("" "".join(out))",STL,medium 238,"You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. If k > 0, replace the ith number with the sum of the next k numbers. If k < 0, replace the ith number with the sum of the previous k numbers. If k == 0, replace the ith number with 0. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! solution main function ```python class Solution: def solve(self, a, k): pass # write your code here``` Example 1: Input: code = [5,7,1,4], k = 3 Output: [12,10,16,13] Example 2: Input: code = [1,2,3,4], k = 0 Output: [0,0,0,0] Constraints: n == code.length 1 <= n <= @data 1 <= code[i] <= @data -(n - 1) <= k <= n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, code, k): n = len(code) ans = [0] * n if k == 0: return ans start = 0 end = 0 step = 0 if k > 0: start = 1 end = k + 1 step = 1 else: start = -1 end = k - 1 step = -1 for i in range(n): current_sum = 0 for j in range(start, end, step): current_sum += code[(i + j) % n] ans[i] = current_sum return ans def solve2(self, code, k): n = len(code) ans = [0] * n if k == 0: return ans if k > 0: start, end, step = 1, k + 1, 1 else: start, end, step = -1, k - 1, -1 for i in range(n): s = 0 for j in range(start, end, step): s += code[(i + j) % n] ans[i] = s return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(a, k) out = [] for it2 in result: out.append(str(it2)) sys.stdout.write("" "".join(out))",math,easy 239,"# Problem Statement Vasya has two hobbies — adding permutations$^{\dagger}$ to arrays and finding the most frequently occurring element. Recently, he found an array $a$ and decided to find out the maximum number of elements equal to the same number in the array $a$ that he can obtain after adding some permutation to the array $a$. More formally, Vasya must choose exactly one permutation $p_1, p_2, p_3, \ldots, p_n$ of length $n$, and then change the elements of the array $a$ according to the rule $a_i := a_i + p_i$. After that, Vasya counts how many times each number occurs in the array $a$ and takes the maximum of these values. You need to determine the maximum value he can obtain. $^{\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the maximum value he can obtain # Example 1: - Input: n = 2 a = [1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): if not a: return 0 a.sort() unique_a = [a[0]] for i in range(1, len(a)): if a[i] != a[i-1]: unique_a.append(a[i]) ans = 0 j = 0 size = len(unique_a) for i in range(size): while j < size and unique_a[j] < unique_a[i] + n: j += 1 ans = max(ans, j - i) return ans def solve2(self, n, a): if not a or n <= 0: return 0 a.sort() ans = 0 ui = 0 uj = 0 count = 0 length = len(a) while ui < length: if uj < ui: uj = ui count = 0 left_val = a[ui] while uj < length and a[uj] < left_val + n: count += 1 v = a[uj] uj += 1 while uj < length and a[uj] == v: uj += 1 if count > ans: ans = count v = a[ui] ui += 1 while ui < length and a[ui] == v: ui += 1 count -= 1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary,greedy,sort",hard 240,"You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matches played in the tournament until a winner is decided. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 7 Output: 6 Example 2: Input: n = 14 Output: 13 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, n: int) -> int: return n - 1 def solve2(self, n: int) -> int: matches = 0 while n > 1: if (n & 1) == 0: matches += n >> 1 n >>= 1 else: matches += (n - 1) >> 1 n = ((n - 1) >> 1) + 1 return matches ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,easy 241,"Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]] Constraints: 1 <= nums.length <= @data -100 <= nums[i] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[5, 10, 15]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: def dfs(self, cur, last, nums): if cur == len(nums): if len(self.temp) >= 2: self.ans.append(list(self.temp)) return if nums[cur] >= last: self.temp.append(nums[cur]) self.dfs(cur + 1, nums[cur], nums) self.temp.pop() if nums[cur] != last: self.dfs(cur + 1, last, nums) def solve1(self, nums): self.ans = [] self.temp = [] self.dfs(0, -math.inf, nums) return self.ans def solve2(self, nums): n = len(nums) ans = [] if n < 2: return ans path = [] starts = [0] while True: depth = len(path) if starts[depth] >= n: if depth == 0: break last_i = path.pop() starts[len(path)] = last_i + 1 continue s = starts[depth] base_start = (path[-1] + 1) if path else 0 prev_val = nums[path[-1]] if path else None i = s found = False while i < n: v = nums[i] if prev_val is None or v >= prev_val: j = base_start dup = False while j < i: if nums[j] == v: dup = True break j += 1 if not dup: found = True break i += 1 if not found: starts[depth] = n continue path.append(i) starts[depth] = i + 1 if len(starts) == len(path): starts.append(i + 1) else: starts[len(path)] = i + 1 if len(path) >= 2: ans.append([nums[k] for k in path]) return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) result = sorted(result) out_lines = [] for it_item in result: line_parts = [] for t in it_item: line_parts.append(str(t)) out_lines.append("" "".join(line_parts)) sys.stdout.write(""\n"".join(out_lines))",bit_manipulation,medium 242,"The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. For example, ""ACGAATTCCG"" is a DNA sequence. When studying DNA, it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. solution main function ```python class Solution: def solve(self, str_var): pass # write your code here``` Example 1: Input: s = ""AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"" Output: [""AAAAACCCCC"",""CCCCCAAAAA""] Example 2: Input: s = ""AAAAAAAAAAAAA"" Output: [""AAAAAAAAAA""] Constraints: 1 <= s.length <= @data s[i] is either 'A', 'C', 'G', or 'T'. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[2000, 1000, 546], [16000, 8000, 4375], [128000, 64000, 35000]]","import collections class Solution: def solve(self, s: str): L = 10 bin_map = {'A': 0, 'C': 1, 'G': 2, 'T': 3} ans = [] n = len(s) if n <= L: return ans x = 0 for i in range(L - 1): x = (x << 2) | bin_map[s[i]] cnt = {} for i in range(n - L + 1): x = ((x << 2) | bin_map[s[i + L - 1]]) & ((1 << (L * 2)) - 1) cnt[x] = cnt.get(x, 0) + 1 if cnt[x] == 2: ans.append(s[i : i + L]) return ans ","import sys def main(): data = sys.stdin.read().split() if not data: return str_var = data[0] solution = Solution() result = solution.solve(str_var) out = [] result = sorted(result) for it in result: out.append(str(it)) sys.stdout.write("" "".join(out)) if __name__ == ""__main__"": main()","string,bit_manipulation",medium 243,"Given a 2D grid of size m x n, you should find the matrix answer of size m x n. The cell answer[r][c] is calculated by looking at the diagonal values of the cell grid[r][c]: Let leftAbove[r][c] be the number of distinct values on the diagonal to the left and above the cell grid[r][c] not including the cell grid[r][c] itself. Let rightBelow[r][c] be the number of distinct values on the diagonal to the right and below the cell grid[r][c], not including the cell grid[r][c] itself. Then answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|. A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached. For example, in the below diagram the diagonal is highlighted using the cell with indices (2, 3) colored gray: Red-colored cells are left and above the cell. Blue-colored cells are right and below the cell. solution main function ```python class Solution: def solve(self, grid): pass # write your code here``` Example 1: Input: grid = [[1,2,3],[3,1,5],[3,2,1]] Output: [[1,1,0],[1,0,1],[0,1,1]] Example 2: Input: grid = [[1]] Output: [[0]] Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data 1 <= grid[i][j] <= 50 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 500]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, grid): width = len(grid[0]) length = len(grid) for i in range(width): elementMap = {} self.makeElementMap(elementMap, grid, 0, i) left = 0 right = len(elementMap) j = 0 while (i + j < width) and (j < length): element = grid[j][i + j] position = elementMap[element] if position[1] == j: right -= 1 grid[j][i + j] = abs(left - right) if position[0] == j: left += 1 j += 1 for i in range(1, length): elementMap = {} self.makeElementMap(elementMap, grid, i, 0) left = 0 right = len(elementMap) j = 0 while (i + j < length) and (j < width): element = grid[i + j][j] position = elementMap[element] if position[1] == j: right -= 1 grid[i + j][j] = abs(left - right) if position[0] == j: left += 1 j += 1 return grid def solve2(self, grid): m = len(grid) n = len(grid[0]) if m > 0 else 0 BASE = 1024 def original_value(x): return x % BASE for r in range(m): for c in range(n): left_count = 0 max_left = min(r, c) for d in range(1, max_left + 1): v = original_value(grid[r - d][c - d]) found = False for e in range(1, d): if original_value(grid[r - e][c - e]) == v: found = True break if not found: left_count += 1 right_count = 0 max_right = min(m - 1 - r, n - 1 - c) for d in range(1, max_right + 1): v = original_value(grid[r + d][c + d]) found = False for e in range(1, d): if original_value(grid[r + e][c + e]) == v: found = True break if not found: right_count += 1 diff = left_count - right_count if diff < 0: diff = -diff grid[r][c] = original_value(grid[r][c]) + diff * BASE for r in range(m): for c in range(n): grid[r][c] = grid[r][c] // BASE return grid def makeElementMap(self, elementMap, grid, startX, startY): offset = 0 length = len(grid) width = len(grid[0]) while (startX + offset < length) and (startY + offset < width): element = grid[startX + offset][startY + offset] if element not in elementMap: elementMap[element] = [offset, offset] else: elementMap[element][1] = offset offset += 1 ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) out_lines = [] for s_row in result: line_parts = [] for it_val in s_row: line_parts.append(str(it_val)) line_parts.append(' ') out_lines.append(''.join(line_parts).rstrip() + '\n') sys.stdout.write(''.join(out_lines))",other,medium 244,"# Problem Statement On another boring day, Egor got bored and decided to do something. But since he has no friends, he came up with a game to play. Egor has a deck of $n$ cards, the $i$-th card from the top has a number $a_i$ written on it. Egor wants to play a certain number of rounds until the cards run out. In each round, he takes a non-zero number of cards from the top of the deck and finishes the round. If the sum of the numbers on the cards collected during the round is between $l$ and $r$, inclusive, the round is won; otherwise, it is lost. Egor knows by heart the order of the cards. Help Egor determine the maximum number of rounds he can win in such a game. Note that Egor is not required to win rounds consecutively. The main function of the solution is defined as: ```python class Solution: def solve(self, n, l, r, a): pass # write your code here``` where: - the return value is the maximum number of rounds Egor can win # Example 1: - Input: n = 5, l = 3, r = 10 a = [2, 1, 11, 3, 7] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq l \leq r \leq 10^9$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 450, 80], [32000, 3600, 640]]","import collections class Solution: def solve1(self, n, l, r, a): start = 0 current_sum = 0 max_rounds = 0 for end in range(n): current_sum += a[end] while current_sum > r and start <= end: current_sum -= a[start] start += 1 if current_sum >= l and current_sum <= r: max_rounds += 1 current_sum = 0 start = end + 1 return max_rounds def solve2(self, n, l, r, a): i = 0 ans = 0 while i < n: s = 0 j = i while j < n and s < l: s += a[j] j += 1 if l <= s <= r: ans += 1 i = j else: i += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) l = int(next(it)) r = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, l, r, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,dp,math",hard 245,"There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree. You are also given a positive integer k, and a 0-indexed array of non-negative integers nums of length n, where nums[i] represents the value of the node numbered i. Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the following operation any number of times (including zero) on the tree: Choose any edge [u, v] connecting the nodes u and v, and update their values as follows: nums[u] = nums[u] XOR k nums[v] = nums[v] XOR k Return the maximum possible sum of the values Alice can achieve by performing the operation any number of times. solution main function ```python class Solution: def solve(self, num, k, e): pass # write your code here``` Example 1: Input: nums = [1,2,1], k = 3, edges = [[0,1],[0,2]] Output: 6 Example 2: Input: nums = [2,3], k = 7, edges = [[0,1]] Output: 9 Constraints: 2 <= n == nums.length <= @data 1 <= k <= 10^9 0 <= nums[i] <= 10^9 edges.length == n - 1 edges[i].length == 2 0 <= edges[i][0], edges[i][1] <= n - 1 The input is generated such that edges represent a valid tree. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums, k, edges): sum = 0 cnt = 0 sacrificeVal = float('inf') for ele in nums: if (ele ^ k) > ele: sum += (ele ^ k) sacrificeVal = min(sacrificeVal, (ele ^ k) - ele) cnt += 1 else: sum += ele sacrificeVal = min(sacrificeVal, ele - (ele ^ k)) if cnt & 1: return sum - sacrificeVal return sum def solve2(self, nums, k, edges): total = 0 cnt = 0 min_diff = 1 << 61 for a in nums: b = a ^ k if b > a: total += b cnt += 1 diff = b - a if diff < min_diff: min_diff = diff else: total += a diff = a - b if diff < min_diff: min_diff = diff if cnt & 1: total -= min_diff return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) e = [] for i in range(1, n): temp = [] for j in range(1, 2 + 1): x = int(next(it)) temp.append(x) e.append(temp) solution = Solution() result = solution.solve(num, k, e) sys.stdout.write(str(result))","sort,greedy,tree,bit_manipulation",hard 246,"There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. solution main function ```python class Solution: def solve(self, n, m): pass # write your code here``` Example 1: Input: numBottles = 9, numExchange = 3 Output: 13 Example 2: Input: numBottles = 15, numExchange = 4 Output: 19 Constraints: 1 <= numBottles <= @data 2 <= numExchange <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, numBottles, numExchange): consumedBottles = 0 while numBottles >= numExchange: K = numBottles // numExchange consumedBottles += numExchange * K numBottles -= numExchange * K numBottles += K return consumedBottles + numBottles def solve2(self, numBottles, numExchange): total = 0 empty = 0 full = numBottles while full > 0: total += full empty += full full = empty // numExchange empty = empty % numExchange return total ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result) + ""\n"")",math,easy 247,"# Problem Statement You have just learned bubble sort, which sorts an array in non-decreasing order. Define the function sort(a) as the number of rounds bubble sort performs until the array is sorted. For a permutation p of length n, define b_i = sort([p_1, p_2, ..., p_i]) for each 1 ≤ i ≤ n. You are given m constraints (k_j, l_j, r_j). For each constraint, let x be the number of indices y (1 ≤ y ≤ n) such that b_y ≤ k_j. It must hold that l_j ≤ x ≤ r_j. Count the number of permutations p satisfying all constraints, modulo 998244353. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, cons): pass # write your code here``` where: - `constraints[i] = {k_i, l_i, r_i}` with 0 ≤ k_i ≤ n-1 and 1 ≤ l_i ≤ r_i ≤ n. - return: number of valid permutations modulo 998244353. # Example: - Input: - n = 4, m = 3 - constraints = [(0,1,1), (1,3,3), (2,4,4)] - Output: - 2 # Constraints: - $2 \leq n \leq @data$ - $0 \leq m \leq 1000$ - $0 \leq k_i \leq n-1$ - $1 \leq l_i \leq r_i \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[2000, 100000, 1000000]",4000,"[[2500, 1250, 750], [20000, 10000, 6000], [160000, 80000, 48000]]","import bisect class Solution: MOD = 998244353 fac = [1] initedUpTo = 0 @classmethod def qpow(cls, a, b): base = a % cls.MOD res = 1 while b > 0: if b & 1: res = (res * base) % cls.MOD base = (base * base) % cls.MOD b >>= 1 return res @classmethod def ensure(cls, needN): if needN <= cls.initedUpTo: return current_len = len(cls.fac) if needN >= current_len: cls.fac.extend([0] * (needN + 1 - current_len)) start = max(1, cls.initedUpTo + 1) for i in range(start, needN + 1): cls.fac[i] = (cls.fac[i - 1] * i) % cls.MOD cls.initedUpTo = needN @classmethod def qry1(cls, l, r, k, invL): if l > r: return 1 if k < l: return cls.qpow(k + 1, r - l + 1) if k > r: cls.ensure(r + 1) return (cls.fac[r + 1] * invL) % cls.MOD cls.ensure(max(k + 1, l)) part = (cls.fac[k + 1] * invL) % cls.MOD powPart = cls.qpow(k + 1, r - k) return (part * powPart) % cls.MOD @classmethod def qry2(cls, l, r, k, x, invL): A = cls.qry1(l, r, k, invL) B = cls.qry1(l, r, x, invL) C = A - B if C < 0: C += cls.MOD return C def solve1(self, n, m, constraints): cls = self.__class__ a = [] v = [] tvals = [] for i in range(m): k, l, r = constraints[i] l -= 1 if l >= 0: v.append(l) if r < n: v.append(r) tvals.append(k) a.append({'l': l, 'r': r, 'k': k}) v.append(n - 1) tvals.extend([-1, n - 1]) v = sorted(list(set(v))) tvals = sorted(list(set(tvals))) V = len(v) T = len(tvals) r1 = [T - 1] * V r2 = [0] * V for it in a: if it['k'] == n - 1 and it['r'] < n - 1: return 0 idx = bisect.bisect_left(tvals, it['k']) if it['l'] >= 0: posIdx = bisect.bisect_left(v, it['l']) r1[posIdx] = min(r1[posIdx], idx) if it['r'] < n: posIdx = bisect.bisect_left(v, it['r']) r2[posIdx] = max(r2[posIdx], idx) dp = [0] * (T + 2) dp[1] = 1 lastL = 0 for i in range(V): pos = v[i] cls.ensure(lastL) invL = cls.qpow(cls.fac[lastL], cls.MOD - 2) pref = [0] * (T + 2) for j in range(1, T): s = pref[j - 1] + dp[j] if s >= cls.MOD: s -= cls.MOD pref[j] = s ndp = [0] * (T + 2) r1v = r1[i] r2v = r2[i] for j in range(1, T): if j > r2v and j <= r1v: left = (dp[j] * cls.qry1(lastL, pos, tvals[j], invL)) % cls.MOD right = (pref[j - 1] * cls.qry2(lastL, pos, tvals[j], tvals[j - 1], invL)) % cls.MOD s = left + right if s >= cls.MOD: s -= cls.MOD ndp[j] = s else: ndp[j] = 0 dp = ndp lastL = pos + 1 ans = 0 for j in range(1, T + 1): s = ans + dp[j] if s >= cls.MOD: s -= cls.MOD ans = s return ans def solve2(self, n, m, constraints): for i in range(m): k, l, r = constraints[i] base = k + 1 if base > n: base = n if base > r: return 0 if m == 0: res = 1 mod = self.MOD for i in range(2, n + 1): res = (res * i) % mod return res p = [i + 1 for i in range(n)] ans = 0 while True: valid_perm = True for idx in range(m): k, l, r = constraints[idx] base = k + 1 if base > n: base = n if base == n: continue count = base y = base + 1 while y <= n: if count + (n - y + 1) < l: valid_perm = False break maxd = 0 j = 0 while j < y: less = 0 t = 0 vj = p[j] while t < y: if p[t] < vj: less += 1 t += 1 d = j - less if d > maxd: maxd = d if maxd > k: break j += 1 if maxd <= k: count += 1 if count > r: valid_perm = False break y += 1 if not valid_perm: break if count < l: valid_perm = False break if valid_perm: ans += 1 if ans >= self.MOD: ans -= self.MOD i = n - 2 while i >= 0 and p[i] >= p[i + 1]: i -= 1 if i < 0: break j = n - 1 while p[j] <= p[i]: j -= 1 p[i], p[j] = p[j], p[i] a = i + 1 b = n - 1 while a < b: p[a], p[b] = p[b], p[a] a += 1 b -= 1 return ans % self.MOD","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) cons = [None] * m for i in range(m): k = int(next(it)) l = int(next(it)) r = int(next(it)) cons[i] = [k, l, r] solution = Solution() result = solution.solve(n, m, cons) sys.stdout.write(str(result) + ""\n"")","dp,math",hard 248,"Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive) solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [0,2,1,5,3,4] Output: [0,1,2,4,5,3] Example 2: Input: nums = [5,0,1,2,3,4] Output: [4,5,0,1,2,3] Constraints: 1 <= nums.length <= @data 0 <= nums[i] < nums.length The elements in nums are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","from typing import * class Solution: def solve1(self, nums: List[int]) -> List[int]: answer = [0] * len(nums) for i in range(len(nums)): answer[i] = nums[nums[i]] return answer def solve2(self, nums: List[int]) -> List[int]: n = len(nums) for i in range(n): nums[i] += n * (nums[nums[i] % n] % n) for i in range(n): nums[i] //= n return nums","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) out = [] for item in result: out.append(str(item)) sys.stdout.write("" "".join(out))",other,easy 249,"You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]] Output: 6 Example 2: Input: rectangles = [[0,0,1000000000,1000000000]] Output: 49 Constraints: 1 <= rectangles.length <= @data rectanges[i].length == 4 0 <= xi1, yi1, xi2, yi2 <= 10^9 xi1 <= xi2 yi1 <= yi2 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections class Solution: def func(self, intervals): if not intervals: return 0 sorted_intervals = sorted(intervals) area = 0 prev = -1 for it in sorted_intervals: height = max(0, it[1] - max(prev, it[0])) area += height prev = max(prev, it[1]) return area def solve1(self, rectangles): MOD = 10**9 + 7 lines = [] for rect in rectangles: lines.append([rect[0], 0, rect[1], rect[3]]) lines.append([rect[2], 1, rect[1], rect[3]]) if not lines: return 0 lines.sort() prev_x = lines[0][0] total_area = 0 intervals = [] for line in lines: width = line[0] - prev_x if width > 0: height = self.func(intervals) total_area += width * height interval_to_process = (line[2], line[3]) if line[1] == 1: if interval_to_process in intervals: intervals.remove(interval_to_process) else: intervals.append(interval_to_process) prev_x = line[0] return total_area % MOD def solve2(self, rectangles): MOD = 10**9 + 7 n = len(rectangles) if n == 0: return 0 current_x = rectangles[0][0] for r in rectangles[1:]: if r[0] < current_x: current_x = r[0] total_area = 0 while True: next_x = None for r in rectangles: x1 = r[0] x2 = r[2] if x1 > current_x and (next_x is None or x1 < next_x): next_x = x1 if x2 > current_x and (next_x is None or x2 < next_x): next_x = x2 if next_x is None: break dx = next_x - current_x if dx > 0: have_cur = False cur_lo = 0 cur_hi = 0 total_h = 0 prev_y1 = None prev_y2 = None while True: have_candidate = False cand_a = 0 cand_b = 0 for r in rectangles: if r[0] <= current_x and r[2] > current_x: a = r[1] b = r[3] if prev_y1 is None or a > prev_y1 or (a == prev_y1 and b > prev_y2): if not have_candidate: cand_a = a cand_b = b have_candidate = True else: if a < cand_a or (a == cand_a and b < cand_b): cand_a = a cand_b = b if not have_candidate: break if not have_cur: have_cur = True cur_lo = cand_a cur_hi = cand_b else: if cand_a > cur_hi: if cur_hi > cur_lo: total_h += (cur_hi - cur_lo) cur_lo = cand_a cur_hi = cand_b else: if cand_b > cur_hi: cur_hi = cand_b prev_y1 = cand_a prev_y2 = cand_b if have_cur and cur_hi > cur_lo: total_h += (cur_hi - cur_lo) total_area += dx * total_h current_x = next_x return total_area % MOD ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, 5): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")",data_structures,hard 250,"# Problem Statement Freya the Frog is traveling on the 2D coordinate plane. She is currently at point $(0,0)$ and wants to go to point $(x,y)$. In one move, she chooses an integer $d$ such that $0 \leq d \leq k$ and jumps $d$ spots forward in the direction she is facing. Initially, she is facing the positive $x$ direction. After every move, she will alternate between facing the positive $x$ direction and the positive $y$ direction (i.e., she will face the positive $y$ direction on her second move, the positive $x$ direction on her third move, and so on). What is the minimum amount of moves she must perform to land on point $(x,y)$? The main function of the solution is defined as: ```python class Solution: def solve(self, x, y, k): pass # write your code here``` where: - return: the number of jumps Freya needs to make on a new line. # Example 1: - Input: x = 9, y = 11, k = 3 - Output: 8 # Constraints: - $0 \leq x, y \leq @data$ - $1 \leq k \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, x, y, k): x = (x + k - 1) // k y = (y + k - 1) // k return max(2 * x - 1, 2 * y) def solve2(self, x, y, k): m = 0 turn_x = True while x > 0 or y > 0: if turn_x: if x > 0: x -= min(k, x) else: if y > 0: y -= min(k, y) m += 1 turn_x = not turn_x return m ","import sys data = sys.stdin.read().strip().split() x = int(data[0]) y = int(data[1]) k = int(data[2]) solution = Solution() result = solution.solve(x, y, k) sys.stdout.write(str(result) + ""\n"")",math,medium 251,"# Problem Statement Anya lives in the Flower City. By order of the city mayor, she has to build a fence for herself. The fence consists of $n$ planks, each with a height of $a_i$ meters. According to the order, the heights of the planks must **not increase**. In other words, it is true that $a_i \ge a_j$ for all $i < j$. Anya became curious whether her fence is symmetrical with respect to the diagonal. In other words, will she get the same fence if she lays all the planks horizontally in the same order. Help Anya and determine whether her fence is symmetrical. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return ""YES"" if the fence is symmetrical, otherwise return ""NO"". # Example 1: - Input: n = 5 a = [5, 4, 3, 2, 1] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - $a$ is non-increasing - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): j = n for i in range(n): while j > 0 and a[j - 1] <= i: j -= 1 if a[i] != j: return ""NO"" return ""YES"" def solve2(self, n, a): for i in range(n): threshold = i + 1 cnt = 0 for j in range(n): if a[j] >= threshold: cnt += 1 else: break if a[i] != cnt: return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",sort,medium 252,"# Problem Statement You are given a sequence $a$, consisting of $n$ integers, where the $i$-th element of the sequence is equal to $a_i$. You are also given two integers $x$ and $y$ ($x \le y$). A pair of integers $(i, j)$ is considered interesting if the following conditions are met: - $1 \le i < j \le n$; - if you simultaneously remove the elements at positions $i$ and $j$ from the sequence $a$, the sum of the remaining elements is at least $x$ and at most $y$. Your task is to determine the number of interesting pairs of integers for the given sequence $a$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, x, y, a): pass # write your code here``` where: - return: the number of interesting pairs of integers, please use `long long` type to avoid overflow # Example 1: - Input: n = 4, x = 8, y = 10 a = [4, 6, 3, 6] - Output: 4 # Constraints: - $3 \leq n \leq @data$ - $1 \leq x \leq y \leq 10^14$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, x, y, a): s = 0 for val in a: s += val a.sort() res = 0 l = 0 r = 0 for i in range(n - 1, -1, -1): while r < i and s - a[i] - a[r] >= x: r += 1 while l < r and s - a[l] - a[i] > y: l += 1 if l >= i: break res += min(r, i) - l return res def solve2(self, n, x, y, a): total = 0 for v in a: total += v res = 0 for i in range(n - 1): ai = a[i] for j in range(i + 1, n): s2 = total - ai - a[j] if x <= s2 <= y: res += 1 return res ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) x = int(next(it)) y = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, x, y, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary,sort",medium 253,"# Problem Statement You are given a cyclic array $a_1, a_2, \ldots, a_n$. You can perform the following operation on $a$ at most $n - 1$ times: - Let $m$ be the current size of $a$, you can choose any two adjacent elements where the previous one is no greater than the latter one (In particular, $a_m$ and $a_1$ are adjacent and $a_m$ is the previous one), and delete exactly one of them. In other words, choose an integer $i$ ($1 \leq i \leq m$) where $a_i \leq a_{(i \bmod m) + 1}$ holds, and delete exactly one of $a_i$ or $a_{(i \bmod m) + 1}$ from $a$. Your goal is to find the minimum number of operations needed to make all elements in $a$ equal. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the minimum number of operations needed to make all elements in a equal. # Example 1: - Input: n = 3, a = [1, 2, 3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): a.sort() ans = 0 res = 0 if n > 0: zhi = a[0] for i in range(n): if a[i] == zhi: res += 1 else: ans = max(ans, res) zhi = a[i] res = 1 ans = max(ans, res) return n - ans def solve2(self, n, a): if n <= 1: return 0 maxcnt = 0 for i in range(n): v = a[i] seen = False for k in range(i): if a[k] == v: seen = True break if seen: continue cnt = 0 for j in range(n): if a[j] == v: cnt += 1 if cnt > maxcnt: maxcnt = cnt return n - maxcnt ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",sort,easy 254,"You are given an array nums consisting of positive integers. We call a subarray of an array complete if the following condition is satisfied: The number of distinct elements in the subarray is equal to the number of distinct elements in the whole array. Return the number of complete subarrays. A subarray is a contiguous non-empty part of an array. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [1,3,1,2,2] Output: 4 Example 2: Input: nums = [5,5,5,5] Output: 10 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 2000 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, nums): all = collections.Counter(nums) mp = collections.defaultdict(int) front = 0 back = 0 ans = 0 while front < len(nums): mp[nums[front]] += 1 while len(mp) == len(all): ans += len(nums) - front mp[nums[back]] -= 1 if mp[nums[back]] == 0: del mp[nums[back]] back += 1 front += 1 return ans def solve2(self, nums): n = len(nums) total_distinct = 0 for i in range(n): duplicate = False for j in range(i): if nums[j] == nums[i]: duplicate = True break if not duplicate: total_distinct += 1 ans = 0 for i in range(n): distinct = 0 for j in range(i, n): is_new = True for k in range(i, j): if nums[k] == nums[j]: is_new = False break if is_new: distinct += 1 if distinct == total_distinct: ans += n - j break return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))",other,medium 255,"You are given three positive integers n, x, and y. In a city, there exist houses numbered 1 to n connected by n streets. There is a street connecting the house numbered i with the house numbered i + 1 for all 1 <= i <= n - 1 . An additional street connects the house numbered x with the house numbered y. For each k, such that 1 <= k <= n, you need to find the number of ordered pairs of distinct houses (house1, house2) such that the minimum number of streets that need to be traveled to reach house2 from house1 is k. Return an array result of length n where result[k - 1] represents the total number of ordered pairs of distinct houses such that the minimum streets required to reach one house from the other is k. Note that x and y can be equal. solution main function ```python class Solution: def solve(self, n, x, y): pass # write your code here``` Example 1: Input: n = 3, x = 1, y = 3 Output: [6,0,0] Example 2: Input: n = 5, x = 2, y = 4 Output: [10,8,2,0,0] Constraints: 2 <= n <= @data 1 <= x, y <= n Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math from typing import List class Solution: def solve1(self, n: int, x: int, y: int) -> List[int]: if x > y: x, y = y, x res = [0] * n for i in range(1, n + 1): for j in range(1, i): idx = i - j idx = min(idx, abs(j - x) + 1 + abs(i - y)) if idx >= 1: res[idx - 1] += 2 return res def solve2(self, n, x, y): if x > y: x, y = y, x res = [0] * n for i in range(1, n + 1): j = 1 while j < i: d = i - j t = abs(i - x) + 1 + abs(j - y) if t < d: d = t t = abs(i - y) + 1 + abs(j - x) if t < d: d = t res[d - 1] += 2 j += 1 return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) x = 0 y = 0 n = 0 n = int(next(it)) x = int(next(it)) y = int(next(it)) solution = Solution() result = solution.solve(n, x, y) out = [] for v in result: out.append(str(v)) out.append(' ') sys.stdout.write(''.join(out))","graph,search",medium 256,"# Problem Statement You are given an array $a$ of length $n$. In one operation, you can pick an index $i$ from $2$ to $n-1$ inclusive, and do one of the following actions: - Decrease $a_{i-1}$ by $1$, then increase $a_{i+1}$ by $1$. - Decrease $a_{i+1}$ by $1$, then increase $a_{i-1}$ by $1$. After each operation, all the values must be non-negative. Can you make all the elements equal after any number of operations? The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return ""YES"" without quotation marks if it is possible to make all the elements equal after any number of operations; otherwise, return ""NO"" without quotation marks. # Example 1: - Input: n = 3, a = [3, 2, 1] - Output: YES # Constraints: - $3 \leq n \leq @data$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): s1 = 0 s2 = 0 for i in range(n): if i % 2 == 0: s1 += a[i] else: s2 += a[i] c1 = (n + 1) // 2 c2 = n // 2 if c1 > 0 and c2 > 0: if s1 % c1 == 0 and s2 % c2 == 0 and s1 // c1 == s2 // c2: return ""YES"" else: return ""NO"" elif c1 > 0: if s1 % c1 == 0: return ""YES"" else: return ""NO"" elif c2 > 0: if s2 % c2 == 0: return ""YES"" else: return ""NO"" else: return ""YES"" def solve2(self, n, a): total = 0 s1 = 0 s2 = 0 for i in range(n): v = a[i] total += v if (i & 1) == 0: s1 += v else: s2 += v if n == 0: return ""YES"" if total % n != 0: return ""NO"" x = total // n c1 = (n + 1) // 2 c2 = n // 2 if s1 == c1 * x and s2 == c2 * x: return ""YES"" return ""NO"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,medium 257,"# Problem Statement Petya organized a strange birthday party. He invited $n$ friends and assigned an integer $k_i$ to the $i$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $m$ unique presents available, the $j$-th present costs $c_j$ dollars ($1 \le c_1 \le c_2 \le \ldots \le c_m$). It's **not** allowed to buy a single present more than once. For the $i$-th friend Petya can either buy them a present $j \le k_i$, which costs $c_j$ dollars, or just give them $c_{k_i}$ dollars directly. Help Petya determine the minimum total cost of hosting his party. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, c): pass # write your code here``` where: - return: the minimum total cost of hosting the party, please use `long long` to avoid overflow # Example 1: - Input: n = 5, m = 4 k = [2, 3, 4, 3, 2] c = [3, 5, 12, 20] - Output: 30 # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq k[i] \leq m$ - $1 \leq c[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, m, k, c): k.sort() ans = 0 for i in range(n - 1, -1, -1): ans += c[min(k[i] - 1, n - 1 - i)] return ans def solve2(self, n, m, k, c): k.sort() ans = 0 p = 0 for i in range(n - 1, -1, -1): ki = k[i] - 1 if p < m and p <= ki: ans += c[p] p += 1 else: ans += c[ki] return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = [0] * n c = [0] * m for i in range(n): k[i] = int(next(it)) for i in range(m): c[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, k, c) sys.stdout.write(str(result) + ""\n"")","binary,dp,sort,two_pointers",hard 258,"You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator. Replace the array nums with newNums. Repeat the entire process starting from step 1. Return the triangular sum of nums. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [1,2,3,4,5] Output: 8 Example 2: Input: nums = [5] Output: 5 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, nums): result = 0 m = len(nums) - 1 mck = 1 exp2 = 0 exp5 = 0 inv = [0, 1, 0, 7, 0, 0, 0, 3, 0, 9] pow2mod10 = [6, 2, 4, 8] k = 0 while True: if exp2 == 0 or exp5 == 0: mCk_ = 0 if exp2 > 0: mCk_ = mck * pow2mod10[exp2 % 4] elif exp5 > 0: mCk_ = mck * 5 else: mCk_ = mck result = (result + mCk_ * nums[k]) % 10 if k == m: return result mul = m - k while mul % 2 == 0: mul //= 2 exp2 += 1 while mul % 5 == 0: mul //= 5 exp5 += 1 mck = (mck * mul) % 10 div = k + 1 while div % 2 == 0: div //= 2 exp2 -= 1 while div % 5 == 0: div //= 5 exp5 -= 1 mck = (mck * inv[div % 10]) % 10 k += 1 def solve2(self, nums): n = len(nums) while n > 1: for i in range(n - 1): nums[i] = (nums[i] + nums[i + 1]) % 10 nums.pop() n -= 1 return nums[0] ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))","math,other",medium 259,"# Problem Statement There is a grid, consisting of $2$ rows and $n$ columns. The rows are numbered from $1$ to $2$ from top to bottom. The columns are numbered from $1$ to $n$ from left to right. Each cell of the grid contains an arrow pointing either to the left or to the right. No arrow points outside the grid. There is a robot that starts in a cell $(1, 1)$. Every second, the following two actions happen one after another: 1. Firstly, the robot moves left, right, down or up (**it can't try to go outside the grid, and can't skip a move**); 2. then it moves along the arrow that is placed in the current cell (the cell it ends up after its move). Your task is to determine whether the robot can reach the cell $(2, n)$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s1, s2): pass # write your code here``` where: - `s1` is a string of length $n$, representing the directions of the arrows in the first row - `s2` is a string of length $n$, representing the directions of the arrows in the second row - return ""YES"" or ""NO"" # Example 1: - Input: n = 4 s1 ="">><<"" s2 ="">>><"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - n is even - No arrow points outside the grid - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 100, 64], [4000, 800, 80], [32000, 6400, 640]]","class Solution: def solve1(self, n, s1, s2): flag = False for i in range(n - 1): if i % 2 == 0 and s2[i] == '<' and s1[i + 1] == '<': flag = True if i % 2 == 1 and s2[i + 1] == '<' and s1[i] == '<': flag = True return ""NO"" if flag else ""YES"" def solve2(self, n, s1, s2): rows = [s1, s2] target_r, target_c = 1, n - 1 vis0 = 1 vis1 = 0 cur0 = 1 cur1 = 0 if target_r == 0 and (vis0 & (1 << target_c)): return ""YES"" if target_r == 1 and (vis1 & (1 << target_c)): return ""YES"" while cur0 or cur1: nxt0 = 0 nxt1 = 0 for r in (0, 1): mask = cur0 if r == 0 else cur1 row_str = rows[r] while mask: lb = mask & -mask c = lb.bit_length() - 1 if c > 0: c1 = c - 1 if row_str[c1] == '>': c2 = c else: c2 = c - 2 if r == 0: if (vis0 & (1 << c2)) == 0: vis0 |= 1 << c2 nxt0 |= 1 << c2 if target_r == 0 and c2 == target_c: return ""YES"" else: if (vis1 & (1 << c2)) == 0: vis1 |= 1 << c2 nxt1 |= 1 << c2 if target_r == 1 and c2 == target_c: return ""YES"" if c + 1 < n: c1 = c + 1 if row_str[c1] == '>': c2 = c + 2 else: c2 = c if r == 0: if (vis0 & (1 << c2)) == 0: vis0 |= 1 << c2 nxt0 |= 1 << c2 if target_r == 0 and c2 == target_c: return ""YES"" else: if (vis1 & (1 << c2)) == 0: vis1 |= 1 << c2 nxt1 |= 1 << c2 if target_r == 1 and c2 == target_c: return ""YES"" r1 = 1 - r row_str2 = rows[r1] if row_str2[c] == '>': c2 = c + 1 else: c2 = c - 1 if r1 == 0: if (vis0 & (1 << c2)) == 0: vis0 |= 1 << c2 nxt0 |= 1 << c2 if target_r == 0 and c2 == target_c: return ""YES"" else: if (vis1 & (1 << c2)) == 0: vis1 |= 1 << c2 nxt1 |= 1 << c2 if target_r == 1 and c2 == target_c: return ""YES"" mask ^= lb cur0, cur1 = nxt0, nxt1 return ""NO"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s1 = next(it) s2 = next(it) solution = Solution() result = solution.solve(n, s1, s2) sys.stdout.write(str(result) + ""\n"")","dp,graph,search",hard 260,"You are given a binary string s that contains at least one '1'. You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination. Return a string representing the maximum odd binary number that can be created from the given combination. Note that the resulting string can have leading zeros. solution main function ```python class Solution: def solve(self, str_val): pass # write your code here``` Example 1: Input: s = ""010"" Output: ""001"" Example 2: Input: s = ""010"" Output: ""001"" Constraints: 1 <= s.length <= @data s consists only of '0' and '1'. s contains at least one '1' Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","class Solution: def solve1(self, s): N = len(s) arr = list(s) left = 0 right = N - 1 while left <= right: if arr[left] == '1': left += 1 if arr[right] == '0': right -= 1 if left <= right and arr[left] == '0' and arr[right] == '1': arr[left] = '1' arr[right] = '0' arr[left - 1] = '0' arr[N - 1] = '1' return """".join(arr) def solve2(self, s): n = len(s) ones = 0 for ch in s: if ch == '1': ones += 1 zeros = n - ones return '1' * (ones - 1) + '0' * zeros + '1' ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) try: str_val = next(it).decode() except StopIteration: str_val = """" solution = Solution() result = solution.solve(str_val) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","math,string,greedy",easy 261,"You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed. solution main function ```python class Solution: def solve(self, dic, bas): pass # write your code here``` Example 1: Input: products = [""mobile"",""mouse"",""moneypot"",""monitor"",""mousepad""], searchWord = ""mouse"" Output: [[""mobile"",""moneypot"",""monitor""],[""mobile"",""moneypot"",""monitor""],[""mouse"",""mousepad""],[""mouse"",""mousepad""],[""mouse"",""mousepad""]] Example 2: Input: products = [""havana""], searchWord = ""havana"" Output: [[""havana""],[""havana""],[""havana""],[""havana""],[""havana""],[""havana""]] Constraints: 1 <= products.length <= @data 1 <= products[i].length <= 3000 1 <= sum(products[i].length) <= 2 * 10^4 All the strings of products are unique. products[i] consists of lowercase English letters. 1 <= searchWord.length <= @data searchWord consists of lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 500, 1000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import bisect class Solution: def solve1(self, products, searchWord): products.sort() query = """" iter_last = 0 ans = [] for ch in searchWord: query += ch iter_find = bisect.bisect_left(products, query, lo=iter_last) selects = [] for i in range(3): if iter_find + i < len(products) and products[iter_find + i].startswith(query): selects.append(products[iter_find + i]) ans.append(selects) iter_last = iter_find return ans def solve2(self, products, searchWord): ans = [] s = searchWord m = len(s) for k in range(1, m + 1): a = b = c = None for p in products: if len(p) < k: continue match = True for i in range(k): if p[i] != s[i]: match = False break if not match: continue if a is None or p < a: c = b b = a a = p elif b is None or p < b: c = b b = p elif c is None or p < c: c = p cur = [] if a is not None: cur.append(a) if b is not None: cur.append(b) if c is not None: cur.append(c) ans.append(cur) return ans ","import sys lines = [l.strip() for l in sys.stdin.read().split('\n') if l.strip()] if not lines: sys.exit(0) n = int(lines[0]) if len(lines) >= n + 2: dic = lines[1:n + 1] bas = lines[n + 1] else: dic = lines[1:] bas = lines[-1] solution = Solution() result = solution.solve(dic, bas) out_lines = [] for it_inner in result: line_parts = [] for str_val in it_inner: line_parts.append(str(str_val)) out_lines.append("" "".join(line_parts) + "" "" if line_parts else """") sys.stdout.write(""\n"".join(out_lines))","string,binary",easy 262,"You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: Water the plants in order from left to right. After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can. You cannot refill the watering can early. You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. solution main function ```python class Solution: def solve(self, s, m): pass # write your code here``` Example 1: Input: plants = [2,2,3,3], capacity = 5 Output: 14 Example 2: Input: plants = [1,1,1,4,2,3], capacity = 4 Output: 30 Constraints: n == plants.length 1 <= n <= @data 1 <= plants[i] <= 10^6 max(plants[i]) <= capacity <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, p, capacity): ans = 0 c = capacity for i in range(len(p)): if c >= p[i]: ans += 1 else: ans += i ans += i + 1 c = capacity c -= p[i] return ans def solve2(self, p, capacity): ans = 0 c = capacity for i in range(len(p)): if c >= p[i]: ans += 1 else: ans += i + (i + 1) c = capacity c -= p[i] return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, m) sys.stdout.write(str(result))",other,medium 263,"# Problem Statement Petya has an array $a_i$ of $n$ integers. His brother Vasya became envious and decided to make his own array of $n$ integers. To do this, he found $m$ integers $b_i$ ($m\ge n$), and now he wants to choose some $n$ integers of them and arrange them in a certain order to obtain an array $c_i$ of length $n$. To avoid being similar to his brother, Vasya wants to make his array as different as possible from Petya's array. Specifically, he wants the total difference $D = \sum_{i=1}^{n} |a_i - c_i|$ to be as large as possible. Help Vasya find the maximum difference $D$ he can obtain. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, a, b): pass # write your code here``` where: - the return value is a 64-bit integer representing the maximum difference $D$ # Example 1: - Input: n = 4, m = 6 a = [6, 1, 2, 4] b = [3, 5, 1, 7, 2, 3] - Output: 16 # Constraints: - $1 \leq n \leq m \leq @data$ - $1 \leq a[i], b[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, m, a, b): a.sort() b.sort() ans = 0 l1 = 0 l2 = 0 r1 = n - 1 r2 = m - 1 for _ in range(n): if b[r2] - a[l1] > a[r1] - b[l2]: ans += b[r2] - a[l1] r2 -= 1 l1 += 1 else: ans += a[r1] - b[l2] r1 -= 1 l2 += 1 return ans def solve2(self, n, m, a, b): a.sort() b.sort() ans = 0 l1 = 0 l2 = 0 r1 = n - 1 r2 = m - 1 for _ in range(n): if b[r2] - a[l1] > a[r1] - b[l2]: ans += b[r2] - a[l1] r2 -= 1 l1 += 1 else: ans += a[r1] - b[l2] r1 -= 1 l2 += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) b = [0] * m for i in range(m): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, a, b) sys.stdout.write(str(result) + ""\n"")","two_pointers,data_structures,greedy,sort",hard 264,"# Problem Statement You are given two integers $n$ and $m$. An array $a_1,a_2,\dots,a_n$ is called snake if and only if: - All elements are integers between $0$ and $m$; - $a_1+a_2+\cdots+a_n = m$; - $a_n = \max([a_1,a_2,\dots,a_n])$. Define the function $f(a)$ by the following pseudocode: ``` function f(array a): pos := 1 res := 0 let nxt[x] be the smallest index y such that y > x and a[y] > a[x], or undefined if no such y exists while pos < n: if a[pos] < a[n]: res += a[nxt[pos]] - a[pos] pos := nxt[pos] else: pos += 1 return res ``` Your task is to compute the sum of $f(a)$ over all snake arrays of length $n$ with sum $m$, modulo $10^9+7$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m): pass # write your code here``` where: - `n`: length of the array, - `m`: total sum of the array, - return: the sum of `f(a)` over all snake arrays, modulo $10^9+7$. # Example 1: - Input: ``` n = 2 m = 5 ``` - Output: ``` 9 ``` # Constraints: - $2 \leq n \leq @data$ - $0 \leq m \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 200000]",4000,"[[5000, 1000, 500], [40000, 8000, 4000], [320000, 64000, 32000]]","import sys class Solution: F = [] I = [] MOD = 1000000007 def solve1(self, n, m): MOD = self.MOD MXN = n + m + 7 if len(self.F) < MXN: F_new = [1] * MXN for i in range(1, MXN): F_new[i] = (F_new[i - 1] * i) % MOD I_new = [1] * MXN I_new[-1] = pow(F_new[-1], MOD - 2, MOD) for i in range(MXN - 1, 0, -1): I_new[i - 1] = (I_new[i] * i) % MOD self.F = F_new self.I = I_new F = self.F I = self.I def power(a, b): res = 1 while b: if b & 1: res = (res * a) % MOD a = (a * a) % MOD b >>= 1 return res def C(N, R): if R < 0 or R > N: return 0 return F[N] * I[R] % MOD * I[N - R] % MOD def g(nn, mm, l): if nn == 0: return 1 if mm == 0 else 0 if mm < 0: return 0 ans = 0 for t in range(nn + 1): if t * (l + 1) > mm: break add = C(nn, t) * C(mm + nn - 1 - t * (l + 1), nn - 1) % MOD if t & 1: ans = (ans - add + MOD) % MOD else: ans = (ans + add) % MOD return ans inv = power(n - 1, MOD - 2) ans = 0 for x in range(m + 1): g1 = g(n - 1, m - x, x) g2 = g(n - 2, m - 2 * x, x) ans = (ans + x % MOD * ((g1 + g2 * (n - 1)) % MOD)) % MOD bad = 0 bad = (bad + (m - x) % MOD * g1 % MOD * inv) % MOD bad = (bad + x % MOD * g2) % MOD bad = (bad + max(0, m - 2 * x) % MOD * g2) % MOD ans = (ans - bad + MOD) % MOD return ans def solve2(self, n, m): MOD = self.MOD if n <= 0: return 0 a = [0] * n res_sum = 0 i = 0 curr_sum = 0 a[0] = 0 while True: rem = m - curr_sum if i < n - 1: if a[i] <= rem: i += 1 curr_sum += a[i - 1] a[i] = 0 continue else: if i == 0: break i -= 1 curr_sum -= a[i] a[i] += 1 continue else: a[i] = rem if rem >= 0: last = a[n - 1] ok = True for k in range(n - 1): if a[k] > last: ok = False break if ok: pos = 0 acc = 0 while pos < n - 1: if a[pos] < last: j = pos + 1 while a[j] <= a[pos]: j += 1 acc += (a[j] - a[pos]) pos = j else: pos += 1 res_sum = (res_sum + (acc % MOD)) % MOD if i == 0: break i -= 1 curr_sum -= a[i] a[i] += 1 continue return res_sum % MOD","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result) + ""\n"")",math,hard 265,"We are playing the Guessing Game. The game will work as follows: I pick a number between 1 and n. You guess a number. If you guess the right number, you win the game. If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game. Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 10 Output: 16 Example 2: Input: n = 1 Output: 0 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[8, 50, 200]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, n): dp = [[0] * (n + 1) for _ in range(n + 1)] for length in range(2, n + 1): for begin in range(n - length + 1): end = begin + length for i in range(begin, end): num_picked = i + 1 if i == begin: dp[begin][end] = num_picked + dp[begin + 1][end] else: dp[begin][end] = min(dp[begin][end], max(dp[begin][i], dp[i + 1][end]) + num_picked) return dp[0][n] def solve2(self, n): dp = [[0] * (n + 1) for _ in range(n + 1)] for length in range(2, n + 1): for begin in range(n - length + 1): end = begin + length best = float('inf') for i in range(begin, end): num_picked = i + 1 if i == begin: cost = num_picked + dp[begin + 1][end] else: cost = max(dp[begin][i], dp[i + 1][end]) + num_picked if cost < best: best = cost dp[begin][end] = best return dp[0][n] ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")","math,dp",medium 266,"# Problem Statement You are given a sequence `a` of `n` positive integers. For any sequence `b = [b1, b2, …, bk]`, define the cost: - `cost(b) = ceil(bk / min(b1, b2, …, bk))` For a partition of a sequence `c` into one or more contiguous subsequences whose concatenation equals `c`, define the total cost as the sum of the costs of all parts. Let `f(c)` be the minimum total cost over all possible partitions of `c`. Compute: - Sum of `f([a_l, a_{l+1}, …, a_r])` over all `1 ≤ l ≤ r ≤ n`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: the length of the array - `a`: the array of positive integers - return: the sum of `f` over all contiguous subsequences of `a` # Example 1: - Input: `n = 5` `a = [3, 1, 4, 1, 5]` - Output: `21` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^{18}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import bisect class Solution: def solve1(self, n, a): st = [] realind = [] i2 = [] i3 = [] prevind = [] ans = 0 N = 150 dp = [0] * N for i in range(n): x = a[i] while st and st[-1] >= x: st.pop() realind.pop() i2.pop() i3.pop() prevind.pop() st.append(x) if not realind: prevind.append(-1) else: prevind.append(realind[-1]) realind.append(i) half = (x + 1) // 2 third = (x + 2) // 3 idx2 = bisect.bisect_left(st, half) idx3 = bisect.bisect_left(st, third) i2.append(idx2) i3.append(idx3) for k in range(N): dp[k] = i + 2 dp[0] = len(st) ans += i - prevind[-1] for j in range(N): if j > 1: ans += j * (prevind[dp[j - 1]] - prevind[dp[j]]) if dp[j] == 0: break if j + 1 < N: dp[j + 1] = min(dp[j + 1], dp[j] - 1) if j + 2 < N: dp[j + 2] = min(dp[j + 2], i2[dp[j] - 1]) if j + 3 < N: dp[j + 3] = min(dp[j + 3], i3[dp[j] - 1]) return ans def solve2(self, n, a): ans = 0 for L in range(n): for R in range(L, n): m = R - L + 1 if m == 1: ans += 1 continue best = None gaps = m - 1 limit = 1 << gaps for mask in range(limit): s_cost = 0 mn = a[L] j = 0 while True: x = a[L + j] if x < mn: mn = x boundary = (j == m - 1) or ((mask >> j) & 1) if boundary: s_cost += (x + mn - 1) // mn if best is not None and s_cost >= best: break if j == m - 1: if best is None or s_cost < best: best = s_cost break j += 1 mn = a[L + j] else: j += 1 ans += best return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,data_structures",hard 267,"Given two strings s and t, return 1 if they are equal when both are typed into empty text editors, and return 0 otherwise. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: s = ""ab#c"", t = ""ad#c"" Output: 1 Example 2: Input: s = ""ab##"", t = ""c#d#"" Output: 1 Constraints: 1 <= s.length, t.length <= @data s and t only contain lowercase letters and '#' characters. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, S, T): i = len(S) - 1 j = len(T) - 1 while True: back = 0 while i >= 0 and (back > 0 or S[i] == '#'): if S[i] == '#': back += 1 else: back -= 1 i -= 1 back = 0 while j >= 0 and (back > 0 or T[j] == '#'): if T[j] == '#': back += 1 else: back -= 1 j -= 1 if i >= 0 and j >= 0 and S[i] == T[j]: i -= 1 j -= 1 else: break return 1 if (i == -1 and j == -1) else 0 def solve2(self, S, T): i = len(S) - 1 j = len(T) - 1 while True: back = 0 while i >= 0 and (back > 0 or S[i] == '#'): if S[i] == '#': back += 1 else: back -= 1 i -= 1 back = 0 while j >= 0 and (back > 0 or T[j] == '#'): if T[j] == '#': back += 1 else: back -= 1 j -= 1 if i >= 0 and j >= 0 and S[i] == T[j]: i -= 1 j -= 1 else: break return 1 if (i == -1 and j == -1) else 0 ","import sys def main(): data = sys.stdin.read().split() it = iter(data) a = next(it) b = next(it) solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","string,two_pointers",easy 268,"There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. solution main function ```python class Solution: def solve(self, g): pass # write your code here``` Example 1: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Example 2: Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] Output: [4] Constraints: n == graph.length 1 <= n <= @data 0 <= graph[i].length <= n 0 <= graph[i][j] <= n - 1 graph[i] is sorted in a strictly increasing order. The graph may contain self-loops. The number of edges in the graph will be in the range [1, 4 * n]. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys sys.setrecursionlimit(20000) class Solution: def solve1(self, graph): n = len(graph) vis = [False] * n safe = [False] * n def dfs(u): vis[u] = True for v in graph[u]: if not vis[v]: dfs(v) if not safe[v]: return elif not safe[v]: return safe[u] = True for i in range(n): if not vis[i]: dfs(i) ans = [] for i in range(n): if safe[i]: ans.append(i) return ans def solve2(self, graph): n = len(graph) for i in range(n): if isinstance(graph[i], list) and len(graph[i]) == 0: graph[i] = -1 changed = True while changed: changed = False for i in range(n): if isinstance(graph[i], list): lst = graph[i] all_safe = True for v in lst: if isinstance(graph[v], list) or graph[v] != -1: all_safe = False break if all_safe: graph[i] = -1 changed = True ans = [] for i in range(n): if not isinstance(graph[i], list) and graph[i] == -1: ans.append(i) return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) e = [[] for _ in range(n + 1)] g = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) e[x].append(y) for i in range(0, n): g.append(e[i]) solution = Solution() result = solution.solve(g) out = [] for v in result: out.append(str(v)) sys.stdout.write("" "".join(out))","graph,search",medium 269,"You are 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. solution main function ```python class Solution: def solve(self, n, start): pass # write your code here``` Example 1: Input: n = 5, start = 0 Output: 8 Example 2: Input: n = 4, start = 3 Output: 8 Constraints: 1 <= n <= @data 0 <= start <= 1000 n == nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, n, start): num = start for i in range(1, n): num = num ^ (start + 2 * i) return num def solve2(self, n, start): res = 0 for i in range(n): res ^= start + (i << 1) return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) start = int(next(it)) solution = Solution() result = solution.solve(n, start) sys.stdout.write(str(result))","greedy,sort",easy 270,"# Problem Statement You are given a string $s$ of length $n$ consisting of characters $\texttt{A}$ and $\texttt{B}$. You are allowed to do the following operation: - Choose an index $1 \le i \le n - 1$ such that $s_i = \texttt{A}$ and $s_{i + 1} = \texttt{B}$. Then, swap $s_i$ and $s_{i+1}$. You are only allowed to do the operation **at most once** for each index $1 \le i \le n - 1$. However, you can do it in any order you want. Find the maximum number of operations that you can carry out. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return: the maximum number of operations that you can carry out # Example 1: - Input: n = 2 s = ""AB"" - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $ s[i] \in \{ \texttt{A}, \texttt{B} \}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): l = 0 r = n while l < r and s[l] == 'B': l += 1 while l < r and s[r - 1] == 'A': r -= 1 return max(0, r - l - 1) def solve2(self, n, s): l = 0 r = n while l < r and s[l] == 'B': l += 1 while l < r and s[r - 1] == 'A': r -= 1 t = r - l - 1 if t < 0: return 0 return t ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,string,two_pointers",hard 271,"# Problem Statement For all integers $x \ge 1$ and $k \ge 2$, let $v_k(x!)$ be the number of trailing zeros in the base-$k$ representation of $x!$, i.e., the largest integer $i$ such that $k^i$ divides $x!$. For a prime $p$, we have $$ v_p(x!)=\sum_{j=1}^{\infty} \left\lfloor \frac{x}{p^j} \right\rfloor. $$ If $k$ is not prime and $k=\prod p_i^{e_i}$ is its prime factorization, then $$ v_k(x!)=\min_i \left\lfloor \frac{v_{p_i}(x!)}{e_i} \right\rfloor. $$ For any two positive integers $a,b$ and any $k\ge 2$, define the weight $$ w_k(a,b)= \begin{cases} \min\big(v_k(a!), v_k(b!)\big), & v_k(a!) \ne v_k(b!),\\ 10^{100}, & \text{otherwise.} \end{cases} $$ Then define $$ f_m(a,b)=\min_{2\le k\le m} w_k(a,b). $$ Given two integers $n$ and $m$, compute $$ \sum_{1\le x \le n-1} f_m(x,n). $$ The result is strictly less than $10^{100}$ under the given constraints. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m): pass # write your code here``` where: - `n`: upper bound for the sum (we sum over `x=1..n-1`) - `m`: upper bound for base `k` (we minimize over `k=2..m`) - return: the value of `sum_{x=1}^{n-1} f_m(x, n)` # Example: - Input: ``` n = 6 m = 7 ``` - Output: ``` 1 ``` # Constraints: - $2 \leq n \leq @data$ - $n \leq m \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 100000, 10000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, m): INF = 1000000005 if n <= 2: return 0 limSmall = int(math.sqrt(max(n, m))) + 5 is_comp = [False] * (limSmall + 1) smallPrimes = [] for i in range(2, int(math.sqrt(limSmall)) + 1): if not is_comp[i]: for j in range(i * i, limSmall + 1, i): is_comp[j] = True for i in range(2, limSmall + 1): if not is_comp[i]: smallPrimes.append(i) def isPrime(x): if x < 2: return False for p in smallPrimes: if p * p > x: break if x % p == 0: return False return True def legendre(p, x): res = 0 while x > 0: x //= p res += x return res def factorize(x): f = [] temp_x = x for p in smallPrimes: if p * p > temp_x: break if temp_x % p == 0: c = 0 while temp_x % p == 0: temp_x //= p c += 1 f.append((p, c)) if temp_x > 1: f.append((temp_x, 1)) return f q = n while q >= 2 and not isPrime(q): q -= 1 if q >= n: return 0 g = n - q facts = [[] for _ in range(g + 1)] for y in range(q, n + 1): facts[y - q] = factorize(y) plist_set = set() for i in range(g + 1): for p, _ in facts[i]: plist_set.add(p) plist = sorted(list(plist_set)) if not plist: return 0 pid = {p: i for i, p in enumerate(plist)} sq = int(math.sqrt(m)) idxSmall, idxBig = [], [] for i, p in enumerate(plist): if p <= sq: idxSmall.append(i) else: idxBig.append(i) P = len(plist) vpN = [0] * P vpX = [0] * P limE = [0] * P for i in range(P): p = plist[i] vpN[i] = legendre(p, n) if p <= sq: pw = p while pw <= m: limE[i] += 1 if m // p < pw: break pw *= p for i in range(P): vpX[i] = legendre(plist[i], q) vpN_div = [None] * P for idx in idxSmall: vpN_div[idx] = [0] * (limE[idx] + 1) for e in range(1, limE[idx] + 1): vpN_div[idx][e] = vpN[idx] // e ans = 0 for off in range(g): best = INF for idx in idxBig: if vpX[idx] != vpN[idx]: best = min(best, vpX[idx]) if best == 0: break if best != 0: for idx in idxSmall: if vpX[idx] == vpN[idx]: continue a = vpX[idx] for e in range(1, limE[idx] + 1): ax = a // e if ax != vpN_div[idx][e]: best = min(best, ax) if best == 0: break if best == 0: break if best == INF: best = 0 ans += best if off + 1 < g: yIdx = off + 1 for p, c in facts[yIdx]: idx = pid[p] vpX[idx] += c return ans def solve2(self, n, m): TEN100 = 10 ** 100 total = 0 for x in range(1, n): best = TEN100 k = 2 while k <= m: t = k min_vx = None min_vn = None i = 2 while i * i <= t: if t % i == 0: e = 0 while t % i == 0: t //= i e += 1 tx = x vx = 0 while tx: tx //= i vx += tx tn = n vn = 0 while tn: tn //= i vn += tn vx //= e vn //= e if min_vx is None or vx < min_vx: min_vx = vx if min_vn is None or vn < min_vn: min_vn = vn i += 1 if t > 1: p = t tx = x vx = 0 while tx: tx //= p vx += tx tn = n vn = 0 while tn: tn //= p vn += tn if min_vx is None or vx < min_vx: min_vx = vx if min_vn is None or vn < min_vn: min_vn = vn if min_vx is None: min_vx = 0 min_vn = 0 if min_vx != min_vn: w = min(min_vx, min_vn) else: w = TEN100 if w < best: best = w if best == 0: break k += 1 if best == TEN100: best = 0 total += best return total ","import sys data = sys.stdin.buffer.read().split() n = int(data[0]) m = int(data[1]) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result) + ""\n"")",math,hard 272,"# Problem Statement You are given a binary array $a$ of $n$ elements, a binary array is an array consisting only of $0$s and $1$s. A blank space is a segment of **consecutive** elements consisting of only $0$s. Your task is to find the length of the longest blank space. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return the length of the longest blank space. # Example 1: - Input: n = 5 a = [1, 0, 0, 1, 0] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a_i \leq 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, n: int, a: List[int]) -> int: ans = 0 t = 0 for i in range(n): if a[i] == 0: t += 1 else: t = 0 ans = max(ans, t) return ans def solve2(self, n: int, a: List[int]) -> int: ans = 0 for i in range(n): if a[i] == 0: length = 0 for j in range(i, n): if a[j] == 0: length += 1 else: break if length > ans: ans = length return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",greedy,easy 273,"Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [3,4,5,2] Output: 12 Example 2: Input: nums = [1,5,4,5] Output: 16 Constraints: 2 <= nums.length <= @data 1 <= nums[i] <= 10^3 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, nums: List[int]) -> int: biggest = 0 secondBiggest = 0 for num in nums: if num > biggest: secondBiggest = biggest biggest = num else: secondBiggest = max(secondBiggest, num) return (biggest - 1) * (secondBiggest - 1) def solve2(self, nums: List[int]) -> int: n = len(nums) best = (nums[0] - 1) * (nums[1] - 1) i = 0 while i < n: j = i + 1 while j < n: val = (nums[i] - 1) * (nums[j] - 1) if val > best: best = val j += 1 i += 1 return best","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))",sort,easy 274,"# Problem Statement You are given a path consisting of $n$ consecutive cells. Each cell is represented by a character: - `.` denotes an empty cell, - `@` denotes a coin, - `*` denotes a thorn. Count the number of coins before the first occurrence of two consecutive thorn cells (`**`). If the string does not contain two consecutive thorn cells, count all coins in the string. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - `s` is a string of length `n`. - return: the number of coins before the first `**` segment, or all coins if no such segment exists. # Example 1: - Input: n = 10 s = "".@@*@.**@@"" - Output: 3 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve(self, n, s): p = s.find(""**"") if p == -1: p = n ans = 0 for i in range(p): if s[i] == '@': ans += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,dp",medium 275,"# Problem Statement: You are given a checkerboard of size $2*n \times 2*n$, i. e. it has $2*n$ rows and $2*n$ columns. The rows of this checkerboard are numbered from $-n$ to $n$ from bottom to top. The columns of this checkerboard are numbered from $-n$ to $n$ from left to right. The notation $(r, c)$ denotes the cell located in the $r$-th row and the $c$-th column. There is a king piece at position $(0, 0)$ and it wants to get to position $(a, b)$ as soon as possible. In this problem our king is lame. Each second, the king makes exactly one of the following five moves. - Skip move. King's position remains unchanged. - Go up. If the current position of the king is $(r, c)$ he goes to position $(r + 1, c)$. - Go down. Position changes from $(r, c)$ to $(r - 1, c)$. - Go right. Position changes from $(r, c)$ to $(r, c + 1)$. - Go left. Position changes from $(r, c)$ to $(r, c - 1)$. King is **not allowed** to make moves that put him outside of the board. The important consequence of the king being lame is that he is **not allowed** to make the same move during two consecutive seconds. For example, if the king goes right, the next second he can only skip, go up, down, or left. What is the minimum number of seconds the lame king needs to reach position $(a, b)$? The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, b): pass # write your code here``` Where: - `n` is an integer representing the size of the chessboard. - `a` and `b` are integers representing the target position coordinates. - The function should return an integer representing the minimum time (in seconds) required for the king to reach the target position. # Example 1 - Input: n = 100 a = -4 b = 1 - Output: 7 # Constraints: - $0 < n \leq @data$ - $-n \leq a \leq n$ - $-n \leq b \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a, b): a = abs(a) b = abs(b) return min(a, b) * 2 + max(0, 2 * abs(b - a) - 1) def solve2(self, n, a, b): dr = abs(a) dc = abs(b) t = 0 last = 0 while dr > 0 and dc > 0: if dr >= dc: if last == 1: dc -= 1 last = 2 else: dr -= 1 last = 1 else: if last == 2: dr -= 1 last = 1 else: dc -= 1 last = 2 t += 1 if dr > 0: while dr > 0: if last == 1: t += 1 last = 3 else: dr -= 1 t += 1 last = 1 elif dc > 0: while dc > 0: if last == 2: t += 1 last = 3 else: dc -= 1 t += 1 last = 2 return t ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = int(next(it)) b = int(next(it)) solution = Solution() result = solution.solve(n, a, b) sys.stdout.write(str(result) + ""\n"")","greedy,math",hard 276,"Given an integer num, return a string of its base 7 representation. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: num = 100 Output: ""202"" Example 2: Input: num = -7 Output: ""-10"" Constraints: -@data <= num <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 10000000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, num: int) -> str: str_list = [] sign = '' if num < 0: num = -num sign = 'n' if num == 0: return ""0"" while num > 0: str_list.append(str(num % 7)) num = num // 7 if sign == 'n': str_list.append('-') str_list.reverse() return """".join(str_list) def solve2(self, num: int) -> str: if num == 0: return ""0"" neg = num < 0 x = -num if neg else num power = 1 while power <= x // 7: power *= 7 res = """" while power > 0: d = x // power res += chr(48 + d) x -= d * power power //= 7 if neg: res = ""-"" + res return res ","import sys def main(): data = sys.stdin.read().split() n = int(data[0]) if data else 0 solution = Solution() result = solution.solve(n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",math,easy 277,"# Problem Statement You are given an array $a$ of $n$ elements $a_1, a_2, \ldots, a_n$. You can perform the following operation any number (possibly $0$) of times: - Choose two integers $i$ and $j$, where $1 \le i, j \le n$, and assign $a_i := a_j$. Find the minimum number of operations required to make the array $a$ satisfy the condition: - For every pairwise distinct triplet of indices $(x, y, z)$ ($1 \le x, y, z \le n$, $x \ne y$, $y \ne z$, $x \ne z$), there exists a non-degenerate triangle with side lengths $a_x$, $a_y$ and $a_z$, i.e. $a_x + a_y > a_z$, $a_y + a_z > a_x$ and $a_z + a_x > a_y$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the minimum number of operations required. # Example 1: - Input: n = 7 a = [1, 2, 3, 4, 5, 6, 7] - Output: 3 # Constraints: - $3 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import bisect class Solution: def solve1(self, n, a): a.sort() ans = n - 1 for i in range(1, n): pos = bisect.bisect_left(a, a[i] + a[i - 1]) ans = min(ans, i - 1 + n - pos) return ans def solve2(self, n, a): a.sort() def lb(val): lo, hi = 0, n while lo < hi: mid = (lo + hi) // 2 if a[mid] < val: lo = mid + 1 else: hi = mid return lo ans = n i = 0 while i < n: x = a[i] j = i while j < n: y = a[j] lpos_y = j bottom = lpos_y - (1 if y > x else 0) pos = lb(x + y) top = n - pos ops = bottom + top if ops < ans: ans = ops v = y jj = j + 1 while jj < n and a[jj] == v: jj += 1 j = jj v = x ii = i + 1 while ii < n and a[ii] == v: ii += 1 i = ii maxfreq = 1 cur = 1 for k in range(1, n): if a[k] == a[k - 1]: cur += 1 if cur > maxfreq: maxfreq = cur else: cur = 1 if n - maxfreq < ans: ans = n - maxfreq return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","binary,sort,math,two_pointers",hard 278,"Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for: i - k <= r <= i + k, j - k <= c <= j + k, and (r, c) is a valid position in the matrix. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[12,21,16],[27,45,33],[24,39,28]] Example 2: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 Output: [[45,45,45],[45,45,45],[45,45,45]] Constraints: m == mat.length n == mat[i].length 1 <= m, n, k <= @data 1 <= mat[i][j] <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 500]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, mat, k): h = len(mat) w = len(mat[0]) integralImg = [[0 for _ in range(w)] for _ in range(h)] outputImg = [[0 for _ in range(w)] for _ in range(h)] for y in range(h): pixelSum = 0 for x in range(w): pixelSum += mat[y][x] integralImg[y][x] = pixelSum if y > 0: integralImg[y][x] += integralImg[y - 1][x] for y in range(h): minRow = max(0, y - k) maxRow = min(h - 1, y + k) for x in range(w): minCol = max(0, x - k) maxCol = min(w - 1, x + k) outputImg[y][x] = integralImg[maxRow][maxCol] if minRow > 0: outputImg[y][x] -= integralImg[minRow - 1][maxCol] if minCol > 0: outputImg[y][x] -= integralImg[maxRow][minCol - 1] if (minRow > 0) and (minCol > 0): outputImg[y][x] += integralImg[minRow - 1][minCol - 1] return outputImg def solve2(self, mat, k): h = len(mat) w = len(mat[0]) if h > 0 else 0 ans = [] for i in range(h): minRow = i - k if minRow < 0: minRow = 0 maxRow = i + k if maxRow >= h: maxRow = h - 1 row = [] for j in range(w): minCol = j - k if minCol < 0: minCol = 0 maxCol = j + k if maxCol >= w: maxCol = w - 1 s = 0 r = minRow while r <= maxRow: c = minCol row_r = mat[r] while c <= maxCol: s += row_r[c] c += 1 r += 1 row.append(s) ans.append(row) return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s, k) out = sys.stdout.write for s in result: line_parts = [] for it2 in s: line_parts.append(str(it2)) if line_parts: out("" "".join(line_parts)) out(""\n"")","dynamic_programming,other",medium 279,"You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. Store any matrix that satisfies the conditions in the passed ans two-dimensional array. The ans array has been initialized to a two-dimensional zero matrix. The examples show one valid matrix; this runner validates ans and prints 1 if it is valid, or 0 otherwise. solution main function ```python class Solution: def solve(self, a, b, ans): pass # write your code here``` Example 1: Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0],[1,7]] Example 2: Input: rowSum = [5,7,10], colSum = [8,6,8] Output: [[0,5,0],[6,1,0],[2,0,8]] Constraints: 1 <= rowSum.length * colSum.length <= @data 0 <= rowSum[i], colSum[i] <= 10^8 sum(rowSum) == sum(colSum) Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, rowSum, colSum, ans): N = len(rowSum) M = len(colSum) r = rowSum[:] c = colSum[:] i = 0 j = 0 while i < N and j < M: val = min(r[i], c[j]) ans[i][j] = val r[i] -= val c[j] -= val if r[i] == 0: i += 1 else: j += 1 def solve2(self, rowSum, colSum, ans): n = len(rowSum) m = len(colSum) for i in range(n): row_rem = rowSum[i] for j in range(m): if row_rem == 0: continue col_rem = colSum[j] if i > 0: s = 0 for k in range(i): s += ans[k][j] col_rem -= s if col_rem <= 0: continue v = row_rem if row_rem <= col_rem else col_rem ans[i][j] = v row_rem -= v ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [] b = [] ans = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): temp.append(0) ans.append(temp) for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, m + 1): x = int(next(it)) b.append(x) x = a[:] y = b[:] solution = Solution() solution.solve(a, b, ans) if len(ans) != n: sys.stdout.write(""0"") return for row in ans: if not isinstance(row, list) or len(row) != m: sys.stdout.write(""0"") return for i in range(1, n + 1): sum_val = 0 for j in range(1, m + 1): value = ans[i - 1][j - 1] if type(value) is not int or value < 0: sys.stdout.write(""0"") return sum_val += value if sum_val != x[i - 1]: sys.stdout.write(""0"") return for i in range(1, m + 1): sum_val = 0 for j in range(1, n + 1): sum_val += ans[j - 1][i - 1] if sum_val != y[i - 1]: sys.stdout.write(""0"") return sys.stdout.write(""1"") if __name__ == ""__main__"": main()","math,greedy",easy 280,"# Problem Statement Let's consider the following simple problem. You are given a string $s$ of length $n$, consisting of lowercase Latin letters, as well as an array of indices $ind$ of length $m$ ($1 \leq ind_i \leq n$) and a string $c$ of length $m$, consisting of lowercase Latin letters. Then, in order, you perform the update operations, namely, during the $i$-th operation, you set $s_{ind_i} = c_i$. Note that you perform all $m$ operations from the first to the last. Of course, if you change the order of indices in the array $ind$ and/or the order of letters in the string $c$, you can get different results. Find the lexicographically smallest string $s$ that can be obtained after $m$ update operations, if you can rearrange the indices in the array $ind$ and the letters in the string $c$ as you like. A string $a$ is lexicographically less than a string $b$ if and only if one of the following conditions is met: - $a$ is a prefix of $b$, but $a \neq b$; - in the first position where $a$ and $b$ differ, the symbol in string $a$ is earlier in the alphabet than the corresponding symbol in string $b$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, s, ind, c): pass # write your code here``` where the method should return the lexicographically smallest string that can be obtained after performing the $m$ update operations. # Example 1: - Input: n = 1, m = 2 s = ""a"" ind = [1, 1] c = ""cb"" - Output: b # Constraints: - $1 \leq n, m \leq @data$ - $s, c$ consists of lowercase Latin letters - $1 \leq ind[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, m, s, ind, c): ind.sort() c = """".join(sorted(c)) s_list = list(s) last = 0 cnt = 0 for i in range(m): if ind[i] != last: s_list[ind[i] - 1] = c[cnt] cnt += 1 last = ind[i] res_str = """".join(s_list) return res_str def solve2(self, n, m, s, ind, c): s_list = list(s) ind.sort() freq = [0] * 26 for ch in c: freq[ord(ch) - 97] += 1 p = 0 last = 0 for idx in ind: if idx != last: while p < 26 and freq[p] == 0: p += 1 if p < 26: s_list[idx - 1] = chr(97 + p) freq[p] -= 1 last = idx res_str = """".join(s_list) return res_str ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = next(it) ind = [0] * m for i in range(m): ind[i] = int(next(it)) c = next(it) solution = Solution() result = solution.solve(n, m, s, ind, c) sys.stdout.write(str(result) + ""\n"")","data_structures,greedy,sort",hard 281,"# Problem Statement Amidst skyscrapers in the bustling metropolis of Metro Manila, the newest Noiph mall in the Philippines has just been completed! The construction manager, Penchick, ordered a state-of-the-art monument to be built with $n$ pillars. The heights of the monument's pillars can be represented as an array $h$ of $n$ positive integers, where $h_i$ represents the height of the $i$-th pillar for all $i$ between $1$ and $n$. Penchick wants the heights of the pillars to be in **non-decreasing** order, i.e. $h_i \le h_{i + 1}$ for all $i$ between $1$ and $n - 1$. However, due to confusion, the monument was built such that the heights of the pillars are in **non-increasing** order instead, i.e. $h_i \ge h_{i + 1}$ for all $i$ between $1$ and $n - 1$. Luckily, Penchick can modify the monument and do the following operation on the pillars as many times as necessary: - Modify the height of a pillar to any positive integer. Formally, choose an index $1\le i\le n$ and a positive integer $x$. Then, assign $h_i := x$. Help Penchick determine the minimum number of operations needed to make the heights of the monument's pillars **non-decreasing**. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return a single integer representing the minimum number of operations needed to make the heights of the pillars non-decreasing. # Example 1: - Input: n = 5 a = [5, 3, 2, 4, 1] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq h[i] \leq n$ - $h[i] \geq h[i + 1]$ for all $i$ between $1$ and $n - 1$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, h): ans = n l = -1 c = 0 for i in range(n): if h[i] == l: c += 1 else: c = 1 l = h[i] ans = min(ans, n - c) return ans def solve2(self, n, h): max_run = 0 run = 0 prev = -1 for i in range(n): if h[i] == prev: run += 1 else: run = 1 prev = h[i] if run > max_run: max_run = run return n - max_run ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy,math",hard 282,"You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points. solution main function ```python class Solution: def solve(self, g): pass # write your code here``` Example 1: Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] Output: 20 Example 2: Input: points = [[3,12],[-2,5],[-4,1]] Output: 18 Constraints: 1 <= points.length <= @data -10^6 <= xi, yi <= 10^6 All pairs (xi, yi) are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, points): n = len(points) visited = [False] * n minDist = [math.inf] * n minDist[0] = 0 result = 0 for i in range(n): minCost = math.inf currentNode = -1 for j in range(n): if not visited[j] and minDist[j] < minCost: minCost = minDist[j] currentNode = j visited[currentNode] = True result += minCost for j in range(n): if not visited[j]: dist = abs(points[currentNode][0] - points[j][0]) +\ abs(points[currentNode][1] - points[j][1]) minDist[j] = min(minDist[j], dist) return result def solve2(self, points): n = len(points) if n <= 1: return 0 res = 0 k = 1 while k < n: min_cost = 10**30 best_j = k for i in range(k): xi, yi = points[i][0], points[i][1] for j in range(k, n): xj, yj = points[j][0], points[j][1] d = abs(xi - xj) + abs(yi - yj) if d < min_cost: min_cost = d best_j = j res += min_cost if best_j != k: points[k], points[best_j] = points[best_j], points[k] k += 1 return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) g = [] for i in range(1, n + 1): temp = [] x = int(next(it)) y = int(next(it)) temp.append(x) temp.append(y) g.append(temp) solution = Solution() result = solution.solve(g) sys.stdout.write(str(result))","graph,tree,search",medium 283,"# Problem Statement Three friends gathered to play a few games of chess together. In every game, two of them play against each other. The winner gets $2$ points while the loser gets $0$, and in case of a draw, both players get $1$ point each. Note that the same pair of players could have played any non-negative number of times (possibly zero). It is also possible that no games were played at all. You've been told that their scores after all the games were played were $p_1$, $p_2$ and $p_3$. Additionally, it is guaranteed that $p_1 \leq p_2 \leq p_3$ holds. Find the maximum number of draws that could have happened and print it. If there isn't any way to obtain $p_1$, $p_2$ and $p_3$ as a result of a non-negative number of games between the three players, print $-1$ instead. The main function of the solution is defined as: ```python class Solution: def solve(self, p1, p2, p3): pass # write your code here``` where: - return: the maximum possible number of draws that could've happened, or −1 if the scores aren't consistent with any valid set of games and results. # Example 1: - Input: p1 = 0, p2 = 1, p3 = 1 - Output: 1 # Constraints: - $0 \leq p1 \leq p2 \leq p3 \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, p1, p2, p3): s = p1 + p2 + p3 m = max(p1, p2, p3) if s % 2: return -1 else: return min(s - m, s // 2) def solve2(self, p1, p2, p3): s = p1 + p2 + p3 if s & 1: return -1 m = p1 if p2 > m: m = p2 if p3 > m: m = p3 d = s // 2 t = s - m if t < d: d = t return d ","import sys data = sys.stdin.buffer.read().split() it = iter(data) p1 = int(next(it)) p2 = int(next(it)) p3 = int(next(it)) solution = Solution() result = solution.solve(p1, p2, p3) sys.stdout.write(str(result) + ""\n"")","math,dp",medium 284,"Given two integers, num and t. A number x is achievable if it can become equal to num after applying the following operation at most t times: Increase or decrease x by 1, and simultaneously increase or decrease num by 1. Return the maximum possible value of x. solution main function ```python class Solution: def solve(self, x, y): pass # write your code here``` Example 1: Input: num = 4, t = 1 Output: 6 Example 2: Input: num = 3, t = 2 Output: 7 Constraints: 1 <= num, t <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, num, t): return num + t * 2 def solve2(self, num, t): return num + 2 * t ","import sys data = sys.stdin.read().split() it = iter(data) x = int(next(it)) y = int(next(it)) solution = Solution() result = solution.solve(x, y) sys.stdout.write(str(result))","math,other",easy 285,"# Problem Statement Rostam's loyal horse, Rakhsh, has seen better days. Once powerful and fast, Rakhsh has grown weaker over time, struggling to even move. Rostam worries that if too many parts of Rakhsh's body lose strength at once, Rakhsh might stop entirely. To keep his companion going, Rostam decides to strengthen Rakhsh, bit by bit, so no part of his body is too frail for too long. Imagine Rakhsh's body as a line of spots represented by a binary string $s$ of length $n$, where each $0$ means a weak spot and each $1$ means a strong one. Rostam's goal is to make sure that no interval of $m$ consecutive spots is entirely weak (all $0$s). Luckily, Rostam has a special ability called Timar, inherited from his mother Rudabeh at birth. With Timar, he can select any segment of length $k$ and instantly strengthen all of it (changing every character in that segment to $1$). The challenge is to figure out the minimum number of times Rostam needs to use Timar to keep Rakhsh moving, ensuring there are no consecutive entirely weak spots of length $m$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, s): pass # write your code here``` where: - the return value is the minimum number of times Timar is used # Example 1: - Input: n = 5, m = 1, k = 1 s = ""10101"" - Output: 2 # Constraints: - $1 \leq m, k \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, m, k, s): cnt = 0 ans = 0 r = 0 for l in range(1, n + 1): if s[l - 1] == '1': cnt = 0 else: if l > r: cnt += 1 if cnt == m: ans += 1 cnt = 0 r = l + k - 1 return ans def solve2(self, n, m, k, s): cnt = 0 ans = 0 r = 0 for l in range(1, n + 1): if s[l - 1] == '1': cnt = 0 else: if l > r: cnt += 1 if cnt == m: ans += 1 cnt = 0 r = l + k - 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, m, k, s) sys.stdout.write(str(result) + ""\n"")","two_pointers,data_structures",medium 286,"# Problem Statement Jonathan is fighting against DIO's Vampire minions. There are $n$ of them with strengths $a_1, a_2, \dots, a_n$. Denote $(l, r)$ as the group consisting of the vampires with indices from $l$ to $r$. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group $(l, r)$ is defined as $$ f(l,r) = a_l \and a_{l+1} \and a_{l+2} \and \ldots \and a_r. $$ Here, $\and$ denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Because Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in **exactly** one group, and the **sum** of strengths of the groups is **minimized**. Among all ways to divide the vampires, he would like to find the way with the **maximum** number of groups. Given the strengths of each of the $n$ vampires, find the **maximum number** of groups among all possible ways to divide the vampires with the smallest sum of strengths. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): all_val = ~0 for i in range(n): all_val &= a[i] if all_val != 0: return 1 ans = 0 res = ~0 for i in range(n): res &= a[i] if res == 0: ans += 1 res = ~0 return ans def solve2(self, n, a): all_val = -1 for i in range(n): all_val &= a[i] if all_val != 0: return 1 ans = 0 res = -1 for i in range(n): res &= a[i] if res == 0: ans += 1 res = -1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","bit_manipulation,two_pointers,greedy",hard 287,"# Problem Statement You are given an array $a$ of $n$ non-negative integers and an integer $x$. You can do the following two-step operation any (possibly zero) number of times: 1. Choose an index $i$ ($1 \leq i \leq n$). 2. Increase $a_i$ by $x$, in other words $a_i := a_i + x$. Find the maximum value of the $\operatorname{MEX}$ of $a$ if you perform the operations optimally. The $\operatorname{MEX}$ (minimum excluded value) of an array is the smallest non-negative integer that is not in the array. For example: - The $\operatorname{MEX}$ of $[2,2,1]$ is $0$ because $0$ is not in the array. - The $\operatorname{MEX}$ of $[3,1,0,1]$ is $2$ because $0$ and $1$ are in the array but $2$ is not. - The $\operatorname{MEX}$ of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$ and $3$ are in the array but $4$ is not. The main function of the solution is defined as: ```python class Solution: def solve(self, n, x, a): pass # write your code here``` where: - return: the maximum value of the $\operatorname{MEX}$ of $a$ if you perform the operations optimally. # Example 1: - Input: n = 6, x = 3, a = [0, 3, 2, 1, 5, 2] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x \leq 10^6$ - $0 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, x, a): cnt = [0] * (n + 1) for val in a: if val <= n: cnt[val] += 1 for i in range(n + 1): if cnt[i] == 0: return i if i + x <= n: cnt[i + x] += cnt[i] - 1 return n + 1 def solve2(self, n, x, a): for i in range(n + 1): flag = False for j in range(n): if a[j] < i: k = (i - a[j] + x - 1) // x a[j] += k * x if a[j] == i: flag = True a[j] = int(1E9) break if not flag: return i return n + 1 ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) x = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, x, a) sys.stdout.write(str(result) + ""\n"")",math,medium 288,"# Problem Statement You are given a game with $n$ piles of stones. A configuration is valid if each pile has an integer number of stones between $1$ and $m$ (inclusive). Some indices from $1$ to $n$ are marked as good (it is guaranteed that index $1$ is always good). Alice and Bob alternately take turns for $n-1$ turns with Alice going first. In each turn: - Choose an integer $i$ such that $1 \le i \le p$ (where $p$ is the number of piles left) and $i$ is good, then remove the $i$-th pile completely. After removal, the piles are re-indexed from $1$ to $p-1$. The game ends when only one pile remains. Let $x$ be the number of stones in the final remaining pile. Alice wants to maximize $x$, while Bob wants to minimize it. Both play optimally. Compute the sum of $x$ over all valid configurations modulo $10^9+7$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, good): pass # write your code here``` where: - `n`: number of piles - `m`: upper bound on stones per pile - `k`: number of good indices - `good`: strictly increasing array of size `k`, `good[0] = 1`, and `1 = c1 < c2 < ... < ck ≤ n` - return: the sum of $x$ over all valid configurations modulo $10^9+7$ # Example: - Input: n = 2, m = 3 k = 1 good = [1] - Output: 18 # Constraints: - $1 \le n \le 20$ - $1 \le m \le @data$ - $1 \le k \le n$, and good indices satisfy $1=c_1> pos) & 1: afterMask = ((mask >> (pos + 1)) << pos) | (mask & ((1 << pos) - 1)) aliceRes = aliceRes or (dpPrev[afterMask][1] != 0) bobRes = bobRes and (dpPrev[afterMask][0] != 0) dpCurr[mask][0] = int(aliceRes) dpCurr[mask][1] = int(bobRes) dpPrev = dpCurr countByOnes = [0] * (n + 1) fullStates = 1 << n for mask in range(fullStates): if dpPrev[mask][0]: ones = bin(mask).count('1') countByOnes[ones] += 1 answer = 0 for val in range(1, m + 1): for ones in range(n + 1): if countByOnes[ones] == 0: continue term1 = pow(val - 1, n - ones, MOD) term2 = pow(m - val + 1, ones, MOD) ways = (term1 * term2) % MOD answer = (answer + ways * countByOnes[ones]) % MOD return answer def solve2(self, n, m, k, good): MOD = 1000000007 goodMask = 0 for idx in good: if 1 <= idx <= n: goodMask |= (1 << (idx - 1)) def insert(u, L, p): res = 0 lowMask = (1 << p) - 1 shiftHigh = p + 1 v = u while v: b = v & -v j = b.bit_length() - 1 low = j & lowMask high = j >> p idx0 = (high << shiftHigh) | low res |= 1 << idx0 res |= 1 << (idx0 | (1 << p)) v -= b return res prevAlice = 2 prevBob = 2 for length in range(2, n + 1): goodMaskLen = goodMask & ((1 << length) - 1) dpAliceBits = 0 dpBobBits = None for pos in range(length): if (goodMaskLen >> pos) & 1: insBob = insert(prevBob, length, pos) dpAliceBits |= insBob insAlice = insert(prevAlice, length, pos) if dpBobBits is None: dpBobBits = insAlice else: dpBobBits &= insAlice prevAlice = dpAliceBits prevBob = dpBobBits if dpBobBits is not None else 0 counts = [0] * (n + 1) x = prevAlice while x: b = x & -x j = b.bit_length() - 1 counts[j.bit_count()] += 1 x -= b answer = 0 for val in range(1, m + 1): for ones in range(n + 1): c = counts[ones] if c == 0: continue term1 = pow(val - 1, n - ones, MOD) term2 = pow(m - val + 1, ones, MOD) ways = (term1 * term2) % MOD answer = (answer + ways * c) % MOD return answer ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) good = [0] * k for i in range(k): good[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, k, good) sys.stdout.write(str(result) + ""\n"")",dp,hard 289,"# Problem Statement Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$. Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n` is the number of coins - `a` is the array of coin values - return the minimum number of pockets needed # Example 1: - Input: n = 6 a = [1, 2, 4, 3, 3, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): a.sort() ans = 0 pre = 0 cnt = 0 for i in range(n): if a[i] == pre: cnt += 1 ans = max(ans, cnt) else: cnt = 1 pre = a[i] ans = max(ans, cnt) return ans def solve2(self, n, a): ans = 0 for i in range(n): cnt = 0 x = a[i] for j in range(n): if a[j] == x: cnt += 1 if cnt > ans: ans = cnt return ans","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,sort",medium 290,"Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, ""ace"" is a subsequence of ""abcde"". solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""aabca"" Output: 3 Example 2: Input: s = ""adc"" Output: 0 Constraints: 3 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, s): first = [-1] * 26 last = [-1] * 26 for i in range(len(s)): curr = ord(s[i]) - ord('a') if first[curr] == -1: first[curr] = i last[curr] = i ans = 0 for i in range(26): if first[i] == -1: continue between = set() for j in range(first[i] + 1, last[i]): between.add(s[j]) ans += len(between) return ans def solve2(self, s): ans = 0 for li in range(26): ch = chr(ord('a') + li) L = s.find(ch) if L == -1: continue R = s.rfind(ch) if R <= L + 0: continue mask = 0 for j in range(L + 1, R): mask |= 1 << (ord(s[j]) - 97) cnt = 0 for k in range(26): if (mask >> k) & 1: cnt += 1 ans += cnt return ans ","import sys def main(): data = sys.stdin.buffer.read().split() if not data: return s = data[0].decode() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","string,bit_manipulation",hard 291,"Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""00110011"" Output: 6 Example 2: Input: s = ""10101"" Output: 4 Constraints: 1 <= s.length <= @data s[i] is either '0' or '1'. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s): curr = 1 prev = 0 ans = 0 for i in range(1, len(s)): if s[i] == s[i-1]: curr += 1 else: ans += min(curr, prev) prev = curr curr = 1 return ans + min(curr, prev) def solve2(self, s): n = len(s) ans = 0 for i in range(n - 1): if s[i] != s[i + 1]: left = i right = i + 1 cl = s[left] cr = s[right] while left >= 0 and right < n and s[left] == cl and s[right] == cr: ans += 1 left -= 1 right += 1 return ans ","import sys def main(): data = sys.stdin.read().split() if not data: s = """" else: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","two_pointers,string",medium 292,"Given a positive integer $k$, consider the increasing sequence formed by all sums of distinct powers of $k$. Equivalently, for each positive integer $N$, write $N$ in binary and replace the binary place value $2^i$ with $k^i$. For example, when $k = 3$, the sequence begins: $1, 3, 4, 9, 10, 12, 13, \ldots$ Find the value of the $N$-th item in this sequence, expressed as an integer in base 10. solution main function ```python class Solution: def solve(self, k, N): pass # write your code here ``` Pass in parameters: - `k`: the base used for powers. - `N`: the 1-indexed item position. Return parameters: An integer representing the answer. Example 1: Input: k = 3, N = 100 Output: 981 Constraints: 1 <= k <= 15 0 < N <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[200, 300, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, k, n): sum = 0 base = 1 for i in range(11): sum += ((n >> i) & 1) * base base *= k return sum def solve2(self, k, n): ans = 0 base = 1 while n > 0: if n & 1: ans += base base *= k n >>= 1 return ans ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) k = int(next(it)) N = int(next(it)) solution = Solution() result = solution.solve(k, N) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()",math,hard 293,"You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 2 Output: 2 Example 2: Input: n = 100 Output: 14 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: def solve1(self, n): tmp = int(math.sqrt(2 * n)) if tmp * (tmp + 1) >= 2 * n: return tmp return tmp + 1 def solve2(self, n): moves = 0 total = 0 while total < n: moves += 1 total += moves return moves ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))","dp,math",medium 294,"Child A is playing a message game with his friends. The rules of the game are as follows: There are n players, all of whom are numbered from 0 to n-1, and child A is numbered 0 Each player has a fixed number of other players to whom information can be transmitted (or not). The information transfer relationship is one-way (for example, A can send information to B, but B cannot send information to A). Each round of information must need to be passed to another person, and the information can be repeated through the same person Given the total number of players n, and the two-dimensional array relation formed by the [player number, corresponding to the passable player number] relation. Returns the number of schemes passed from minor A (number 0) to the small partner (number n-1) after k rounds; If it cannot be reached, return 0. The number of schemes is modded to 998244353 solution main function ```python class Solution: def solve(self, n, relation, k): pass # write your code here``` Example 1: Input: n = 5, base = [[0, 2], [2, 1], [3, 4], [2, 3], [1, 4], [2, 0], [0, 4]], k = 3 Output: 3 Example 2: Input: n = 3, relation = [[0,2],[2,1]], k = 2 Output: 0 Constraints: 2 <= n <= @data 1 <= k <= @data 1 <= relation.length <= 10*@data, and relation[i].length == 2 0 <= relation[i][0],relation[i][1] < n and relation[i][0]! = relation[i][1] Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, relation, k): mod = 998244353 dp = [0] * n dp[0] = 1 for i in range(k): nxt = [0] * n for src, dst in relation: if 0 <= src < n and 0 <= dst < n: nxt[dst] = (nxt[dst] + dp[src]) % mod dp = nxt return dp[n - 1] def solve2(self, n, relation, k): mod = 998244353 dp = [0] * n dp[0] = 1 B = 1000000000000000000 for _ in range(k): for i in range(n): dp[i] *= B for src, dst in relation: if 0 <= src < n and 0 <= dst < n: orig = dp[src] // B v = dp[dst] dp[dst] = (v // B) * B + ((v % B + orig) % mod) for i in range(n): dp[i] = dp[i] % B return dp[n - 1] % mod ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) relation = [] i = 1 while i <= m: x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) relation.append(temp) i += 1 k = int(next(it)) solution = Solution() result = solution.solve(n, relation, k) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","dp,graph",hard 295,"The middle order and post order of a binary tree are given. Find its preordering. (Convention tree nodes are represented by different capital letters). solution main function ```python class Solution: def solve(self, mid, suf): pass # write your code here``` Pass in parameters: Two strings of uppercase letters representing the middle and back order of a binary tree Return parameters: A string representing the first order of a binary tree. Example 1: Input: mid=""BADC"",suf=""BDCA"" Output: ""ABCD"" Constraints: The string length is less than or equal to @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[3, 5, 8]",4000,"[[64, 64, 64], [160, 80, 80], [1280, 640, 640]]","import sys class Solution: def dfs(self, mid, suf): if not mid: return """" ch = suf[-1] k = mid.find(ch) return ch + self.dfs(mid[:k], suf[:k]) + self.dfs(mid[k + 1:], suf[k:-1]) def solve1(self, mid, suf): return self.dfs(mid, suf) def solve2(self, mid, suf): n = len(mid) if n == 0: return """" out = [] stack = [(0, n - 1, 0, n - 1)] while stack: il, ir, pl, pr = stack.pop() if il > ir: continue root = suf[pr] out.append(root) i = il while i <= ir and mid[i] != root: i += 1 k = i left_len = k - il if k + 1 <= ir: stack.append((k + 1, ir, pl + left_len, pr - 1)) if il <= k - 1: stack.append((il, k - 1, pl, pl + left_len - 1)) return """".join(out) ","import sys data = sys.stdin.read().split() mid = """" suf = """" if len(data) > 0: mid = data[0] if len(data) > 1: suf = data[1] solution = Solution() result = solution.solve(mid, suf) sys.stdout.write(str(result) + ""\n"")",tree,easy 296,"Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: grid = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Example 2: Input: grid = [[7]] Output: 7 Constraints: n == grid.length == grid[i].length 1 <= n <= @data -99 <= grid[i][j] <= 99 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 500]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, grid): N = len(grid) prev_min1 = -1 prev_min2 = -1 for r in range(N - 1, -1, -1): cur_min1 = -1 cur_min2 = -1 for c in range(N): if r < N - 1: grid[r][c] += grid[r + 1][prev_min2] if prev_min1 == c else grid[r + 1][prev_min1] if cur_min1 == -1 or grid[r][c] < grid[r][cur_min1]: cur_min2 = cur_min1 cur_min1 = c elif cur_min2 == -1 or grid[r][c] < grid[r][cur_min2]: cur_min2 = c prev_min1 = cur_min1 prev_min2 = cur_min2 return grid[0][prev_min1] def solve2(self, grid): n = len(grid) if n == 0: return 0 for i in range(1, n): row_prev = grid[i - 1] for j in range(n): m = float('inf') for k in range(n): if k != j: v = row_prev[k] if v < m: m = v grid[i][j] += m last_row = grid[n - 1] ans = last_row[0] for j in range(1, n): if last_row[j] < ans: ans = last_row[j] return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): temp = [] for i in range(1, n + 1): x = int(next(it)) temp.append(x) num.append(temp) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))",greedy,medium 297,"# Problem Statement Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $n$ boxes, arranged in a row. The $i$-th box contains $a_i$ magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the $i$-th box was covered with a lid initially, he can either move the lid from the $i$-th box to the box $(i-1)$ (if it exists), or keep the lid on the $i$-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak. You have to calculate the maximum number of magazines Monocarp can save from the rain. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s, a): pass # write your code here``` Where: - `n` is an integer representing the number of boxes. - `s` is a string, where $s[i] = 1$ if the $i$-th box is covered with a lid, and $s[i] = 0$ otherwise. - `a` is an integer array, where $a[i]$ is the number of magazines in the $i$-th box. - The function should return an integer, representing the maximum number of magazines Monocarp can save from the rain. # Example 1 - Input: n = 4 s = ""0111"" a = [5, 4, 5, 1] - Output: 14 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import math import heapq class Solution: def solve1(self, n, s, a): s_list = list(s) j = -1 for i in range(n): if s_list[i] == '0': j = i elif j >= 0 and a[i] < a[j]: s_list[j], s_list[i] = s_list[i], s_list[j] j = i ans = 0 for i in range(n): if s_list[i] == '1': ans += a[i] return ans def solve2(self, n, s, a): ans = 0 j = -1 for i in range(n): if s[i] == '0': j = i else: if j >= 0 and a[i] < a[j]: ans += a[j] j = i else: ans += a[i] return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, s, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy",hard 298,"# Problem Statement An array `b` is called good if there do not exist indices `1 ≤ i < j ≤ |b|` such that `b_j - b_i = 1`. You are given an integer array `a` of length `n`. Determine the minimum number of elements that need to be removed from `a` so that it becomes a good array. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: the length of the array - `a`: the array of integers - return: the minimum number of elements to remove so that the array is good # Example 1: - Input: ``` n = 5 a = [1, 2, 3, 4, 5] ``` - Output: ``` 2 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[10, 10000, 100000]",4000,"[[1000, 750, 375], [8000, 6000, 3000], [64000, 48000, 24000]]","import sys class Solution: def solve1(self, n, a): for i in range(n): a[i] -= 1 at = [[] for _ in range(n)] for i in range(n): at[a[i]].append(i) ans = 0 for v in range(n - 1): mx = min(len(at[v]), len(at[v + 1])) low = 0 high = mx + 1 while low + 1 < high: mid = (low + high) // 2 ok = True for j in range(mid): if at[v][j] > at[v + 1][len(at[v + 1]) - mid + j]: ok = False break if ok: low = mid else: high = mid ans += low if low > 0: at[v + 1] = at[v + 1][:-low] return ans def solve2(self, n, a): ans = 0 prev_k = 0 for v in range(1, n): total_v = 0 total_w = 0 for x in a: if x == v: total_v += 1 elif x == v + 1: total_w += 1 early_v_count = total_v - prev_k if early_v_count < 0: early_v_count = 0 if early_v_count == 0 or total_w == 0: k = 0 else: cnt_v = 0 cnt_w = 0 maxDelta = 0 for x in a: if x == v: if cnt_v < early_v_count: cnt_v += 1 elif x == v + 1: cnt_w += 1 delta = cnt_w - cnt_v if delta > maxDelta: maxDelta = delta k = total_w - maxDelta if k > early_v_count: k = early_v_count if k < 0: k = 0 ans += k prev_k = k return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,data_structures",hard 299,"Given an array of integers num, compute the sum of all numbers that appear in odd-length contiguous subarrays of num. Return the answer modulo 998244353. Example 1: Input: num = [1,4,2,5,3] Output: 58 Example 2: Input: num = [1,2] Output: 3 Constraints: 1 <= num.length <= @data 1 <= num[i] <= 1000 Time limit: @time_limit ms Memory limit: @memory_limit KB solution main function ```python class Solution: def solve(self, num): pass # write your code here```","[100, 1000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, arr): mod = 998244353 n = len(arr) answer = 0 for i in range(n): left = i right = n - i - 1 answer += arr[i] * (left // 2 + 1) * (right // 2 + 1) answer %= mod answer += arr[i] * ((left + 1) // 2) * ((right + 1) // 2) answer %= mod return answer def solve2(self, arr): mod = 998244353 n = len(arr) ans = 0 for i in range(n): s = 0 for j in range(i, n): s = (s + arr[j]) % mod if ((j - i + 1) & 1) == 1: ans += s if ans >= mod: ans -= mod return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))",math,hard 300,"# Problem Statement Arseniy came up with another business plan — to sell soda from a vending machine! For this, he purchased a machine with $n$ shelves, as well as $k$ bottles, where the $i$-th bottle is characterized by the brand index $b_i$ and the cost $c_i$. You can place any number of bottles on each shelf, but all bottles on the same shelf must be of the same brand. Arseniy knows that all the bottles he puts on the shelves of the machine will be sold. Therefore, he asked you to calculate the **maximum** amount he can earn. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, bottle): pass # write your code here``` where: - `n`: the number of shelves, `k`: the number of bottles - `bottle`: the brand index $b_i$ and cost $c_i$ of each bottle - return: the maximum amount he can earn # Example 1: - Input: n = 3, k = 3 bottle = [(2, 6), (2, 7), (1, 15)] - Output: 28 # Constraints: - $1 \leq n, k \leq @data$ - $1 \leq bottle[i].first \leq k$ - $1 \leq bottle[i].second \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 64], [4000, 2000, 400], [32000, 16000, 3200]]","class Solution: def solve1(self, n, k, bottle): n = min(n, k) totals = [0] * k for b, c in bottle: if 1 <= b <= k: totals[b - 1] += c totals.sort(reverse=True) return sum(totals[:n]) def solve2(self, n, k, bottle): n = min(n, k) res = 0 length = len(bottle) if n <= 0 or length == 0: return 0 for _ in range(n): max_sum = 0 max_brand = 0 for i in range(length): b, c = bottle[i] if c <= 0 or b < 1 or b > k: continue s = 0 for j in range(length): bj, cj = bottle[j] if cj > 0 and bj == b: s += cj if s > max_sum: max_sum = s max_brand = b if max_sum == 0: break res += max_sum for i in range(length): b, c = bottle[i] if c > 0 and b == max_brand: bottle[i] = (b, 0) return res ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) bottle = [] available_pairs = max(0, (len(data) - 2) // 2) pairs_to_read = min(k, available_pairs) for _ in range(pairs_to_read): first = int(next(it)) second = int(next(it)) bottle.append((first, second)) solution = Solution() result = solution.solve(n, k, bottle) sys.stdout.write(str(result) + ""\n"")","greedy,sort",easy 301,"There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node. solution main function ```python class Solution: def solve(self, n, e, re): pass # write your code here``` Example 1: Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] Output: 4 Example 2: Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] Output: 3 Constraints: 2 <= n <= @data edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree. 1 <= restricted.length < n 1 <= restricted[i] < n All the values of restricted are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 1000, 100000]",4000,"[[11718, 1171, 117], [93750, 9375, 937], [750000, 75000, 7500]]","class Solution: def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def unionSet(self, a, b): a = self.find(a) b = self.find(b) if a != b: if self.sz[a] > self.sz[b]: a, b = b, a self.p[a] = b self.sz[b] += self.sz[a] def solve1(self, n, edges, restricted): self.p = list(range(n + 1)) self.sz = [1] * (n + 1) self.r = [False] * (n + 1) for x in restricted: self.r[x] = True for e in edges: if not self.r[e[1]] and not self.r[e[0]]: self.unionSet(e[0], e[1]) return self.sz[self.find(0)] def solve2(self, n, edges, restricted): count = 1 for i in range(len(edges)): if edges[i][0] == 0: edges[i][0] = -1 if edges[i][1] == 0: edges[i][1] = -1 while True: changed = False for i in range(len(edges)): a = edges[i][0] b = edges[i][1] av = a < 0 bv = b < 0 if av != bv: candidate = b if av else a is_restricted = False for r in restricted: if r == candidate: is_restricted = True break if not is_restricted: neg = -candidate - 1 for j in range(len(edges)): if edges[j][0] == candidate: edges[j][0] = neg if edges[j][1] == candidate: edges[j][1] = neg count += 1 changed = True if not changed: break return count ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) e = [] re = [] for i in range(1, n): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) e.append(temp) for i in range(1, m + 1): x = int(next(it)) re.append(x) solution = Solution() result = solution.solve(n, e, re) sys.stdout.write(str(result))",graph,medium 302,"# Problem Statement Nene invented a new game based on an increasing sequence of integers $a_1, a_2, \ldots, a_k$. In this game, initially $n$ players are lined up in a row. In each of the rounds of this game, the following happens: - Nene finds the $a_1$-th, $a_2$-th, $\ldots$, $a_k$-th players in a row. They are kicked out of the game simultaneously. If the $i$-th player in a row should be kicked out, but there are fewer than $i$ players in a row, they are skipped. Once no one is kicked out of the game in some round, all the players that are still in the game are declared as winners. For example, consider the game with $a=[3, 5]$ and $n=5$ players. Let the players be named player A, player B, $\ldots$, player E in the order they are lined up initially. Then, - Before the first round, players are lined up as ABCDE. Nene finds the $3$-rd and the $5$-th players in a row. These are players C and E. They are kicked out in the first round. - Now players are lined up as ABD. Nene finds the $3$-rd and the $5$-th players in a row. The $3$-rd player is player D and there is no $5$-th player in a row. Thus, only player D is kicked out in the second round. - In the third round, no one is kicked out of the game, so the game ends after this round. - Players A and B are declared as the winners. Nene has not yet decided how many people would join the game initially. Nene gave you $q$ integers $n_1, n_2, \ldots, n_q$ and you should answer the following question for each $1 \le i \le q$ **independently**: - How many people would be declared as winners if there are $n_i$ players in the game initially? The main function of the solution is defined as: ```python class Solution: def solve(self, k, q, a, n): pass # write your code here``` where: - `k` represents the length of `a`, `q` represents the length of `n` - `a` represents the increasing sequence of integers, `n` represents the number of players - return the array of the number of winners for each `n`, and the length is `q` # Example 1: - Input: k = 2, q = 1 a = [3, 5] n = [5] - Output: [2] # Constraints: - $1 \leq k, q \leq @data$ - $1 \leq a[i], n[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",4000,"[[500, 100, 64], [4000, 800, 400], [32000, 6400, 3200]]","import math class Solution: def solve1(self, k, q, a, n): p = a[0] res = [str(min(p - 1, n[i])) for i in range(q)] return res def solve2(self, k, q, a, n): limit = a[0] - 1 res = [0] * q for i in range(q): v = n[i] if v > limit: res[i] = limit else: res[i] = v return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) k = int(next(it)) q = int(next(it)) a = [0] * k n = [0] * q for i in range(k): a[i] = int(next(it)) for i in range(q): n[i] = int(next(it)) solution = Solution() result = solution.solve(k, q, a, n) out = [] for x in result: out.append(str(x)) sys.stdout.write("" "".join(out) + ""\n"")","greedy,data_structures,binary",hard 303,"You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 13 Output: 4 Example 2: Input: n = 2 Output: 2 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, n): cnt = 0 v = [0] * 40 for i in range(1, n + 1): x = i s = 0 while x: s += x % 10 x //= 10 v[s] += 1 maxi = 0 if v: maxi = max(v) for i in v: if i == maxi: cnt += 1 return cnt def solve2(self, n): t = n digits = 0 while t > 0: digits += 1 t //= 10 S = digits * 9 max_freq = 0 count_max = 0 s = 1 while s <= S: cnt = 0 if n >= 1: i = 1 sum_d = 1 while True: if sum_d == s: cnt += 1 if i == n: break y = i t9 = 0 while y % 10 == 9: t9 += 1 y //= 10 sum_d += 1 - 9 * t9 i += 1 if cnt > max_freq: max_freq = cnt count_max = 1 elif cnt == max_freq: count_max += 1 s += 1 return count_max ","import sys def main(): data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","string,other",easy 304,"Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. solution main function ```python class Solution: def solve(self, n, m): pass # write your code here``` Example 1: Input: n = 34, k = 6 Output: 9 Example 2: Input: n = 10, k = 10 Output: 1 Constraints: 1 <= n <= @data 2 <= k <= 10 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, n, k): res = 0 while n > 0: res += n % k n //= k return res def solve2(self, n, k): res = 0 while n > 0: res += n % k n //= k return res ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",math,easy 305,"# Problem Statement: You are given $n$ of integers $a_1, a_2, \ldots, a_n$. Process $q$ queries of two types: - query of the form ""0 $x_j$"": add the value $x_j$ to all even elements of the array $a$, - query of the form ""1 $x_j$"": add the value $x_j$ to all odd elements of the array $a$. Note that when processing the query, we look specifically at the odd/even value of $a_i$, not its index. After processing each query, print the sum of the elements of the array $a$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, q, a, queries): pass # write your code here``` Where: - `n` is an integer representing the size of the array $a$. - `q` is an integer representing the number of queries. - `a` is a vector of integers, representing the initial array. - `queries` is a vector of pairs, where each pair represents a query of the given type and value. - The function should return a vector of long long integers, representing the sum of the array after processing each query. # Example 1: - Input: n = 1 q = 1 a = [1] queries = [(1, 1)] - Output: [2] # Constraints: - $1 \leq n, q \leq @data$ - $1 \leq a[i] \leq 10^9$ - $1 \leq x_j \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 100], [4000, 2000, 800], [32000, 16000, 6400]]","import sys class Solution: def solve1(self, n, q, a, queries): cnt = [0, 0] sums = [0, 0] for x in a: parity = x % 2 cnt[parity] += 1 sums[parity] += x ans = [] for i in range(q): t = queries[i][0] x = queries[i][1] sums[t] += x * cnt[t] if x % 2 != 0: cnt[1 - t] += cnt[t] sums[1 - t] += sums[t] cnt[t] = 0 sums[t] = 0 ans.append(sums[0] + sums[1]) return ans def solve2(self, n, q, a, queries): res = [] for t, x in queries: s = 0 if t == 0: for i in range(n): if (a[i] & 1) == 0: a[i] += x s += a[i] else: for i in range(n): if (a[i] & 1) == 1: a[i] += x s += a[i] res.append(s) return res","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) q = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) queries = [] for i in range(q): first = int(next(it)) second = int(next(it)) queries.append((first, second)) solution = Solution() result = solution.solve(n, q, a, queries) out_lines = [] for x in result: out_lines.append(str(x)) sys.stdout.write(""\n"".join(out_lines))",math,medium 306,"You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. A subarray is a contiguous part of an array. solution main function ```python class Solution: def solve(self, num, k): pass # write your code here``` Example 1: Input: nums = [0,1,0], k = 1 Output: 2 Example 2: Input: nums = [1,1,0], k = 2 Output: -1 Constraints: 1 <= nums.length <= @data 1 <= k <= nums.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import collections class Solution: def solve1(self, nums, k): ans = 0 n = len(nums) cnt = 0 for i in range(n): if i >= k and nums[i - k] > 1: cnt ^= 1 nums[i - k] -= 2 if nums[i] == cnt: if i + k > n: return -1 cnt ^= 1 nums[i] += 2 ans += 1 return ans def solve2(self, nums, k): n = len(nums) ans = 0 end = n - k + 1 for i in range(end): if nums[i] == 0: ans += 1 j = i lim = i + k while j < lim: nums[j] ^= 1 j += 1 for i in range(end, n): if nums[i] == 0: return -1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num, k) sys.stdout.write(str(result))",bit_manipulation,medium 307,"You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example: Input: prices = [1,2,2], money = 3 Output: 0 Explanation: Buy chocolates with prices 1 and 2, leaving 0 money. Constraints: 2 <= prices.length <= @data 1 <= prices[i] <= @data 1 <= money <= 2*@data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, prices, money): prices1 = float('inf') prices2 = float('inf') for k in prices: if k < prices1: prices2 = prices1 prices1 = k elif k < prices2: prices2 = k if prices1 + prices2 > money: return money else: return money - (prices1 + prices2) def solve2(self, prices, money): best = None n = len(prices) for i in range(n - 1): pi = prices[i] for j in range(i + 1, n): s = pi + prices[j] if s <= money: if best is None or s < best: best = s if best is None: return money return money - best ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) k = int(next(it)) solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result) + ""\n"")","greedy,sort",medium 308,"Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. The answer is modulus 998244353. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[1000, 500, 250], [8000, 4000, 2000], [64000, 32000, 16000]]","class Solution: mod = 998244353 def solve1(self, n): C = 1 inv = [0] * (n + 3) inv[0] = 1 inv[1] = 1 for i in range(2, n + 2): inv[i] = ((self.mod - self.mod // i) * inv[self.mod % i]) % self.mod for i in range(n): C = C * 2 % self.mod * (2 * i + 1) % self.mod * inv[i + 2] % self.mod return C def power(self, x, y): temp = 1 while y: if y & 1: temp = temp * x % self.mod x = x * x % self.mod y >>= 1 return temp def solve2(self, n): C = 1 for i in range(n): C = C * 2 % self.mod * (2 * i + 1) % self.mod * self.power(i + 2, self.mod - 2) % self.mod return C ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,medium 309,"# Problem Statement You are given a string $s$, consisting of digits from $0$ to $9$. In one operation, you can pick any digit in this string, except for $0$ or the leftmost digit, decrease it by $1$, and then swap it with the digit left to the picked. For example, in one operation from the string $1023$, you can get $1103$ or $1022$. Find the lexicographically maximum string you can obtain after any number of operations. The main function of the solution is defined as: ```python class Solution: def solve(self, s): pass # write your code here``` where: - return: the lexicographically maximum string you can obtain after any number of operations. # Example 1: - Input: ""19"" - Output: ""81"" # Constraints: - $1 \leq s.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s: str) -> str: s_list = list(s) n = len(s_list) for i in range(n): k = i for j in range(i, min(n, i + 10)): if int(s_list[j]) - j > int(s_list[k]) - k: k = j while k > i: val = int(s_list[k]) s_list[k] = str(val - 1) s_list[k - 1], s_list[k] = s_list[k], s_list[k - 1] k -= 1 return """".join(s_list) def solve2(self, s: str) -> str: s_list = list(s) n = len(s_list) for i in range(1, n): j = i while j > 0 and s_list[j] != '0': new_char_ord = ord(s_list[j]) - 1 if new_char_ord <= ord(s_list[j - 1]): break left_char = s_list[j - 1] s_list[j - 1] = chr(new_char_ord) s_list[j] = left_char j -= 1 return """".join(s_list) ","import sys s = sys.stdin.buffer.readline().decode().strip() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")","string,greedy,math",hard 310,"# Problem Statement There is a grid, consisting of $2$ rows and $n$ columns. Each cell of the grid is either free or blocked. A free cell $y$ is reachable from a free cell $x$ if at least one of these conditions holds: - $x$ and $y$ share a side; - there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is reachable from $z$. A connected region is a set of free cells of the grid such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule. The given grid contains at most $1$ connected region. Your task is to calculate the number of free cells meeting the following constraint: - if this cell is blocked, the number of connected regions becomes exactly $3$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s1, s2): pass # write your code here``` where: - `s1` and `s2` are two strings of two rows of the grid, each character is `.` or `x`, `.` means free, `x` means blocked - return the maximum number of free cells that meet the condition # Example 1: - Input: n = 8 s1 = "".......x"" s2 = "".x.xx..."" - Output: 1 # Constraints: - $1 \leq n \leq @data$ - The given grid contains at most $1$ connected region - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve(self, n, s1, s2): ans = 0 for i in range(1, n - 1): if (s1[i] == '.' and s1[i - 1] == '.' and s1[i + 1] == '.' and s2[i] == '.' and s2[i - 1] == 'x' and s2[i + 1] == 'x'): ans += 1 if (s2[i] == '.' and s2[i - 1] == '.' and s2[i + 1] == '.' and s1[i] == '.' and s1[i - 1] == 'x' and s1[i + 1] == 'x'): ans += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s1 = next(it) s2 = next(it) solution = Solution() result = solution.solve(n, s1, s2) sys.stdout.write(str(result) + ""\n"")",two_pointers,medium 311,"Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: nums = [3,10,5,25,2,8] Output: 28 Example 2: Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] Output: 127 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 2^31 - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[1000, 200, 100], [8000, 1600, 800], [64000, 12800, 6400]]","import math class Solution: def solve1(self, nums): maxv = 0 if nums: maxv = max(nums) if maxv == 0: return 0 high = maxv.bit_length() - 1 ans = 0 mask = 0 for i in range(high, -1, -1): seen = set() mask |= (1 << i) tmp = ans | (1 << i) for x in nums: prefix = x & mask if (tmp ^ prefix) in seen: ans = tmp break seen.add(prefix) return ans def solve2(self, nums): n = len(nums) if n == 0: return 0 ans = 0 for i in range(n): a = nums[i] for j in range(i, n): v = a ^ nums[j] if v > ans: ans = v return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result))","STL,bit_manipulation",medium 312,"# Problem Statement There is a rectangular maze of size $n\times m$. Denote $(r,c)$ as the cell on the $r$-th row from the top and the $c$-th column from the left. Two cells are adjacent if they share an edge. A path is a sequence of adjacent empty cells. Each cell is initially empty. Li Hua can choose some cells (except $(x_1, y_1)$ and $(x_2, y_2)$) and place an obstacle in each of them. He wants to know the minimum number of obstacles needed to be placed so that there isn't a path from $(x_1, y_1)$ to $(x_2, y_2)$. Suppose you were Li Hua, please solve this problem. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, x1, y1, x2, y2): pass # write your code here``` where: - return the minimum number of obstacles needed to be placed. # Example 1: - Input: n = 4, m = 4 x1 = 2, y1 = 2, x2 = 3, y2 = 3 - Output: 4 # Constraints: - $4 \leq n, m \leq @data$ - $1 \leq x1, x2 \leq n$ - $1 \leq y1, y2 \leq m$ - It is guaranteed that $(x_1, y_1)$ and $(x_2, y_2)$ are **not** adjacent (i.e., they do not share an edge). - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 100000, 10000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, m, x1, y1, x2, y2): ans = min( (x1 != 1) + (x1 != n) + (y1 != 1) + (y1 != m), (x2 != 1) + (x2 != n) + (y2 != 1) + (y2 != m) ) return ans def solve2(self, n, m, x1, y1, x2, y2): d1 = (x1 != 1) + (x1 != n) + (y1 != 1) + (y1 != m) d2 = (x2 != 1) + (x2 != n) + (y2 != 1) + (y2 != m) return min(d1, d2) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) x1 = int(next(it)) y1 = int(next(it)) x2 = int(next(it)) y2 = int(next(it)) solution = Solution() result = solution.solve(n, m, x1, y1, x2, y2) sys.stdout.write(str(result) + ""\n"")",graph,easy 313,"# Problem Statement Pak Chanek has an array $a$ of $n$ positive integers. Since he is currently learning how to calculate the floored average of two numbers, he wants to practice it on his array $a$. While the array $a$ has at least two elements, Pak Chanek will perform the following three-step operation: 1. Pick two different indices $i$ and $j$ ($1 \leq i, j \leq |a|$; $i \neq j$), note that $|a|$ denotes the current size of the array $a$. 2. Append $\lfloor \frac{a_i+a_j}{2} \rfloor$$^{\text{∗}}$ to the end of the array. 3. Remove elements $a_i$ and $a_j$ from the array and concatenate the remaining parts of the array. For example, suppose that $a=[5,4,3,2,1,1]$. If we choose $i=1$ and $j=5$, the resulting array will be $a=[4,3,2,1,3]$. If we choose $i=4$ and $j=3$, the resulting array will be $a=[5,4,1,1,2]$. After all operations, the array will consist of a single element $x$. Find the maximum possible value of $x$ if Pak Chanek performs the operations optimally. $^{\text{∗}}$$\lfloor x \rfloor$ denotes the floor function of $x$, which is the greatest integer that is less than or equal to $x$. For example, $\lfloor 6 \rfloor = 6$, $\lfloor 2.5 \rfloor=2$, $\lfloor -3.6 \rfloor=-4$ and $\lfloor \pi \rfloor=3$ The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return:the maximum possible value of x after all numbers have been picked. # Example 1: - Input: n = 5 a = [1, 7, 8, 4, 5] - Output: 6 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): a.sort() ans = a[0] for i in range(1, n): ans = (ans + a[i]) // 2 return ans def solve2(self, n, a): if n == 0: return 0 min_idx = 0 for i in range(1, n): if a[i] < a[min_idx]: min_idx = i a[0], a[min_idx] = a[min_idx], a[0] ans = a[0] for k in range(1, n): min_idx = k for i in range(k + 1, n): if a[i] < a[min_idx]: min_idx = i a[k], a[min_idx] = a[min_idx], a[k] ans = (ans + a[k]) // 2 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,greedy,math,sort",hard 314,"# Problem Statement There is an $n \times m$ grid. Each cell can contain any number of indistinguishable tokens. Initially, there are $k$ tokens, the $i$-th of which is at cell $(x_i, y_i)$ ($1 \le x_i \le n$, $1 \le y_i \le m$). Two players, Mimo and Yuyu, play a game alternately. On a turn, a player chooses a token $c$ currently in the grid and a sequence of distinct cells $(a_1,b_1),(a_2,b_2),\dots,(a_p,b_p)$ ($p \ge 2$) such that: - $c$ is located at $(a_1,b_1)$, - adjacent cells in the sequence are grid-adjacent: $|a_{i+1}-a_i| + |b_{i+1}-b_i| = 1$, - columns are non-increasing: $b_1 \ge b_2 \ge \dots \ge b_p$, - the last cell is in column 1: $b_p = 1$, - and $b_1 > b_2$ (thus $b_2 = b_1 - 1$). Then the player removes $c$ from $(a_1,b_1)$ and adds 1 token to each of $(a_2,b_2),\dots,(a_p,b_p)$. The player who cannot move loses. Mimo moves first. Determine the winner assuming optimal play. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, xs, ys): pass # write your code here``` where: - `n`, `m`: grid dimensions, - `k`: number of tokens, - `xs[i]`, `ys[i]`: position of the i-th token, - return: `""Mimo""` if the first player wins, otherwise `""Yuyu""`. # Example 1: - Input: n = 6, m = 4, k = 3 (2,3), (4,2), (6,4) - Output: Mimo # Constraints: - $1 \le n, m, k \le @data$ - $1 \le x_i \le n$, $1 \le y_i \le m$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, m, k, xs, ys): if k == 0: return ""Yuyu"" if n == 1: parity = 0 for i in range(k): if ys[i] == 2: parity ^= 1 return ""Mimo"" if parity else ""Yuyu"" parity_by_col = [0] * (m + 1) for i in range(k): y = ys[i] if y > 1: parity_by_col[y] ^= 1 for col in range(2, m + 1): if parity_by_col[col]: return ""Mimo"" return ""Yuyu"" def solve2(self, n, m, k, xs, ys): if k == 0: return ""Yuyu"" if n == 1: parity = 0 for i in range(k): if ys[i] == 2: parity ^= 1 return ""Mimo"" if parity else ""Yuyu"" for col in range(2, m + 1): parity = 0 for i in range(k): if ys[i] == col: parity ^= 1 if parity: return ""Mimo"" return ""Yuyu"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) xs = [0] * k ys = [0] * k for i in range(k): xs[i] = int(next(it)) ys[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, k, xs, ys) sys.stdout.write(str(result) + ""\n"")",math,hard 315,"You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. solution main function ```python class Solution: def solve(self, n, m): pass # write your code here``` Example 1: Input: lowLimit = 1, highLimit = 10 Output: 2 Example 2: Input: lowLimit = 5, highLimit = 15 Output: 2 Constraints: 1 <= lowLimit <= highLimit <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def _sum(self, n): s = 0 while n > 0: s += n % 10 n //= 10 return s def solve1(self, lowLimit, highLimit): cnt = [0] * 46 m = 0 for n in range(lowLimit, highLimit + 1): box = self._sum(n) cnt[box] += 1 m = max(m, cnt[box]) return m def solve2(self, lowLimit, highLimit): digits = 1 t = highLimit while t >= 10: t //= 10 digits += 1 max_sum = 9 * digits ans = 0 s = 0 while s <= max_sum: cnt = 0 i = lowLimit while i <= highLimit: if self._sum(i) == s: cnt += 1 i += 1 if cnt > ans: ans = cnt s += 1 return ans","import sys data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) m = int(next(it)) except StopIteration: n = 0 m = 0 solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result))",sort,easy 316,"Given an integer number n, return the difference between the product of its digits and the sum of its digits. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 234 Output: 15 Example 2: Input: n = 4421 Output: 21 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, n: int) -> int: s = 0 p = 1 while n > 0: digit = n % 10 s += digit p *= digit n //= 10 return p - s def solve2(self, n: int) -> int: s = 0 p = 1 if n == 0: return 0 while n > 0: d = n % 10 s += d p *= d n //= 10 return p - s ","import sys def main(): data = sys.stdin.read().strip().split() it = iter(data) try: n = int(next(it)) except StopIteration: return solution = Solution() result = solution.solve(n) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","math,other",easy 317,"An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. Any student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 10^9 + 7. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 2 Output: 8 Example 2: Input: n = 1 Output: 3 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n): MOD = 1000000007 dp_curr_state = [[0] * 3 for _ in range(2)] dp_next_state = [[0] * 3 for _ in range(2)] dp_curr_state[0][0] = 1 for _ in range(n): for total_absences in range(2): for consecutive_lates in range(3): dp_next_state[total_absences][0] = ( dp_next_state[total_absences][0] + dp_curr_state[total_absences][consecutive_lates] ) % MOD if total_absences < 1: dp_next_state[total_absences + 1][0] = ( dp_next_state[total_absences + 1][0] + dp_curr_state[total_absences][consecutive_lates] ) % MOD if consecutive_lates < 2: dp_next_state[total_absences][consecutive_lates + 1] = ( dp_next_state[total_absences][consecutive_lates + 1] + dp_curr_state[total_absences][consecutive_lates] ) % MOD dp_curr_state = dp_next_state dp_next_state = [[0] * 3 for _ in range(2)] count = 0 for total_absences in range(2): for consecutive_lates in range(3): count = (count + dp_curr_state[total_absences][consecutive_lates]) % MOD return count def solve2(self, n): MOD = 1000000007 if n == 1: return 3 if n == 2: return 8 a = 1 b = 2 c = 4 f_nm3 = 0 f_nm2 = 0 f_nm1 = 0 f_n = 0 for k in range(3, n + 1): new = (a + b + c) % MOD if k == n: f_nm3 = a f_nm2 = b f_nm1 = c f_n = new a, b, c = b, c, new noA = f_n a0, a1, a2 = 1, 2, 4 b0, b1, b2 = f_nm1, f_nm2, f_nm3 sumA = 0 for _ in range(n): sumA = (sumA + a0 * b0) % MOD nextF = (a0 + a1 + a2) % MOD a0, a1, a2 = a1, a2, nextF nextBack = (b0 - b1 - b2) % MOD b0, b1, b2 = b1, b2, nextBack return (noA + sumA) % MOD ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")",dp,hard 318,"You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. In one operation, you will create a new array arr, and for each i: If i % 2 == 0, then arr[i] = perm[i / 2]. If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. You will then assign arr​​​​ to perm. Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 2 Output: 1 Example 2: Input: n = 4 Output: 2 Constraints: 2 <= n <= @data n​​​​​​ is even. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","class Solution: def solve1(self, n): halfLen = n >> 1 ret = 0 num1Id = 1 while True: if num1Id < halfLen: num1Id <<= 1 else: num1Id = (num1Id << 1) - n + 1 ret += 1 if num1Id == 1: break return ret def solve2(self, n): halfLen = n >> 1 ret = 0 num1Id = 1 while True: if num1Id < halfLen: num1Id <<= 1 else: num1Id = (num1Id << 1) - n + 1 ret += 1 if num1Id == 1: break return ret ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,hard 319,"You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values: 0 represents an empty cell, 1 represents an obstacle that may be removed. You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1). solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: grid = [[0,1,1],[1,1,0],[1,1,0]] Output: 2 Example 2: Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data 2 <= m * n <= @data grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[20000, 10000, 5000], [160000, 80000, 40000], [1280000, 640000, 320000]]","import collections class Solution: def solve1(self, grid): m = len(grid) n = len(grid[0]) distance = [[float('inf')] * n for _ in range(m)] dq = collections.deque() distance[0][0] = 0 dq.appendleft((0, 0)) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] while dq: x, y = dq.popleft() for dx, dy in directions: nx = x + dx ny = y + dy if 0 <= nx < m and 0 <= ny < n: newDist = distance[x][y] + grid[nx][ny] if newDist < distance[nx][ny]: distance[nx][ny] = newDist if grid[nx][ny] == 0: dq.appendleft((nx, ny)) else: dq.append((nx, ny)) return distance[m-1][n-1] def solve2(self, grid): m = len(grid) n = len(grid[0]) grid[0][0] = 2 changed = True while changed: changed = False for i in range(m): for j in range(n): v = grid[i][j] c = v % 2 best = None if i > 0: vn = grid[i - 1][j] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if j > 0: vn = grid[i][j - 1] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if i + 1 < m: vn = grid[i + 1][j] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if j + 1 < n: vn = grid[i][j + 1] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if best is not None: if v < 2 or best < ((v - 2) // 2): grid[i][j] = 2 + 2 * best + c changed = True for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): v = grid[i][j] c = v % 2 best = None if i > 0: vn = grid[i - 1][j] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if j > 0: vn = grid[i][j - 1] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if i + 1 < m: vn = grid[i + 1][j] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if j + 1 < n: vn = grid[i][j + 1] if vn >= 2: nd = ((vn - 2) // 2) + c if best is None or nd < best: best = nd if best is not None: if v < 2 or best < ((v - 2) // 2): grid[i][j] = 2 + 2 * best + c changed = True v = grid[m - 1][n - 1] if v >= 2: return (v - 2) // 2 return 0 ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")","graph,search",medium 320,"# Problem Statement You are given an array $a_1, a_2, \ldots, a_n$ of positive integers. You can color some elements of the array red, but there cannot be two adjacent red elements (i.e., for $1 \leq i \leq n-1$, at least one of $a_i$ and $a_{i+1}$ must not be red). Your score is the maximum value of a red element plus the number of red elements. Find the maximum score you can get. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the maximum score you can get # Example 1: - Input: n = 3 a = [5, 4, 5] - Output: 7 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, a): mx1 = 0 mx2 = 0 cnt1 = 0 cnt2 = 0 for i in range(n): if i % 2: mx1 = max(mx1, a[i]) cnt1 += 1 else: mx2 = max(mx2, a[i]) cnt2 += 1 return max(mx1 + cnt1, mx2 + cnt2) def solve2(self, n, a): ans = 0 for j in range(n): left = j - 1 if left < 0: left = 0 right = n - j - 2 if right < 0: right = 0 cnt = 1 + (left + 1) // 2 + (right + 1) // 2 val = a[j] + cnt if val > ans: ans = val return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy",hard 321,"# Problem Statement Gridlandia has been hit by flooding and now has to reconstruct all of it's cities. Gridlandia can be described by an $n \times m$ matrix. Initially, all of its cities are in economic collapse. The government can choose to rebuild certain cities. Additionally, any collapsed city which has at least one vertically neighboring rebuilt city and at least one horizontally neighboring rebuilt city can ask for aid from them and become rebuilt **without help from the government**. More formally, collapsed city positioned in $(i, j)$ can become rebuilt if **both** of the following conditions are satisfied: - At least one of cities with positions $(i + 1, j)$ and $(i - 1, j)$ is rebuilt; - At least one of cities with positions $(i, j + 1)$ and $(i, j - 1)$ is rebuilt. If the city is located on the border of the matrix and has only one horizontally or vertically neighbouring city, then we consider only that city. The government wants to know the minimum number of cities it has to rebuild such that **after some time** all the cities can be rebuild. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m): pass # write your code here``` where: - `n` is the column number of the cities, and `m` is the row number of the cities - return the minimum number of cities that need to be rebuilt # Example 1: - Input: n = 2, m = 2 - Output: 2 # Constraints: - $1 \leq n, m \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 1000000, 100000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, m): return max(n, m) def solve2(self, n, m): return max(n, m) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) solution = Solution() result = solution.solve(n, m) sys.stdout.write(str(result) + ""\n"")","math,sort,data_structures",hard 322,"# Problem Statement Monocarp is working on his new site, and the current challenge is to make the users pick strong passwords. Monocarp decided that strong passwords should satisfy the following conditions: - password should consist only of lowercase Latin letters and digits; - there should be no digit that comes after a letter (so, after each letter, there is either another letter or the string ends); - all digits should be sorted in the non-decreasing order; - all letters should be sorted in the non-decreasing order. Note that it's allowed for the password to have only letters or only digits. Monocarp managed to implement the first condition, but he struggles with the remaining ones. Can you help him to verify the passwords? The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return ""YES"" if the given password is strong and ""NO"" otherwise. # Example 1: - Input: n = 4 s = ""12ac"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n: int, s: str) -> str: is_s_sorted = True for i in range(n - 1): if s[i] > s[i + 1]: is_s_sorted = False break if is_s_sorted: return ""YES"" else: return ""NO"" def solve2(self, n: int, s: str) -> str: prev_digit = '' prev_letter = '' seen_letter = False for i in range(n): c = s[i] if '0' <= c <= '9': if seen_letter: return ""NO"" if prev_digit and c < prev_digit: return ""NO"" prev_digit = c elif 'a' <= c <= 'z': if prev_letter and c < prev_letter: return ""NO"" prev_letter = c seen_letter = True else: return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","sort,string",easy 323,"You are given a 0-indexed integer array nums and a positive integer k. You can apply the following operation on the array any number of times: Choose any element of the array and flip a bit in its binary representation. Flipping a bit means changing a 0 to 1 or vice versa. Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k. Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2. solution main function ```python class Solution: def solve(self, num, k): pass # write your code here``` Example 1: Input: nums = [2,1,3,4], k = 1 Output: 2 Example 2: Input: nums = [2,0,2,0], k = 0 Output: 0 Constraints: 1 <= nums.length <= @data 0 <= nums[i] <= 10^6 0 <= k <= 10^6 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import functools import operator class Solution: def solve1(self, nums, k): finalXor = 0 for n in nums: finalXor = finalXor ^ n return (finalXor ^ k).bit_count() def solve2(self, nums, k): x = 0 for v in nums: x ^= v y = x ^ k c = 0 while y: y &= y - 1 c += 1 return c ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 solution = Solution() result = solution.solve(num, k) sys.stdout.write(str(result) + ""\n"") return 0 if __name__ == ""__main__"": main()",bit_manipulation,medium 324,"# Problem Statement Dima Vatrushin is a math teacher at school. He was sent on vacation for $n$ days for his good work. Dima has long dreamed of going to a ski resort, so he wants to allocate several **consecutive days** and go skiing. Since the vacation requires careful preparation, he will only go for **at least $k$ days**. You are given an array $a$ containing the weather forecast at the resort. That is, on the $i$-th day, the temperature will be $a_i$ degrees. Dima was born in Siberia, so he can go on vacation only if the temperature does not rise above $q$ degrees throughout the vacation. Unfortunately, Dima was so absorbed in abstract algebra that he forgot how to count. He asks you to help him and count the number of ways to choose vacation dates at the resort. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, q, a): pass # write your code here``` where: - return: the number of ways for Dima to choose vacation dates at the resort, please use `long long` type. # Example 1: - Input: n = 3, k = 1, q = 15 a = [-5, 0, -10] - Output: 6 # Constraints: - $1 \leq k \leq n \leq @data$ - $-10^9 \leq a[i], q \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, k, q, a): ans = 0 suf = 0 for x in a: suf = suf + 1 if x <= q else 0 ans += max(0, suf - k + 1) return ans def solve2(self, n, k, q, a): ans = 0 for i in range(n): if a[i] > q: continue length = 0 for j in range(i, n): if a[j] > q: break length += 1 if length >= k: ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) q = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, q, a) sys.stdout.write(str(result) + ""\n"")","math,two_pointers",medium 325,"# Problem Statement Mocha likes arrays, so before her departure, Chamo gave her an array $a$ consisting of $n$ positive integers as a gift. Mocha doesn't like arrays containing different numbers, so Mocha decides to use magic to change the array. Mocha can perform the following three-step operation some (possibly, zero) times: 1. Choose indices $l$ and $r$ ($1 \leq l \lt r \leq n$) 2. Let $x$ be the median$^\dagger$ of the subarray $[a_l, a_{l+1},\ldots, a_r]$ 3. Set all values $a_l, a_{l+1},\ldots, a_r$ to $x$ Suppose $a=[1,2,3,4,5]$ initially: - If Mocha chooses $(l,r)=(3,4)$ in the first operation, then $x=3$, the array will be changed into $a=[1,2,3,3,5]$. - If Mocha chooses $(l,r)=(1,3)$ in the first operation, then $x=2$, the array will be changed into $a=[2,2,2,4,5]$. Mocha will perform the operation until the array contains only the same number. Mocha wants to know what is the maximum possible value of this number. $^\dagger$ The median in an array $b$ of length $m$ is an element that occupies position number $\lfloor \frac{m+1}{2} \rfloor$ after we sort the elements in non-decreasing order. For example, the median of $[3,1,4,1,5]$ is $3$ and the median of $[5,25,20,24]$ is $20$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the maximum value of the same number at the end # Example 1: - Input: n = 5 a = [1, 2, 3, 4, 5] - Output: 4 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): mx = 0 for i in range(n): if i + 1 < n and a[i + 1] >= a[i]: mx = max(mx, a[i]) if i + 2 < n and a[i + 2] >= a[i]: mx = max(mx, a[i]) if i - 1 >= 0 and a[i - 1] >= a[i]: mx = max(mx, a[i]) if i - 2 >= 0 and a[i - 2] >= a[i]: mx = max(mx, a[i]) return mx def solve2(self, n, a): ans = 0 for i in range(n): if i + 1 < n: x = a[i] if a[i] <= a[i + 1] else a[i + 1] if x > ans: ans = x if i + 2 < n: x = a[i] if a[i] <= a[i + 2] else a[i + 2] if x > ans: ans = x return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","binary,greedy",hard 326,"# Problem Statement Doremy's new city is under construction! The city can be regarded as a simple undirected graph with $n$ vertices. The $i$-th vertex has altitude $a_i$. Now Doremy is deciding which pairs of vertices should be connected with edges. Due to economic reasons, there should be no self-loops or multiple edges in the graph. Due to safety reasons, there should not be **pairwise distinct** vertices $u$, $v$, and $w$ such that $a_u \leq a_v \leq a_w$ and the edges $(u,v)$ and $(v,w)$ exist. Under these constraints, Doremy would like to know the maximum possible number of edges in the graph. Can you help her? Note that the constructed graph is allowed to be disconnected. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return the maximum possible number of edges in the graph. # Example 1: - Input: n = 4 a = [2,2,3,1] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): a.sort() ans = n // 2 for i in range(n): if i == n - 1 or a[i] != a[i + 1]: ans = max(ans, (i + 1) * (n - i - 1)) return ans def solve2(self, n, a): a.sort() ans = n // 2 for i in range(n): if i == n - 1 or a[i] != a[i + 1]: cnt = (i + 1) * (n - i - 1) if cnt > ans: ans = cnt return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",graph,hard 327,"The factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order. For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11. Given an integer n, return the clumsy factorial of n. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 4 Output: 7 Example 2: Input: n = 10 Output: 12 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): if n == 1: return 1 elif n == 2: return 2 elif n == 3: return 6 elif n == 4: return 7 if n % 4 == 0: return n + 1 elif n % 4 <= 2: return n + 2 else: return n - 1 def solve2(self, n): res = n n -= 1 if n >= 1: res *= n n -= 1 if n >= 1: res //= n n -= 1 if n >= 1: res += n n -= 1 while n > 0: t = n n -= 1 if n >= 1: t *= n n -= 1 if n >= 1: t //= n n -= 1 res -= t if n >= 1: res += n n -= 1 return res ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,hard 328,"# Problem Statement Given an array $a$ of $n$ positive integers. In one operation, you can pick any pair of indexes $(i, j)$ such that $a_i$ and $a_j$ have **distinct** parity, then replace the smaller one with the sum of them. More formally: - If $a_i < a_j$, replace $a_i$ with $a_i + a_j$; - Otherwise, replace $a_j$ with $a_i + a_j$. Find the minimum number of operations needed to make all elements of the array have the same parity. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the minimum number of operations required. # Example 1: - Input: n = 5 a = [1, 3, 5, 7, 9] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = 0 flag = 0 mx = -1 for i in range(n): if a[i] % 2 == 1: flag = 1 if flag == 0: return 0 for i in range(n): if a[i] % 2 == 0: ans += 1 if a[i] % 2 == 1: mx = max(mx, a[i]) a.sort() for i in range(n): if a[i] % 2 == 1: continue if a[i] > mx: ans += 1 break mx += a[i] return ans def solve2(self, n, a): mx = -1 evens = 0 for i in range(n): if a[i] & 1: if a[i] > mx: mx = a[i] else: evens += 1 if evens == 0 or mx == -1: return 0 ans = evens prev = -1 processed = 0 while processed < evens: cur = 0 found = False for i in range(n): ai = a[i] if (ai & 1) == 0 and ai > prev: if not found or ai < cur: cur = ai found = True if not found: break if cur >= mx: return ans + 1 c = 0 for i in range(n): if (a[i] & 1) == 0 and a[i] == cur: c += 1 mx += cur * c processed += c prev = cur return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",constructive_algorithms,medium 329,"You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings. Return the minimum number of extra characters left over if you break up s optimally. solution main function ```python class Solution: def solve(self, s, dic): pass # write your code here``` Example 1: Input: s = ""leetscode"", dictionary = [""leet"",""code"",""leetcode""] Output: 1 Example 2: Input: s = ""sayhelloworld"", dictionary = [""hello"",""world""] Output: 3 Constraints: 1 <= s.length <= @data 1 <= dictionary.length <= @data 1 <= dictionary[i].length <= 50 dictionary[i] and s consists of only lowercase English letters dictionary contains distinct words Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import math class Solution: def solve1(self, s, dictionary): n = len(s) dp = [i for i in range(n + 1)] for i in range(n): for word in dictionary: if s.startswith(word, i): dp[i + len(word)] = min(dp[i], dp[i + len(word)]) dp[i + 1] = min(dp[i] + 1, dp[i + 1]) return dp[n] def solve2(self, s, dictionary): n = len(s) max_len = 0 for w in dictionary: lw = len(w) if lw > max_len: max_len = lw if max_len == 0: return n size = max_len + 1 buf = [0] * size for i in range(1, n + 1): best = buf[(i - 1) % size] + 1 for w in dictionary: lw = len(w) start = i - lw if start >= 0 and s.startswith(w, start): cand = buf[start % size] if cand < best: best = cand buf[i % size] = best return buf[n % size] ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) dic = [] for i in range(1, n + 1): s = next(it) dic.append(s) s = next(it) solution = Solution() result = solution.solve(s, dic) sys.stdout.write(str(result))","dp,string",medium 330,"# Problem Statement You are given an array $a$ of $n$ integers. Find the number of pairs $(i, j)$ ($1 \le i < j \le n$) where the sum of $a_i + a_j$ is greater than or equal to $l$ and less than or equal to $r$ (that is, $l \le a_i + a_j \le r$). For example, if $n = 3$, $a = [5, 1, 2]$, $l = 4$ and $r = 7$, then two pairs are suitable: - $i=1$ and $j=2$ ($4 \le 5 + 1 \le 7$); - $i=1$ and $j=3$ ($4 \le 5 + 2 \le 7$). The main function of the solution is defined as: ```python class Solution: def solve(self, n, l, r, a): pass # write your code here``` where: - return: the number of suitable pairs, please return the result as long long type # Example 1: - Input: n = 3, l = 4, r = 7 a = [5, 1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], l, r \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, l, r, a): a.sort() ans = 0 L = n R = n for i in range(n): while L > 0 and a[L - 1] + a[i] >= l: L -= 1 while R > 0 and a[R - 1] + a[i] > r: R -= 1 ans += min(i, R) - min(i, L) return ans def solve2(self, n, l, r, a): ans = 0 for i in range(n): ai = a[i] for j in range(i + 1, n): s = ai + a[j] if l <= s <= r: ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) l = int(next(it)) r = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, l, r, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,math,binary,data_structures",easy 331,"# Problem Statement You are given a sequence $a=[a_1,a_2,\dots,a_n]$ consisting of $n$ **positive** integers. Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $a[l,r]$ a segment of the sequence $a$ with the left end in $l$ and the right end in $r$, i.e. $a[l,r]=[a_l, a_{l+1}, \dots, a_r]$. For example, if $a=[31,4,15,92,6,5]$, then $a[2,5]=[4,15,92,6]$, $a[5,5]=[6]$, $a[1,6]=[31,4,15,92,6,5]$ are segments. We split the given sequence $a$ into segments so that: - each element is in **exactly** one segment; - the sums of elements for all segments are **equal**. For example, if $a$ = $[55,45,30,30,40,100]$, then such a sequence can be split into three segments: $a[1,2]=[55,45]$, $a[3,5]=[30, 30, 40]$, $a[6,6]=[100]$. Each element belongs to exactly segment, the sum of the elements of each segment is $100$. Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $3$. Find the minimum thickness among all possible splits of the given sequence of $a$ into segments in the required way. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the minimum thickness # Example 1: - Input: n = 6 a = [55,45,30,30,40,100] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 5000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve(self, n, a): s = 0 for i in range(n): s += a[i] ans = n def check(p): tem = 0 mx = 0 l = 0 r = 0 while l < n: while r < n and tem + a[r] <= p: tem += a[r] r += 1 if tem != p: return n mx = max(r - l, mx) l = r tem = 0 return mx i = 1 while i * i <= s: if i > n: break if s % i == 0: ans = min(ans, check(s // i)) j = s // i if s % i == 0 and j != i and j <= n: ans = min(ans, check(i)) i += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,math,two_pointers",easy 332,"# Problem Statement Kinich wakes up to the start of a new day. He turns on his phone, checks his mailbox, and finds a mysterious present. He decides to unbox the present. Kinich unboxes an array $a$ with $n$ integers. Initially, Kinich's score is $0$. He will perform the following operation any number of times: - Select two indices $i$ and $j$ $(1 \leq i < j \leq n)$ such that neither $i$ nor $j$ has been chosen in any previous operation and $a_i = a_j$. Then, add $1$ to his score. Output the maximum score Kinich can achieve after performing the aforementioned operation any number of times. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum score achievable. # Example 1: - Input: n = 2 a = [2, 2] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, n: int, a: List[int]) -> int: a.sort() ans = 0 pre = -1 cnt = 0 for i in range(n): if pre == -1: pre = a[i] cnt += 1 else: if a[i] == pre: cnt += 1 else: ans += cnt // 2 pre = a[i] cnt = 1 ans += cnt // 2 return ans def solve2(self, n: int, a: List[int]) -> int: ans = 0 for i in range(n): if a[i] == 0: continue v = a[i] for j in range(i + 1, n): if a[j] == v: ans += 1 a[i] = 0 a[j] = 0 break return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",implementation,easy 333,"You are given an undirected, connected tree of n nodes labeled from 0 to n - 1. The tree is represented as an adjacency list graph, where graph[i] is a list of all nodes connected with node i by an edge. Return the length of the shortest walk that visits every node. You may start and stop at any node, revisit nodes multiple times, and reuse edges. solution main function ```python class Solution: def solve(self, e): pass # write your code here``` Example 1: Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Example 2: Input: graph = [[1],[0,2],[1,3],[2]] Output: 3 Constraints: n == graph.length 1 <= n <= @data graph is an undirected connected tree with exactly n - 1 edges. graph[i] does not contain i. If graph[a] contains b, then graph[b] contains a. Time limit: @time_limit ms Memory limit: @memory_limit KB","[4, 8, 12]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections import sys class Solution: def solve1(self, graph): n = len(graph) dp = [[-1] * (1 << n) for _ in range(n)] q = collections.deque() for i in range(n): mask = 1 << i q.append((i, mask)) dp[i][mask] = 0 while q: node, visited = q.popleft() for neigh in graph[node]: new_visited = visited | (1 << neigh) if dp[neigh][new_visited] == -1: dp[neigh][new_visited] = dp[node][visited] + 1 q.append((neigh, new_visited)) all_visited = (1 << n) - 1 ans = sys.maxsize for i in range(n): if dp[i][all_visited] != -1: ans = min(ans, dp[i][all_visited]) return ans def solve2(self, graph): n = len(graph) if n <= 1: return 0 total_edges = 0 for adj in graph: total_edges += len(adj) total_edges //= 2 if total_edges == n - 1: m = n rounds = 0 while m > 2: leaves = 0 for u in range(n): adj = graph[u] if len(adj) == 1: x = adj[0] if x >= 0: adj[0] = ~x leaves += 1 if leaves == 0: break for u in range(n): adj = graph[u] if len(adj) == 1 and adj[0] < 0: v = ~adj[0] graph[u] = [] lst = graph[v] for i in range(len(lst)): if lst[i] == u: lst.pop(i) break m -= leaves rounds += 1 if m == 1: diameter = 2 * rounds elif m == 2: diameter = 2 * rounds + 1 else: diameter = 0 return 2 * (n - 1) - diameter all_mask = (1 << n) - 1 def exists_with_limit(L): for s in range(n): mask = 1 << s cnt = 1 stack_nodes = [s] stack_index = [0] stack_new = [True] depth = 0 if cnt == n: return True while stack_nodes: if cnt == n: return True u = stack_nodes[-1] if depth == L or cnt + (L - depth) < n: node = stack_nodes.pop() stack_index.pop() new_flag = stack_new.pop() if new_flag: mask ^= (1 << node) cnt -= 1 depth -= 1 continue idx = stack_index[-1] if idx < len(graph[u]): v = graph[u][idx] stack_index[-1] = idx + 1 new_flag = (mask >> v) & 1 == 0 if new_flag: mask |= (1 << v) cnt += 1 stack_nodes.append(v) stack_index.append(0) stack_new.append(new_flag) depth += 1 if cnt == n: return True else: node = stack_nodes.pop() stack_index.pop() new_flag = stack_new.pop() if new_flag: mask ^= (1 << node) cnt -= 1 depth -= 1 return False L = n - 1 while True: if exists_with_limit(L): return L L += 1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) e = [] for _ in range(n): e.append([]) for i in range(1, n): x = int(next(it)) y = int(next(it)) e[x].append(y) e[y].append(x) solution = Solution() result = solution.solve(e) sys.stdout.write(str(result))","graph,dynamic_programming,search,other",hard 334,"There is an undirected graph consisting of n nodes numbered from 0 to n - 1. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A star graph is a subgraph of the given graph having a center node containing 0 or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges. The image below shows star graphs with 3 and 4 neighbors respectively, centered at the blue node. The star sum is the sum of the values of all the nodes present in the star graph. Given an integer k, return the maximum star sum of a star graph containing at most k edges solution main function ```python class Solution: def solve(self, val, edge, k): pass # write your code here``` Example 1: Input: vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2 Output: 16 Example 2: Input: vals = [-5], edges = [], k = 0 Output: -5 Constraints: n == vals.length 1 <= n <= @data -10^4 <= vals[i] <= 10^4 0 <= edges.length <= min(n * (n - 1) / 2, 10^5) edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi 0 <= k <= n - 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, vals, edges, k): n = len(vals) adj = [[] for _ in range(n)] for i in range(len(edges)): u, v = edges[i] adj[u].append(vals[v]) adj[v].append(vals[u]) ans = -math.inf for i in range(n): temp = vals[i] adj[i].sort(reverse=True) limit = min(k, len(adj[i])) for j in range(limit): if adj[i][j] < 0: break temp += adj[i][j] ans = max(ans, temp) return ans def solve2(self, vals, edges, k): n = len(vals) if n == 0: return 0 ans = vals[0] for i in range(n): base = vals[i] if k <= 0: if base > ans: ans = base continue count_pos = 0 sum_pos = 0 max_pos = 0 for e in edges: u = e[0] v = e[1] if u == i: w = vals[v] elif v == i: w = vals[u] else: continue if w > 0: count_pos += 1 sum_pos += w if w > max_pos: max_pos = w if count_pos == 0: best_i = base elif count_pos <= k: best_i = base + sum_pos else: lo = 1 hi = max_pos best_v = 1 while lo <= hi: mid = (lo + hi) // 2 c_ge = 0 for e in edges: u = e[0] v = e[1] if u == i: w = vals[v] elif v == i: w = vals[u] else: continue if w >= mid and w > 0: c_ge += 1 if c_ge >= k: best_v = mid lo = mid + 1 else: hi = mid - 1 sum_gt = 0 c_gt = 0 for e in edges: u = e[0] v = e[1] if u == i: w = vals[v] elif v == i: w = vals[u] else: continue if w > best_v: sum_gt += w c_gt += 1 r = k - c_gt if r < 0: r = 0 best_i = base + sum_gt + r * best_v if best_i > ans: ans = best_i return ans ","import sys def main(): data = sys.stdin.buffer.read() def scan_next(buf, pos): L = len(buf) while pos < L and not (buf[pos] == 45 or 48 <= buf[pos] <= 57): pos += 1 if pos >= L: return None, pos, pos sign = 1 start = pos if buf[pos] == 45: # '-' pos += 1 if pos >= L or not (48 <= buf[pos] <= 57): return scan_next(buf, pos) sign = -1 num = 0 while pos < L and 48 <= buf[pos] <= 57: num = num * 10 + (buf[pos] - 48) pos += 1 end = pos return sign * num, start, end pos = 0 n, s, e = scan_next(data, pos) pos = e m, s, e = scan_next(data, pos) pos = e edge = [] val = [] for _ in range(m): x, s, e = scan_next(data, pos) pos = e y, s, e = scan_next(data, pos) pos = e temp = [] temp.append(x) temp.append(y) edge.append(temp) k, s, e = scan_next(data, pos) pos = e if k is None: k = 0 last = None for _ in range(n): v, s, e = scan_next(data, pos) if v is None: v = last if last is not None else 0 else: pos = e last = v val.append(v) k = max(0, min(k, n - 1)) solution = Solution() result = solution.solve(val, edge, k) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","graph,search",medium 335,"You are given an m * n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves. solution main function ```python class Solution: def solve(self, g): pass # write your code here``` Example 1: Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Example 2: Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data grid[i][j] is either 0 or 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] def solve1(self, grid): ret = 0 m, n = len(grid), len(grid[0]) q = collections.deque() for i in range(m): for j in range(n): if grid[i][j] == 1: if i == 0 or j == 0 or i == m - 1 or j == n - 1: q.append((i, j)) grid[i][j] = 2 while q: a, b = q.popleft() for i in range(4): x = a + self.dx[i] y = b + self.dy[i] if 0 <= x < m and 0 <= y < n and grid[x][y] == 1: q.append((x, y)) grid[x][y] = 2 for i in range(m): for j in range(n): if grid[i][j] == 1: ret += 1 return ret def solve2(self, grid): m = len(grid) n = len(grid[0]) if m > 0 else 0 if m == 0 or n == 0: return 0 for j in range(n): if grid[0][j] == 1: grid[0][j] = 2 if grid[m - 1][j] == 1: grid[m - 1][j] = 2 for i in range(m): if grid[i][0] == 1: grid[i][0] = 2 if grid[i][n - 1] == 1: grid[i][n - 1] = 2 changed = True while changed: changed = False for i in range(m): for j in range(n): if grid[i][j] == 1: if (i > 0 and grid[i - 1][j] == 2) or (i + 1 < m and grid[i + 1][j] == 2) or (j > 0 and grid[i][j - 1] == 2) or (j + 1 < n and grid[i][j + 1] == 2): grid[i][j] = 2 changed = True ret = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: ret += 1 return ret ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) g = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) g.append(temp) solution = Solution() result = solution.solve(g) sys.stdout.write(str(result))",graph,medium 336,"# Problem Statement You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case. Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. # Example 1: - Input: n = 5 a = [1, 1, 1, 1, 1] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): j = 0 a.sort() for i in range(n): if a[i] > a[j]: j += 1 return j def solve2(self, n, a): a.sort() j = 0 for i in range(n): if a[i] > a[j]: j += 1 return j ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","math,sort",medium 337,"# Problem Statement You are given an integer $n$ and an array $a$ of length $n$. Each element $a_i$ is either $-1$ or an integer from $1$ to $n$. A permutation $p$ of $\{0, 1, \dots, n-1\}$ is compatible with $a$ if, for every index $i$ such that $a_i \neq -1$, we have $p_i = a_i - 1$. A compatible permutation is called valid if there exists an integer $k$, with $0 \leq k \leq n-2$, such that: - the elements of $p$ whose values are at most $k$, read from left to right, are in increasing order; - the elements of $p$ whose values are greater than $k$, read from left to right, are in increasing order. Count the number of distinct valid compatible permutations modulo $998244353$. # Function Signature ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - $n$ is the length of the array. - $a$ is the array of fixed values and unknown positions. - The function returns the number of valid compatible permutations modulo $998244353$. # Example 1 **Input: ** $n = 2$, $a = [2, 1]$ **Output:** $1$ **Explanation:** The only compatible permutation is $[1, 0]$. For $k = 0$, the values at most $0$ form $[0]$, and the values greater than $0$ form $[1]$. Both are increasing, so the permutation is valid. # Example 2 **Input: ** $n = 3$, $a = [-1, -1, -1]$ **Output:** $5$ **Explanation:** All positions are unknown. Among the six permutations of $\{0,1,2\}$, all except $[2,1,0]$ satisfy the condition for at least one valid $k$. Therefore the answer is $5$. # Constraints - $2 \leq n \leq @data$ - Each $a_i$ is either $-1$ or an integer between $1$ and $n$, inclusive. - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[300, 1500, 3000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve(self, n, a): MOD = 998244353 b = list(a) for i in range(len(b)): if b[i] != -1: b[i] -= 1 def modpow(base, exp): res = 1 base %= MOD if base < 0: base += MOD while exp > 0: if exp % 2 == 1: res = (res * base) % MOD base = (base * base) % MOD exp //= 2 return res fac = [0] * (n + 1) ifac = [0] * (n + 1) fac[0] = 1 for i in range(1, n + 1): fac[i] = (fac[i - 1] * i) % MOD ifac[n] = modpow(fac[n], MOD - 2) for i in range(n, 0, -1): ifac[i - 1] = (ifac[i] * i) % MOD def C(N, R): if R < 0 or R > N: return 0 return (fac[N] * ifac[R] % MOD * ifac[N - R]) % MOD ans = 0 for k in range(n - 1): res = 1 spaces = 0 less = -1 more = k for j in range(n): if b[j] == -1: spaces += 1 continue if b[j] <= k: need = b[j] - less - 1 res = res * C(spaces, need) % MOD more += spaces - need less = b[j] else: need = b[j] - more - 1 res = res * C(spaces, need) % MOD less += spaces - need more = b[j] spaces = 0 res = res * C(spaces, k - less) % MOD ans += res if ans >= MOD: ans -= MOD sorted_flag = True for i in range(n): if b[i] != -1 and b[i] != i: sorted_flag = False break if sorted_flag: ans -= (n - 2) ans %= MOD if ans < 0: ans += MOD return ans % MOD ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","combinatorics,dp",hard 338,"# Problem Statement Today, Cat and Fox found an array $a$ consisting of $n$ non-negative integers. Define the loneliness of $a$ as the **smallest** positive integer $k$ ($1 \le k \le n$) such that for any two positive integers $i$ and $j$ ($1 \leq i, j \leq n - k +1$), the following holds: $$ a_i | a_{i+1} | \ldots | a_{i+k-1} = a_j | a_{j+1} | \ldots | a_{j+k-1}, $$ where $x | y$ denotes the bitwise OR of $x$ and $y$. In other words, for every $k$ consecutive elements, their bitwise OR should be the same. Note that the loneliness of $a$ is well-defined, because for $k = n$ the condition is satisfied. Cat and Fox want to know how lonely the array $a$ is. Help them calculate the loneliness of the found array. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the loneliness of the given array. # Example 1: - Input: n = 3 a = [2, 2, 2] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] \leq 10^6$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = 1 for j in range(20): lst = -1 for i in range(n): if (a[i] >> j) & 1: ans = max(ans, i - lst) lst = i if lst != -1: ans = max(ans, n - lst) return ans def solve2(self, n, a): for k in range(1, n + 1): v = 0 i = 0 while i < k: v |= a[i] i += 1 ok = True start = 1 end = n - k + 1 while start < end: cur = 0 t = start t_end = start + k while t < t_end: cur |= a[t] t += 1 if cur != v: ok = False break start += 1 if ok: return k return n ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","bit_manipulation,binary,two_pointers,math",medium 339,"You are given a string s consisting only of uppercase English letters. You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings ""AB"" or ""CD"" from s. Return the minimum possible length of the resulting string that you can obtain. Note that the string concatenates after removing the substring and could produce new ""AB"" or ""CD"" substrings. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""ABFCACDB"" Output: 2 Example 2: Input: s = ""ACBBD"" Output: 5 Constraints: 1 <= s.length <= @data s consists only of uppercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","class Solution: def solve1(self, s): writePtr = 0 charArray = list(s) for readPtr in range(len(s)): charArray[writePtr] = charArray[readPtr] if (writePtr > 0 and (charArray[writePtr - 1] == 'A' or charArray[writePtr - 1] == 'C') and ord(charArray[writePtr]) == ord(charArray[writePtr - 1]) + 1): writePtr -= 1 else: writePtr += 1 return writePtr def solve2(self, s): arr = list(s) n = len(arr) i = 0 while i + 1 < n: c0 = arr[i] c1 = arr[i + 1] if (c0 == 'A' and c1 == 'B') or (c0 == 'C' and c1 == 'D'): j = i + 2 k = i while j < n: arr[k] = arr[j] k += 1 j += 1 n -= 2 if i > 0: i -= 1 else: i += 1 return n ","import sys def main(): data = sys.stdin.buffer.read().split() if not data: return s = data[0].decode() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()",string,easy 340,"# Problem Statement An array $[b_1, b_2, \ldots, b_m]$ is a palindrome, if $b_i = b_{m+1-i}$ for each $i$ from $1$ to $m$. Empty array is also a palindrome. An array is called **kalindrome**, if the following condition holds: - It's possible to select some integer $x$ and delete some of the elements of the array equal to $x$, so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to $x$, and you don't have to delete at least one element equal to $x$. For example : - $[1, 2, 1]$ is kalindrome because you can simply not delete a single element. - $[3, 1, 2, 3, 1]$ is kalindrome because you can choose $x = 3$ and delete both elements equal to $3$, obtaining array $[1, 2, 1]$, which is a palindrome. - $[1, 2, 3]$ is not kalindrome. You are given an array $[a_1, a_2, \ldots, a_n]$. Determine if $a$ is kalindrome or not. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return YES if a is kalindrome and NO otherwise # Example 1: - Input: n = 2 a = [1, 2] - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): i = 0 flag = 0 for i in range(n // 2): if a[i] != a[n - i - 1]: flag = 1 break def check(x, n_local): i_check = 0 j_check = n_local - 1 while i_check < j_check: if a[i_check] == x: i_check += 1 continue if a[j_check] == x: j_check -= 1 continue if a[i_check] == a[j_check]: i_check += 1 j_check -= 1 continue return 0 return 1 if not flag: return ""YES"" else: if check(a[i], n) or check(a[n - i - 1], n): return ""YES"" else: return ""NO"" def solve2(self, n, a): def check(x): i = 0 j = n - 1 while i < j: if a[i] == x: i += 1 continue if a[j] == x: j -= 1 continue if a[i] == a[j]: i += 1 j -= 1 continue return ""NO"" return ""YES"" for i in range(n): res = check(a[i]) if res == ""YES"": return ""YES"" return ""NO"" ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,two_pointers",medium 341,"# Problem Statement Given a rooted tree `T` with `n` vertices (rooted at `1`) and an integer array `a` of length `n`, count the number of permutations `p` of length `n` that satisfy: - For every vertex `u (1 ≤ u ≤ n)`, there are exactly `a[u]` ancestors `v` of `u` such that `p[v] < p[u]`. It is guaranteed that the input is selected such that at least one valid permutation exists. Return the answer modulo `998244353`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, fa, a): pass # write your code here``` where: - `fa` is a parent array of size `n + 1` (1-indexed), with `fa[1] = 0`, and for `2 ≤ i ≤ n`, `fa[i]` is the parent of node `i`. - `a` is a 1-indexed array of size `n`, where `0 ≤ a[i] < depth(i)`, and `depth(1) = 1`. - The function returns the number of valid permutations modulo `998244353`. # Example - Input: - n = 5 - fa = [0, 0, 1, 2, 3, 4] // 1-indexed, fa[1]=0, parents for 2..n: 1 2 3 4 - a = [0, 1, 2, 3, 4] - Output: - 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq a[i] < depth(i)$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[5000, 2500, 1250], [40000, 20000, 10000], [320000, 160000, 80000]]","import sys class Solution: def solve1(self, n, fa, a): MOD = 998244353 if n > 950: sys.setrecursionlimit(n + 50) G = [[] for _ in range(n + 1)] for i in range(2, n + 1): G[fa[i]].append(i) siz = [0] * (n + 1) hson = [0] * (n + 1) def dfs(u): siz[u] = 1 for v in G[u]: dfs(v) siz[u] += siz[v] if siz[v] > siz[hson[u]]: hson[u] = v dfs(1) fact = [1] * (n + 1) ifac = [1] * (n + 1) for i in range(1, n + 1): fact[i] = (fact[i - 1] * i) % MOD if n > 0: ifac[n] = pow(fact[n], MOD - 2, MOD) for i in range(n - 1, -1, -1): ifac[i] = (ifac[i + 1] * (i + 1)) % MOD def C(x, y): if x < 0 or x > y: return 0 return fact[y] * ifac[x] % MOD * ifac[y - x] % MOD class Seg: def __init__(self): self.base = 1 self.len = [] def init(self, need): self.base = 1 while self.base < need: self.base <<= 1 self.len = [0] * (self.base * 2) for i in range(self.base): self.len[i + self.base] = 1 for i in range(self.base - 1, 0, -1): self.len[i] = self.len[i << 1] + self.len[(i << 1) | 1] def qpos(self, k): u = 1 while u < self.base: if self.len[u << 1] >= k: u <<= 1 else: k -= self.len[u << 1] u = (u << 1) | 1 return u - self.base def gpos(self, leaf): ans = 1 x = leaf + self.base while x > 1: if (x & 1): ans += self.len[x ^ 1] x >>= 1 return ans def add(self, leaf, v): x = leaf + self.base self.len[x] += v x >>= 1 while x > 0: self.len[x] = self.len[x << 1] + self.len[(x << 1) | 1] x >>= 1 T = Seg() T.init(n + 3) a_1based = [0] * (n + 1) for i in range(1, n + 1): a_1based[i] = a[i] + 1 vec = [[] for _ in range(n + 1)] cnt = [0] * T.base ans = 1 def work(u): nonlocal ans pth = [] v_iter = u while v_iter: pth.append(v_iter) for w in G[v_iter]: if w != hson[v_iter]: work(w) v_iter = hson[v_iter] pth.reverse() upd = [] posi = [] for v in pth: for w in G[v]: if w != hson[v]: for rank, count in vec[w]: t = T.qpos(rank) posi.append(t) ans = ans * C(count, cnt[t] + count) % MOD cnt[t] += count vec[w].clear() p = T.qpos(a_1based[v]) q = T.qpos(a_1based[v] + 1) cnt[q] += cnt[p] + 1 cnt[p] = 0 posi.append(q) upd.append(p) T.add(p, -1) for i in posi: if cnt[i]: vec[u].append((T.gpos(i), cnt[i])) cnt[i] = 0 for i in upd: T.add(i, 1) work(1) return ans % MOD def solve2(self, n, fa, a): MOD = 998244353 if n <= 1: return 1 p = [0] + [i for i in range(1, n + 1)] ans = 0 while True: ok = True for u in range(1, n + 1): c = 0 x = fa[u] pu = p[u] while x != 0: if p[x] < pu: c += 1 x = fa[x] if c != a[u]: ok = False break if ok: ans += 1 if ans >= MOD: ans -= MOD i = n - 1 while i >= 1 and p[i] >= p[i + 1]: i -= 1 if i < 1: break j = n while p[j] <= p[i]: j -= 1 p[i], p[j] = p[j], p[i] l, r = i + 1, n while l < r: p[l], p[r] = p[r], p[l] l += 1 r -= 1 return ans % MOD ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) fa = [0] * (n + 1) a = [0] * (n + 1) for i in range(2, n + 1): fa[i] = int(next(it)) for i in range(1, n + 1): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, fa, a) sys.stdout.write(str(result) + ""\n"")","data_structures,tree",hard 342,"# Problem Statement Given a binary string $s$ of length $n$, consisting of characters 0 and 1. Let's build a **square** table of size $n \times n$, consisting of 0 and 1 characters as follows. In the first row of the table write the original string $s$. In the second row of the table write cyclic shift of the string $s$ by one to the right. In the third row of the table, write the cyclic shift of line $s$ by two to the right. And so on. Thus, the row with number $k$ will contain a cyclic shift of string $s$ by $k$ to the right. The rows **are numbered from $0$ to $n - 1$ top-to-bottom**. In the resulting table we need to find the rectangle consisting only of ones that has the largest area. We call a rectangle the set of all cells $(i, j)$ in the table, such that $x_1 \le i \le x_2$ and $y_1 \le j \le y_2$ for some integers $0 \le x_1 \le x_2 < n$ and $0 \le y_1 \le y_2 < n$. Recall that the cyclic shift of string $s$ by $k$ to the right is the string $s_{n-k+1} \ldots s_n s_1 s_2 \ldots s_{n-k}$. For example, the cyclic shift of the string ""01011"" by $0$ to the right is the string itself ""01011"", its cyclic shift by $3$ to the right is the string ""01101"". The main function of the solution is defined as: ```python class Solution: def solve(self, s): pass # write your code here``` where: - return value is a 64-bit integer representing the area of the largest rectangle # Example 1: - Input: s = ""101"" - Output: 2 # Constraints: - $1 \leq s.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 64], [4000, 2000, 400], [32000, 16000, 3200]]","import math class Solution: def solve1(self, s): n = len(s) if s.count('0') == 0: return n * n s = s + s ans = 0 i = 0 while i < n: if s[i] == '1': j = i while s[j] == '1': j += 1 d = j - i + 1 ans = max(ans, (d // 2) * (d - d // 2)) i = j i += 1 return ans def solve2(self, s): n = len(s) if n == 0: return 0 if s.count('0') == 0: return n * n max_run = 0 cur = 0 for ch in s: if ch == '1': cur += 1 if cur > max_run: max_run = cur else: cur = 0 head = 0 i = 0 while i < n and s[i] == '1': head += 1 i += 1 tail = 0 i = n - 1 while i >= 0 and s[i] == '1': tail += 1 i -= 1 L = max(max_run, head + tail) a = (L + 1) // 2 b = (L + 1) - a return a * b ","import sys def main(): data = sys.stdin.read().split() if not data: s = """" else: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","two_pointers,math,string",hard 343,"Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it into some number of substrings such that: Each substring is balanced. Return the maximum number of balanced strings you can obtain. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""RLRRLLRLRL"" Output: 4 Example 2: Input: s = ""RLRRRLLRLL"" Output: 2 Constraints: 2 <= s.length <= @data s[i] is either 'L' or 'R'. s is a balanced string. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, s: str) -> int: x = 0 l = 0 r = 0 n = len(s) for i in range(n): if s[i] == 'R': r += 1 else: l += 1 if r == l: x += 1 l = 0 r = 0 return x def solve2(self, s: str) -> int: n = len(s) count = 0 i = 0 while i < n: l = 0 r = 0 j = i while j < n: if s[j] == 'L': l += 1 else: r += 1 if l == r: count += 1 i = j + 1 break j += 1 else: i = n return count ","import sys def main(): argv = sys.argv argc = len(argv) s = """" solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","string,greedy,other",easy 344,"# Problem Statement Vladislav wrote the integers from $1$ to $n$, inclusive, on the board. Then he replaced each integer with the sum of its digits. What is the sum of the numbers on the board now? For example, if $n=12$ then initially the numbers on the board are: $$ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12. $$ Then after the replacement, the numbers become: $$ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3. $$ The sum of these numbers is $1+2+3+4+5+6+7+8+9+1+2+3=51$. Thus, for $n=12$ the answer is $51$. The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - the return value is the total sum of the digits of all numbers # Example 1: - Input: n = 12 - Output: 51 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): s = str(n) s_len = len(s) tem = 1 if s_len > 1: tem = 10**(s_len - 1) current_sum = 0 ans = 0 num = n for i in range(s_len): d = int(s[i]) ans += current_sum * 45 * tem current_sum = current_sum * 10 + d ans += (d * (d - 1) // 2) * tem if tem > 0: num %= tem ans += d * (num + 1) if tem > 0: tem //= 10 return ans def solve2(self, n): total = 0 for i in range(1, n + 1): x = i while x: total += x % 10 x //= 10 return total ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")","math,dp",easy 345,"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. solution main function ```python class Solution: def solve(self, n, edge): pass # write your code here``` Example 1: Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] Output: [[1,3]] Example 2: Input: n = 2, connections = [[0,1]] Output: [[0,1]] Constraints: 2 <= n <= @data n - 1 <= connections.length <= 10^5 0 <= a[i], b[i] <= n - 1 a[i] != b[i] All undirected connections are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 10000]",4000,"[[500, 312, 171], [4000, 2500, 1375], [32000, 20000, 11000]]","import sys class Solution: def solve(self, n, connections): sys.setrecursionlimit(100005) dict = [[] for _ in range(n)] for edge in connections: dict[edge[0]].append(edge[1]) dict[edge[1]].append(edge[0]) id = [-1] * n res = [] self.dfs(0, 0, -1, id, dict, res) return res def dfs(self, node, nodeId, par, id, dict, res): id[node] = nodeId for next in dict[node]: if next == par: continue elif id[next] == -1: id[node] = min(id[node], self.dfs(next, nodeId + 1, node, id, dict, res)) else: id[node] = min(id[next], id[node]) if id[node] == nodeId and node != 0: res.append([par, node]) return id[node] ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) edge = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) edge.append(temp) solution = Solution() result = solution.solve(n, edge) normalized = [] for it_item in result: if not isinstance(it_item, list) or len(it_item) != 2: sys.stdout.write(""__INVALID__"") sys.exit(0) x = it_item[0] y = it_item[1] if x > y: x, y = y, x normalized.append([x, y]) normalized.sort() out_parts = [] for it_item in normalized: x = it_item[0] y = it_item[1] out_parts.append(str(x)) out_parts.append(' ') out_parts.append(str(y)) out_parts.append(' ') sys.stdout.write(''.join(out_parts))",graph,easy 346,"You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules: The chosen integers have to be in the range [1, n]. Each integer can be chosen at most once. The chosen integers should not be in the array banned. The sum of the chosen integers should not exceed maxSum. Return the maximum number of integers you can choose following the mentioned rules. solution main function ```python class Solution: def solve(self, s, n, mx): pass # write your code here``` Example 1: Input: banned = [1,6,5], n = 5, maxSum = 6 Output: 2 Example 2: Input: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 Output: 0 Constraints: 1 <= banned.length <= @data 1 <= banned[i], n <= @data 1 <= maxSum <= @data^2 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import math import heapq class Solution: def solve1(self, banned, n, maxSum): banned.sort() current_sum = 0 res = 0 it = 0 length = len(banned) for i in range(1, n + 1): if it < length and banned[it] == i: while it < length and banned[it] == i: it += 1 else: current_sum += i if current_sum <= maxSum: res += 1 else: return res return res def solve2(self, banned, n, maxSum): total = 0 count = 0 for i in range(1, n + 1): banned_flag = False for x in banned: if x == i: banned_flag = True break if not banned_flag: if total + i <= maxSum: total += i count += 1 else: break return count ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) mx = int(next(it)) s = [] for i in range(1, m + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, n, mx) sys.stdout.write(str(result))","sort,greedy",easy 347,"# Problem Statement There is a chessboard of size $n$ by $n$. The square in the $i$-th row from top and $j$-th column from the left is labelled $(i,j)$. Currently, Gregor has some pawns in the $n$-th row. There are also enemy pawns in the $1$-st row. On one turn, Gregor moves one of **his** pawns. A pawn can move one square up (from $(i,j)$ to $(i-1,j)$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $(i,j)$ to either $(i-1,j-1)$ or $(i-1,j+1)$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed. Gregor wants to know what is the maximum number of his pawns that can reach row $1$? Note that only Gregor takes turns in this game, and **the enemy pawns never move**. Also, when Gregor's pawn reaches row $1$, it is stuck and cannot make any further moves. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, b): pass # write your code here``` where: - `n`: the size of the chessboard - `a` consists of a string of binary digits of length n, where a 1 in the i-th position corresponds to an enemy's pawn in the i-th cell from the left, and 0 corresponds to an empty cell. - `b` consists of a string of binary digits of length n, where a 1 in the i-th position corresponds to a Gregor's pawn in the i-th cell from the left, and 0 corresponds to an empty cell. - return: the maximum number of Gregor's pawns which can reach the 1-st row. # Example 1: - Input: n = 3 a = ""000"" b = ""111"" - Output: 3 # Constraints: - $2 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import math class Solution: def solve1(self, n, a, b): a_list = list(a) b_list = list(b) la = '0' lb = '0' ans = 0 for i in range(n): if b_list[i] == '1' and (lb == '1' or a_list[i] == '0'): ans += 1 lb = '0' b_list[i] = '0' if a_list[i] == '1' and la == '1': ans += 1 la = '0' a_list[i] = '0' la = b_list[i] lb = a_list[i] return ans def solve2(self, n, a, b): ans = 0 prev_avail = False used_current = False for i in range(n): curr_avail = (b[i] == '1') and (not used_current) used_next = False if a[i] == '0': if curr_avail: ans += 1 curr_avail = False else: if prev_avail: ans += 1 else: if i + 1 < n and b[i + 1] == '1': ans += 1 used_next = True prev_avail = curr_avail used_current = used_next return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = next(it) b = next(it) solution = Solution() result = solution.solve(n, a, b) sys.stdout.write(str(result) + ""\n"")","search,dp,graph",easy 348,"Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 12 Output: 3 Example 2: Input: n = 13 Output: 2 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def isPerfectSquare(self, x: int) -> bool: y = int(math.sqrt(x)) return y * y == x def checkAnswer4(self, x: int) -> bool: while x % 4 == 0: x //= 4 return x % 8 == 7 def solve1(self, n: int) -> int: if self.isPerfectSquare(n): return 1 if self.checkAnswer4(n): return 4 i = 1 while i * i <= n: j = n - i * i if self.isPerfectSquare(j): return 2 i += 1 return 3 def solve2(self, n: int) -> int: y = math.isqrt(n) if y * y == n: return 1 m = n while m % 4 == 0: m //= 4 if m % 8 == 7: return 4 i = 1 while i * i <= n: j = n - i * i y = math.isqrt(j) if y * y == j: return 2 i += 1 return 3","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,medium 349,"# Problem Statement You are given three positive integers `x`, `y`, and `k`, and a binary string `a` with length `x + y`. Count the number of binary strings `b` such that: - `b` has exactly `x` zeros and exactly `y` ones; - there exists an index `i` (1 ≤ i ≤ x + y − 1) such that `min( f(b1…bi), f(b(i+1)…b(x+y)) ) ≥ k`, where `f(s)` is the length of the longest non-decreasing subsequence (LNDS) in `s`; - `b` is lexicographically larger than `a`. Return the answer modulo 998244353. The main function of the solution is defined as: ```python class Solution: def solve(self, x, y, k, a): pass # write your code here``` where: - `x`: number of zeros in `b` - `y`: number of ones in `b` - `k`: target LNDS threshold per half - `a`: a given binary string of length `x + y` - return: the number of valid `b` modulo 998244353 Example: Input: x = 2, y = 2, k = 2, a = ""0000"" Output: 3 Explanation: The valid strings are ""0011"", ""0101"", and ""1100"". # Constraints: - 1 ≤ x, y ≤ @data - 1 ≤ k < x + y - |a| = x + y, a consists only of '0' and '1' - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[100, 1000, 3000]",4000,"[[5000, 1000, 500], [40000, 8000, 4000], [320000, 64000, 32000]]","import sys class Solution: MAXN = 10010 MOD = 998244353 fac = None ifac = None invInt = None fac_inited = False @classmethod def ensure_fac(cls): if cls.fac_inited: return SIZE = cls.MAXN + 10 cls.fac = [1] * SIZE cls.ifac = [1] * SIZE cls.invInt = [1] * SIZE for i in range(1, SIZE): cls.fac[i] = (cls.fac[i - 1] * i) % cls.MOD cls.ifac[SIZE - 1] = pow(cls.fac[SIZE - 1], cls.MOD - 2, cls.MOD) for i in range(SIZE - 2, -1, -1): cls.ifac[i] = (cls.ifac[i + 1] * (i + 1)) % cls.MOD cls.invInt[0] = 0 cls.invInt[1] = 1 for i in range(2, SIZE): cls.invInt[i] = (cls.fac[i - 1] * cls.ifac[i]) % cls.MOD cls.fac_inited = True @classmethod def ncr(cls, n, r): if 0 <= r <= n: return (((cls.fac[n] * cls.ifac[n - r]) % cls.MOD) * cls.ifac[r]) % cls.MOD return 0 @classmethod def f_bin(cls, a, b, K): if a < 0 or b < 0: return 0 if K > a + b: return 0 if a >= K or b >= K: return cls.ncr(a + b, a) return cls.ncr(a + b, K) @classmethod def g_bin(cls, a, b, c): return (cls.ncr(a + b, a) - cls.f_bin(a, b, c) + cls.MOD) % cls.MOD def solve1(self, X, Y, K, S): self.ensure_fac() n = X + Y P = [[0] * (Y + 2) for _ in range(X + 2)] for i in range(X + 2): for j in range(Y + 2): P[i][j] = self.f_bin(i, j, K) if i > 0 and j < Y + 1: P[i][j] = (P[i][j] + P[i - 1][j + 1]) % self.MOD def getP(i, j): if i < 0 or i > X + 1 or j < 0 or j > Y + 1: return 0 return P[i][j] def solve_prefix(m, flip_pos): nx, ny = X, Y prefix_list = list(S[:m]) if flip_pos < m: prefix_list[flip_pos] = '1' for i in range(m): if prefix_list[i] == '0': nx -= 1 else: ny -= 1 if nx < 0 or ny < 0: return 0 ptr = -1 c0, c1, lis = 0, 0, 0 prefix_str = """".join(prefix_list) for i in range(m): ch = prefix_str[i] if ch == '0': c0 += 1 lis = max(lis, c0) else: lis += 1 c1 += 1 if lis == K and ptr == -1: ptr = i c0, c1, lis = 0, 0, 0 if ptr == -1: res = 0 rem_len = n - m for l in range(1, rem_len - K + 1): r = rem_len - l if l + lis < K: continue if l - K + lis >= K - c0: continue L_c0_val1 = l - K + lis L_c1_val1 = l - L_c0_val1 if 0 <= L_c0_val1 <= nx and 0 <= L_c1_val1 <= ny: term1 = self.g_bin(L_c0_val1, L_c1_val1 - 1, K - c0) term2 = self.f_bin(nx - L_c0_val1, ny - L_c1_val1, K) res = (res + term1 * term2) % self.MOD L_c0_val2 = K - c0 L_c1_val2 = l - L_c0_val2 if L_c0_val1 != L_c0_val2 and 0 <= L_c0_val2 <= nx and 0 <= L_c1_val2 <= ny: term1 = self.g_bin(L_c0_val2 - 1, L_c1_val2, K - c0) term2 = self.f_bin(nx - L_c0_val2, ny - L_c1_val2, K) res = (res + term1 * term2) % self.MOD pL = l - K + lis + 1 pR = K - c0 - 1 pL = max(pL, l - ny) pR = min(pR, nx) if pL <= pR: ways = self.f_bin(pL, l - pL, K - c0) ways = (ways - self.f_bin(pL - 1, l - pL, K - c0) + self.MOD) % self.MOD ways = (ways - self.f_bin(pL, l - pL - 1, K - c0) + self.MOD) % self.MOD npL = nx - pR npR = nx - pL right_tot = getP(npR, r - npR) if npL > 0: right_tot = (right_tot - getP(npL - 1, r - npL + 1) + self.MOD) % self.MOD res = (res + right_tot * ways) % self.MOD return res else: if lis + ny >= K: return self.ncr(nx + ny, nx) else: return self.f_bin(nx, ny, K - c0) ans = 0 for p in range(n): if S[p] == '0': res = solve_prefix(p + 1, p) ans = (ans + res) % self.MOD return ans def solve2(self, X, Y, K, S): n = X + Y b = ['0'] * X + ['1'] * Y def next_permutation(arr): i = len(arr) - 2 while i >= 0 and arr[i] >= arr[i + 1]: i -= 1 if i < 0: return False j = len(arr) - 1 while arr[j] <= arr[i]: j -= 1 arr[i], arr[j] = arr[j], arr[i] l, r = i + 1, len(arr) - 1 while l < r: arr[l], arr[r] = arr[r], arr[l] l += 1 r -= 1 return True def lnds_binary(arr, l, r): if l >= r: return 0 total_ones = 0 i = l while i < r: if arr[i] == '1': total_ones += 1 i += 1 ones_seen = 0 zeros_seen = 0 best = total_ones i = l while i < r: if arr[i] == '0': zeros_seen += 1 else: ones_seen += 1 cand = zeros_seen + (total_ones - ones_seen) if cand > best: best = cand i += 1 if zeros_seen > best: best = zeros_seen return best def is_lex_greater(arr, S): for i in range(n): a = arr[i] s = S[i] if a != s: return a > s return False ans = 0 while True: if is_lex_greater(b, S): if lnds_binary(b, 0, n) >= K: i = K limit = n - K valid = False while i <= limit: if lnds_binary(b, 0, i) >= K and lnds_binary(b, i, n) >= K: valid = True break i += 1 if valid: ans += 1 if ans >= self.MOD: ans -= self.MOD if not next_permutation(b): break return ans % self.MOD","import sys data = sys.stdin.read().split() it = iter(data) x = int(next(it)) y = int(next(it)) k = int(next(it)) a = next(it) solution = Solution() result = solution.solve(x, y, k, a) sys.stdout.write(str(result) + ""\n"")","string,dp",hard 350,"# Problem Statement The heroic outlaw Robin Hood is famous for taking from the rich and giving to the poor. Robin encounters $n$ people starting from the $1$-st and ending with the $n$-th. The $i$-th person has $a_i$ gold. If $a_i \ge k$, Robin will take all $a_i$ gold, and if $a_i=0$, Robin will give $1$ gold if he has any. Robin starts with $0$ gold. Find out how many people Robin gives gold to. The main function of the solution is defined as: ```python class Solution: def solve(self, n, x, a): pass # write your code here``` where: - return:the number of people that will get gold from Robin Hood. # Example 1: - Input: n = 2, k = 2, a = [2, 0] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $1 \leq k \leq 1000$ - $0 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, k, a): cnt = 0 s = 0 for i in range(n): x = a[i] if x >= k: s += x elif x == 0 and s > 0: cnt += 1 s -= 1 return cnt def solve2(self, n, k, a): cnt = 0 s = 0 for i in range(n): x = a[i] if x >= k: s += x elif x == 0 and s > 0: cnt += 1 s -= 1 return cnt ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) x = int(next(it)) a = [] for i in range(n): a.append(int(next(it))) solution = Solution() result = solution.solve(n, x, a) sys.stdout.write(str(result) + ""\n"")",math,easy 351,"Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. solution main function ```python class Solution: def solve(self, s, word_dict): pass # write your code here``` Example 1: Input: s = ""leetcode"", wordDict = [""leet"",""code""] Output: 1 Example 2: Input: s = ""applepenapple"", wordDict = [""apple"",""pen""] Output: 1 Constraints: 1 <= s.length <= @data 1 <= wordDict.length <= @data 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 500, 1000]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import collections class Solution: def solve1(self, s: str, wordDict: list[str]) -> bool: dp = [False] * (len(s) + 1) dp[0] = True for i in range(1, len(s) + 1): for w in wordDict: word_len = len(w) if i - word_len >= 0: if dp[i - word_len] and s[i - word_len:i] == w: dp[i] = True break return dp[-1] def solve2(self, s: str, wordDict: list[str]) -> bool: n = len(s) if n == 0: return True min_len = len(wordDict[0]) max_len = len(wordDict[0]) for w in wordDict[1:]: lw = len(w) if lw < min_len: min_len = lw if lw > max_len: max_len = lw total_masks = 1 << (n - 1) for mask in range(total_masks): start = 0 valid = True i = 0 while i < n: boundary = (i == n - 1) or ((mask >> i) & 1) if boundary: seg_len = i - start + 1 if seg_len < min_len or seg_len > max_len: valid = False break matched = False for w in wordDict: if len(w) != seg_len: continue k = 0 while k < seg_len and s[start + k] == w[k]: k += 1 if k == seg_len: matched = True break if not matched: valid = False break start = i + 1 i += 1 if valid and start == n: return True return False ","import sys def main(): data = sys.stdin.read().split() it = iter(data) n = int(next(it)) word_dict = [] for _ in range(n): word = next(it) word_dict.append(word) s = next(it) solution = Solution() result = solution.solve(s, word_dict) sys.stdout.write(""1"" if result else ""0"") if __name__ == ""__main__"": main()","string,dp,STL",medium 352,"# Problem Statement You are on an undirected connected graph of `n` vertices and `m` weighted edges. The edges are indexed from `1` to `m`. The `i`-th edge connects vertex `u[i]` and `v[i]`, and has weight `w[i]`. Starting at vertex `1`, you need to mark every edge at least once and finally return to vertex `1`. You may repeatedly perform the following operations: - Move along an edge: If you are at vertex `x`, choose an edge `(x, y)` (with index `e`) and move to `y`, paying exactly `w[e]`. The edge becomes marked. - Transfer by train: If you are at `x` and want to go to any vertex `z ≠ x`, choose any path from `x` to `z` (not necessarily simple). If the indices of edges on this path are `e1, e2, ..., ek`, you pay `w[max(e1, ..., ek)]`. Note this cost depends on the weight of the edge with the maximum index on the chosen path, not the maximum weight on the path. Compute the minimum total cost to mark every edge at least once and return to vertex `1`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, u, v, w): pass # write your code here``` where: - `n`: number of vertices - `m`: number of edges - `u[i], v[i]`: endpoints of the i-th edge (1-indexed vertices) - `w[i]`: weight of the i-th edge - return: the minimum total cost # Example: - Input: ``` n = 4, m = 3 edges: 1 2 3 1 3 2 1 4 1 ``` - Output: ``` 8 ``` # Constraints: - $1 \leq n \leq @data$ - $0 \leq m \leq @data$ - $1 \leq u[i], v[i] \leq n$ - $1 \leq w[i] \leq 10^9$ - The graph is connected (except possibly when `n = 1`, `m = 0`) - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[5000, 2500, 1250], [40000, 20000, 10000], [320000, 160000, 80000]]","import collections class Solution: def solve1(self, n, m, u, v, w): if m == 0: return 0 ans = 0 deg = [0] * n for i in range(m): u[i] -= 1 v[i] -= 1 deg[u[i]] += 1 deg[v[i]] += 1 ans += w[i] class DSU: def __init__(self, size): self.p = list(range(size)) def get(self, x): if self.p[x] == x: return x self.p[x] = self.get(self.p[x]) return self.p[x] def unite_force(self, x, y): root_x = self.get(x) root_y = self.get(y) if root_x != root_y: self.p[root_x] = root_y tot = n + m tree = [[] for _ in range(tot)] dsu = DSU(n) rt = list(range(n)) for i in range(m): x = dsu.get(u[i]) y = dsu.get(v[i]) cur = n + i if x == y: tree[rt[x]].append(cur) tree[cur].append(rt[x]) rt[x] = cur else: tree[rt[x]].append(cur) tree[cur].append(rt[x]) tree[rt[y]].append(cur) tree[cur].append(rt[y]) dsu.unite_force(x, y) rt[y] = cur root = n + m - 1 parent = [-1] * tot order = [] q = collections.deque([root]) parent[root] = -1 while q: vtx = q.popleft() order.append(vtx) for to in tree[vtx]: if to != parent[vtx]: parent[to] = vtx q.append(to) INF = 1000000007 up = [INF] * tot for vtx in order: if vtx >= n: up[vtx] = min(up[vtx], w[vtx - n]) if parent[vtx] != -1: up[vtx] = min(up[vtx], up[parent[vtx]]) cnt = [0] * tot for i in range(n): if deg[i] % 2 == 1: cnt[i] = 1 for i in range(len(order) - 1, -1, -1): vtx = order[i] ans += up[vtx] * (cnt[vtx] // 2) if parent[vtx] != -1: cnt[parent[vtx]] += cnt[vtx] % 2 return ans def solve2(self, n, m, u, v, w): if m == 0: return 0 for i in range(m): u[i] -= 1 v[i] -= 1 ans = 0 for i in range(m): ans += w[i] p = list(range(n)) def get(x): while p[x] != x: p[x] = p[p[x]] x = p[x] return x rt = list(range(n)) tot = n + m parent = [-1] * tot for i in range(m): x = get(u[i]) y = get(v[i]) cur = n + i if x == y: px = rt[x] parent[px] = cur rt[x] = cur else: parent[rt[x]] = cur parent[rt[y]] = cur p[x] = y rt[y] = cur INF = 10**18 up = [INF] * tot for vtx in range(tot - 1, -1, -1): if vtx >= n: wi = w[vtx - n] if wi < up[vtx]: up[vtx] = wi pnt = parent[vtx] if pnt != -1 and up[pnt] < up[vtx]: up[vtx] = up[pnt] deg = [0] * n for i in range(m): deg[u[i]] += 1 deg[v[i]] += 1 cnt = [0] * tot for i in range(n): cnt[i] = deg[i] & 1 for vtx in range(tot): pair = cnt[vtx] >> 1 if pair: ans += up[vtx] * pair rem = cnt[vtx] & 1 pnt = parent[vtx] if pnt != -1: cnt[pnt] += rem return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) u = [0] * m v = [0] * m w = [0] * m for i in range(m): u[i] = int(next(it)) v[i] = int(next(it)) w[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, u, v, w) sys.stdout.write(str(result) + ""\n"")","graph,greedy",hard 353,"# Problem Statement The square still has a rectangular shape of $n \times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement. You are given the picture of the squares: - if $a_{i,j} = $ ""\*"", then the $j$-th square in the $i$-th row should be **black**; - if $a_{i,j} = $ ""."", then the $j$-th square in the $i$-th row should be **white**. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: - $1 \times 1$ tiles — each tile costs $x$ burles and covers exactly $1$ square; - $1 \times 2$ tiles — each tile costs $y$ burles and covers exactly $2$ adjacent squares of the **same row**. **Note that you are not allowed to rotate these tiles or cut them into $1 \times 1$ tiles.** **You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.** What is the smallest total price of the tiles needed to cover all the white squares? The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, x, y, a): pass # write your code here``` where: - return: the smallest total price of the tiles needed to cover all the white squares in burles. # Example 1: - Input: n = 1, m = 1, x = 10, y = 1 a = ""."" - Output: 10 # Constraints: - $1 \leq n * m \leq @data$ - $1 \leq x, y \leq 10^3$ - $a[i][j] \in \{'.', '*'\}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, m, x, y, a): ans = 0 y = min(y, 2 * x) for i in range(n): l = 0 while l < m: if a[i][l] == '*': l += 1 else: r = l while r < m and a[i][r] == '.': r += 1 ans += (r - l) // 2 * y + (r - l) % 2 * x l = r return ans def solve2(self, n, m, x, y, a): ans = 0 if y >= 2 * x: for i in range(n): for j in range(m): if a[i][j] == '.': ans += x else: for i in range(n): j = 0 while j < m: if a[i][j] == '*': j += 1 else: if j + 1 < m and a[i][j + 1] == '.': ans += y j += 2 else: ans += x j += 1 return ans ","import sys def main(): data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) x = int(next(it)) y = int(next(it)) a = [[''] * m for _ in range(n)] for i in range(n): row = list(next(it)) for j in range(m): a[i][j] = row[j] solution = Solution() result = solution.solve(n, m, x, y, a) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","greedy,dp,two_pointers",medium 354,"You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands. solution main function ```python class Solution: def solve(self, g1, g2): pass # write your code here``` Example 1: Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] Output: 3 Example 2: Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] Output: 2 Constraints: m == grid1.length == grid2.length n == grid1[i].length == grid2[i].length 1 <= m, n <= @data grid1[i][j] and grid2[i][j] are either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 500]",4000,"[[500, 390, 234], [4000, 3125, 1875], [32000, 25000, 15000]]","import sys class Solution: def solve1(self, grid1, grid2): m = len(grid1) n = len(grid1[0]) count = 0 directions = ((1, 0), (-1, 0), (0, 1), (0, -1)) for i in range(m): for j in range(n): if grid2[i][j] == 1: stack = [(i, j)] grid2[i][j] = 0 is_sub_island = grid1[i][j] == 1 while stack: x, y = stack.pop() for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < m and 0 <= ny < n and grid2[nx][ny] == 1: if grid1[nx][ny] == 0: is_sub_island = False grid2[nx][ny] = 0 stack.append((nx, ny)) if is_sub_island: count += 1 return count def solve2(self, grid1, grid2): m = len(grid1) n = len(grid1[0]) for i in range(m): for j in range(n): if grid2[i][j] == 1 and grid1[i][j] == 0: stack = [(i, j)] grid2[i][j] = 0 while stack: x, y = stack.pop() if x > 0 and grid2[x - 1][y] == 1: grid2[x - 1][y] = 0 stack.append((x - 1, y)) if x + 1 < m and grid2[x + 1][y] == 1: grid2[x + 1][y] = 0 stack.append((x + 1, y)) if y > 0 and grid2[x][y - 1] == 1: grid2[x][y - 1] = 0 stack.append((x, y - 1)) if y + 1 < n and grid2[x][y + 1] == 1: grid2[x][y + 1] = 0 stack.append((x, y + 1)) count = 0 for i in range(m): for j in range(n): if grid2[i][j] == 1: count += 1 stack = [(i, j)] grid2[i][j] = 0 while stack: x, y = stack.pop() if x > 0 and grid2[x - 1][y] == 1: grid2[x - 1][y] = 0 stack.append((x - 1, y)) if x + 1 < m and grid2[x + 1][y] == 1: grid2[x + 1][y] = 0 stack.append((x + 1, y)) if y > 0 and grid2[x][y - 1] == 1: grid2[x][y - 1] = 0 stack.append((x, y - 1)) if y + 1 < n and grid2[x][y + 1] == 1: grid2[x][y + 1] = 0 stack.append((x, y + 1)) return count ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) g1 = [] g2 = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) g1.append(temp) for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) g2.append(temp) solution = Solution() result = solution.solve(g1, g2) sys.stdout.write(str(result))","graph,search",medium 355,"You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution. Return the minimum unfairness of all distributions. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example: Input: cookies = [1,2,3], k = 2 Output: 3 Explanation: Give bags [1,2] to one child and [3] to the other child. Constraints: 2 <= cookies.length <= 8 1 <= cookies[i] <= @data 2 <= k <= cookies.length Time limit: @time_limit ms Memory limit: @memory_limit KB ","[4, 6, 8]",4000,"[[2000, 100, 64], [16000, 800, 400], [128000, 6400, 3200]]","import sys class Solution: def helper(self, cookies, k, children, index): if index == len(cookies): self.foo = min(self.foo, max(children)) return self.foo ans = float('inf') for i in range(k): children[i] += cookies[index] if children[i] < self.foo: ans = min(ans, self.helper(cookies, k, children, index + 1)) children[i] -= cookies[index] if children[i] == 0: break return ans def solve1(self, cookies, k): self.foo = float('inf') children = [0] * k self.helper(cookies, k, children, 0) return self.foo def solve2(self, cookies, k): n = len(cookies) if k == 1: s = 0 for i in range(n): s += cookies[i] return s if k >= n: mx = 0 for i in range(n): if cookies[i] > mx: mx = cookies[i] return mx s0 = s1 = s2 = s3 = s4 = s5 = s6 = s7 = 0 d0 = d1 = d2 = d3 = d4 = d5 = d6 = d7 = 0 total = 0 for i in range(n): total += cookies[i] s0 = total lower = (total + k - 1) // k best = total def addsum(child, delta): nonlocal s0, s1, s2, s3, s4, s5, s6, s7 if child == 0: s0 += delta elif child == 1: s1 += delta elif child == 2: s2 += delta elif child == 3: s3 += delta elif child == 4: s4 += delta elif child == 5: s5 += delta elif child == 6: s6 += delta else: s7 += delta def maxsum(): m = s0 if k >= 2 and s1 > m: m = s1 if k >= 3 and s2 > m: m = s2 if k >= 4 and s3 > m: m = s3 if k >= 5 and s4 > m: m = s4 if k >= 6 and s5 > m: m = s5 if k >= 7 and s6 > m: m = s6 if k >= 8 and s7 > m: m = s7 return m def getd(i): if i == 0: return d0 elif i == 1: return d1 elif i == 2: return d2 elif i == 3: return d3 elif i == 4: return d4 elif i == 5: return d5 elif i == 6: return d6 else: return d7 def setd(i, v): nonlocal d0, d1, d2, d3, d4, d5, d6, d7 if i == 0: d0 = v elif i == 1: d1 = v elif i == 2: d2 = v elif i == 3: d3 = v elif i == 4: d4 = v elif i == 5: d5 = v elif i == 6: d6 = v else: d7 = v while True: cur_max = maxsum() if cur_max < best: best = cur_max if best == lower: return best pos = 0 while True: if pos >= n: return best cur = getd(pos) if cur == k - 1: addsum(k - 1, -cookies[pos]) addsum(0, cookies[pos]) setd(pos, 0) pos += 1 else: addsum(cur, -cookies[pos]) addsum(cur + 1, cookies[pos]) setd(pos, cur + 1) break ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result) + ""\n"")","bit_manipulation,dp",medium 356,"# Problem Statement You are given a sequence a of n positive integers. You may partition the sequence into one or more consecutive subarrays whose concatenation equals a. For a subarray b = [b1, b2, ..., bk], define its cost as: cost(b) = ceil(bk / min(b1, b2, ..., bk)) The total cost of a partition is the sum of the costs of its subarrays. Let f(a) be the minimum possible total cost over all valid partitions of a. Compute f(a). The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: length of the sequence a - `a`: array of positive integers - return: the minimal total cost f(a) # Example 1: - Input: ``` n = 5 a = [3, 1, 4, 1, 5] ``` - Output: ``` 2 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^{18}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 400000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import bisect class Solution: def solve1(self, n, a): seq = [] for i in range(n): while seq and a[i] <= seq[-1]: seq.pop() seq.append(a[i]) m = len(seq) INF = 1000000000 dp = [INF] * (m + 1) dp[0] = 0 for i in range(m): for cost in range(1, 4): limit = seq[i] * cost p = bisect.bisect_right(seq, limit) dp[p] = min(dp[p], dp[i] + cost) return dp[m] def solve2(self, n, a): if n == 0: return 0 best = (1 << 62) limit = 1 << (n - 1) for mask in range(limit): total = 0 cur_min = a[0] ok = True for i in range(n): if i > 0 and a[i] < cur_min: cur_min = a[i] if i == n - 1 or ((mask >> i) & 1): total += (a[i] + cur_min - 1) // cur_min if total >= best: ok = False break if i + 1 < n: cur_min = a[i + 1] if ok and total < best: best = total return best ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,dp",hard 357,"# Problem Statement Even in university, students need to relax. That is why Sakurakos teacher decided to go on a field trip. It is known that all of the students will be walking in one line. The student with index $i$ has some topic of interest which is described as $a_i$. As a teacher, you want to minimise the disturbance of the line of students. The disturbance of the line is defined as the number of neighbouring people with the same topic of interest. In other words, disturbance is the number of indices $j$ ($1 \le j < n$) such that $a_j = a_{j + 1}$. In order to do this, you can choose index $i$ ($1\le i\le n$) and swap students at positions $i$ and $n-i+1$. You can perform any number of swaps. Your task is to determine the minimal amount of disturbance that you can achieve by doing the operation described above any number of times. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the minimal amount of disturbance that you can achieve by doing the operation described above any number of times # Example 1: - Input: n = 5 a = [1, 1, 1, 2, 3] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = 0 for i in range(1, (n - 1) // 2 + 1): x = a[i] y = a[n - 1 - i] z = a[i - 1] w = a[n - i] ans += min((x == z) + (y == w), (x == w) + (y == z)) if n % 2 == 0: ans += (a[n // 2 - 1] == a[n // 2]) return ans def solve2(self, n, a): k = n // 2 best = n for mask in range(1 << k): cur = 0 for j in range(n - 1): m = n - 1 - j p_j = j if j < m else m bit_j = 0 if p_j >= k else (mask >> p_j) & 1 v1 = a[j] if bit_j == 0 else a[m] j1 = j + 1 m1 = n - 1 - j1 p_j1 = j1 if j1 < m1 else m1 bit_j1 = 0 if p_j1 >= k else (mask >> p_j1) & 1 v2 = a[j1] if bit_j1 == 0 else a[m1] if v1 == v2: cur += 1 if cur < best: best = cur return best ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy,two_pointers",hard 358,"You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x. Return the minimum possible value of nums[n - 1]. solution main function ```python class Solution: def solve(self, n, x): pass # write your code here``` Example 1: Input: n = 3, x = 4 Output: 6 Example 2: Input: n = 2, x = 7 Output: 15 Constraints: 1 <= n, x <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 100000, 100000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, x): result = x n -= 1 mask = 1 while n > 0: if (mask & x) == 0: result |= (n & 1) * mask n >>= 1 mask <<= 1 return result def solve2(self, n, x): res = x k = n - 1 mask = 1 while k > 0: if (x & mask) == 0: if k & 1: res |= mask k >>= 1 mask <<= 1 return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) x = int(next(it)) solution = Solution() result = solution.solve(n, x) sys.stdout.write(str(result) + ""\n"")",math,hard 359,"# Problem Statement Today, Sakurako was studying arrays. An array $a$ of length $n$ is considered good if and only if: - the array $a$ is increasing, meaning $a_{i - 1} < a_i$ for all $2 \le i \le n$; - the differences between adjacent elements are increasing, meaning $a_i - a_{i-1} < a_{i+1} - a_i$ for all $2 \le i < n$. Sakurako has come up with boundaries $l$ and $r$ and wants to construct a good array of maximum length, where $l \le a_i \le r$ for all $a_i$. Help Sakurako find the maximum length of a good array for the given $l$ and $r$. The main function of the solution is defined as: ```python class Solution: def solve(self, l, r): pass # write your code here``` where: - return:the length of the longest good array Sakurako can form given l and r. # Example 1: - Input: l = 1, r = 2 - Output: 2 # Constraints: - $1 \leq l \leq r \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 1000000, 1000000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, l, r): n = r - l if n < 0: return -2147437307 a = int(math.isqrt(2 * n)) while a * (a + 1) // 2 <= n: a += 1 return a def solve2(self, l, r): n = r - l if n < 0: return -2147437307 s = 0 i = 1 cnt = 0 while s + i <= n: s += i i += 1 cnt += 1 return cnt + 1 ","import sys data = sys.stdin.read().strip().split() it = iter(data) l = int(next(it)) r = int(next(it)) solution = Solution() result = solution.solve(l, r) sys.stdout.write(str(result) + ""\n"")",math,easy 360,"# Problem Statement Given $N$, $V$, an array $v$ of length $N$ representing the volume of items, and an array $w$ of length $N$ representing the value of items: There are $N$ items and a backpack with a capacity of $V$. Each item can only be used once. The $i$-th item has a volume of $v[i]$ and a value of $w[i]$. Determine which items to put in the backpack such that the **total volume does not exceed the backpack's capacity** and the **total value is maximized**. Return the maximum total value. The solution's main function is: ```python class Solution: def solve(self, N, V, v, w): pass # write your code here``` where: - `N` is the number of items, - `V` is the capacity of the backpack, - `v` is the array of item volumes, - `w` is the array of item values. # Example 1 - Input: N = 3 V = 4 v = [4, 3, 1] w = [1, 2, 1] - Output: 3 # Constraints: - $1 \leq N, V, v[i], w[i] \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, N, V, v, w): dp = [0] * (V + 1) for i in range(N): for j in range(V, v[i] - 1, -1): dp[j] = max(dp[j], dp[j - v[i]] + w[i]) return dp[V] def solve2(self, N, V, v, w): max_val = 0 sum_v = 0 sum_w = 0 prev_g = 0 total = 1 << N for k in range(total): g = k ^ (k >> 1) if k: diff = g ^ prev_g i = diff.bit_length() - 1 if g & diff: sum_v += v[i] sum_w += w[i] else: sum_v -= v[i] sum_w -= w[i] if sum_v <= V and sum_w > max_val: max_val = sum_w prev_g = g return max_val ","import sys data = sys.stdin.read().split() it = iter(data) N = int(next(it)) V = int(next(it)) v = [] w = [] for i in range(N): x = int(next(it)) v.append(x) for i in range(N): x = int(next(it)) w.append(x) solution = Solution() result = solution.solve(N, V, v, w) sys.stdout.write(str(result) + ""\n"")",dp,easy 361,"# Problem Statement: You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved. Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by **one or several** messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions. Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. **It is guaranteed that the dialog begins with the question of the client.** You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` Where: - `n` is an integer representing the number of messages in the conversation. - `s` is a string where each character represents the type of a message: - `'Q'` for a customer query. - `'A'` for a manager's response. - The return value is a string: `""YES""` if the dialog may correspond to the rules of work, and `""NO""` otherwise. # Example 1: - Input: n = 3 s = ""QAA"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n: int, s: str) -> str: cur = 0 for i in range(n - 1, -1, -1): if s[i] == 'A': cur += 1 else: cur -= 1 if cur < 0: return ""NO"" return ""YES"" def solve2(self, n: int, s: str) -> str: cur = 0 for i in range(n - 1, -1, -1): if s[i] == 'A': cur += 1 else: if cur == 0: return ""NO"" cur -= 1 return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,math",medium 362,"# Problem Statement There are $n$ flowers in a row, the $i$-th of them initially has a positive height of $h_i$ meters. Every second, the wind will blow from the left, causing the height of some flowers to decrease. Specifically, every second, for each $i$ from $1$ to $n$, in this order, the following happens: - If $i = n$ or $h_i > h_{i + 1}$, the value of $h_i$ changes to $\max(0, h_i - 1)$. How many seconds will pass before $h_i=0$ for all $1 \le i \le n$ for the first time? The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of seconds that will pass before hi=0 for all 1≤i≤n. # Example 1: - Input: n = 3 h = [1, 1, 2] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq h[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, h): ans = 0 for i in range(n - 1, -1, -1): ans = max(ans, i + h[i]) return ans def solve2(self, n, h): ans = 0 for i in range(n): val = h[i] + i if val > ans: ans = val return ans ","import sys line = sys.stdin.readline().strip() if line == """": n = 0 else: n = int(line) a = [0] * n if n > 0: parts = [] while len(parts) < n: parts += sys.stdin.readline().strip().split() for i in range(n): a[i] = int(parts[i]) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","dp,sort",medium 363,"The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. For example, the beauty of ""abaacc"" is 3 - 1 = 2. Given a string s, return the sum of beauty of all of its substrings. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""aabcb"" Output: 5 Example 2: Input: s = ""aabcbaa"" Output: 17 Constraints: 1 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[50, 100, 500]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import sys class Solution: def calMinAndMax(self, freq): minCnt = sys.maxsize maxCnt = 0 for i in range(26): if freq[i] != 0: minCnt = min(minCnt, freq[i]) maxCnt = max(maxCnt, freq[i]) return maxCnt, minCnt def solve1(self, s): sum = 0 for i in range(len(s)): freq = [0] * 26 for j in range(i, len(s)): freq[ord(s[j]) - ord('a')] += 1 cnt = self.calMinAndMax(freq) maxCnt = cnt[0] minCnt = cnt[1] sum += (maxCnt - minCnt) return sum def solve2(self, s): n = len(s) res = 0 base = ord('a') for i in range(n): for j in range(i, n): length = j - i + 1 maxCnt = 0 minCnt = length for t in range(26): target = base + t cnt = 0 for k in range(i, j + 1): if ord(s[k]) == target: cnt += 1 if cnt: if cnt > maxCnt: maxCnt = cnt if cnt < minCnt: minCnt = cnt res += (maxCnt - minCnt) return res ","import sys def main(): data = sys.stdin.buffer.read().split() s = """" if data: s = data[0].decode() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()",other,medium 364,"You are given an m x n binary matrix grid. A row or column is considered palindromic if its values read the same forward and backward. You can flip any number of cells in grid from 0 to 1, or from 1 to 0. Return the minimum number of cells that need to be flipped to make either all rows palindromic or all columns palindromic. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: grid = [[1,0,0],[0,0,0],[0,0,1]] Output: 2 Example 2: Input: grid = [[0,1],[0,1],[0,0]] Output: 1 Constraints: m == grid.length n == grid[i].length 1 <= m * n <= @data 0 <= grid[i][j] <= 1 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, grid): m = len(grid) n = len(grid[0]) k = 0 for i in range(m): c = 0 l, r = 0, len(grid[i]) - 1 while l < r: if grid[i][l] != grid[i][r]: c += 1 l += 1 r -= 1 k += c c = 0 for i in range(n): l, r = 0, m - 1 while l < r: if grid[l][i] != grid[r][i]: c += 1 l += 1 r -= 1 return min(k, c) def solve2(self, grid): m = len(grid) n = len(grid[0]) row_flips = 0 for i in range(m): l, r = 0, n - 1 while l < r: if grid[i][l] != grid[i][r]: row_flips += 1 l += 1 r -= 1 col_flips = 0 for j in range(n): l, r = 0, m - 1 while l < r: if grid[l][j] != grid[r][j]: col_flips += 1 l += 1 r -= 1 return min(row_flips, col_flips) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = [] for i in range(1, n + 1): temp = [] for j in range(1, m + 1): x = int(next(it)) temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))","two_pointers,other",medium 365,"# Problem Statement There are $n$ coins on the table forming a circle, and each coin is either facing up or facing down. Alice and Bob take turns to play the following game, and Alice goes first. In each operation, the player chooses a facing-up coin, removes the coin, and flips the two coins that are adjacent to it. If (before the operation) there are only two coins left, then one will be removed and the other won't be flipped (as it would be flipped twice). If (before the operation) there is only one coin left, no coins will be flipped. If (before the operation) there are no facing-up coins, the player loses. Decide who will win the game if they both play optimally. It can be proved that the game will end in a finite number of operations, and one of them will win. The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - `n`: the number of coins, `s`: the orientation of the coins, where `'U'` means facing up and `'D'` means facing down - return: if Alice wins, return ""YES"", otherwise return ""NO"" # Example 1: - Input: n = 5 s = ""UUDUD"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - s[i] = 'U' or 'D' - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n: int, s: str) -> str: cnt = 0 for x in s: if x == 'U': cnt += 1 return ""YES"" if cnt % 2 else ""NO"" def solve2(self, n: int, s: str) -> str: parity = 0 for ch in s: if ch == 'U': parity ^= 1 return ""YES"" if parity else ""NO"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")",greedy,medium 366,"# Problem Statement After a trip with Sakurako, Kousuke was very scared because he forgot about his programming assignment. In this assignment, the teacher gave him an array $a$ of $n$ integers and asked him to calculate the number of **non-overlapping** segments of the array $a$, such that each segment is considered beautiful. A segment $[l,r]$ is considered beautiful if $a_l + a_{l+1} + \dots + a_{r-1} + a_r=0$. For a fixed array $a$, your task is to compute the maximum number of non-overlapping beautiful segments. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the maximum value of the same number at the end # Example 1: - Input: n = 5 a = [2, 1, -3, 2, 1] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $-10^4 \leq a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 100, 64], [4000, 800, 400], [32000, 6400, 3200]]","import sys from typing import List, Set class Solution: def solve1(self, n: int, a: List[int]) -> int: s: Set[int] = set() s.add(0) current_sum = 0 ans = 0 for i in range(n): current_sum += a[i] if current_sum in s: ans += 1 s.clear() s.add(0) current_sum = 0 s.add(current_sum) return ans def solve2(self, n, a): ans = 0 seg_start = 0 current_sum = 0 for i in range(n): current_sum += a[i] if current_sum == 0: ans += 1 seg_start = i + 1 current_sum = 0 else: temp = 0 j = seg_start found = False while j < i: temp += a[j] if temp == current_sum: found = True break j += 1 if found: ans += 1 seg_start = i + 1 current_sum = 0 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","data_structures,dp,greedy,math",easy 367,"There is A crossing pawn at $A$on the board that needs to go to the target $B$point. Pawn walking rules: can go down, or right. At the same time, there is an opposing horse at the $C$point on the board, and the point where the horse is located and all the points reachable by the jump step are called the control point of the opposing horse. Therefore, it is called ""horse blocking the river and pawn"". The board is represented by coordinates, $A$point $(0, 0)$, $B$point $(n, m)$, and the same horse position coordinates need to be given. Now you are asked to calculate the number of paths that the pawn can take from point $A$to point $B$, assuming that the position of the horse is fixed, not that the pawn moves one step at a time. solution main function ```python class Solution: def solve(self, n, m, x, y): pass # write your code here``` Pass in parameters: Four integers, $n,m,x,y$, represent the coordinates of point B and horse, respectively. Return parameters: An integer indicating the number of all paths. Example 1: Input: n=6,m=6,x=3,y=3 Output: 6 Constraints: 0 a: return 0 if b == 0 or b == a: return 1 if b > a - b: b = a - b res = 1 for i in range(1, b + 1): res = res * (a - b + i) // i return res pts = [] if 0 <= x <= n and 0 <= y <= m: pts.append((x, y)) moves = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] for dx, dy in moves: xx = x + dx yy = y + dy if 0 <= xx <= n and 0 <= yy <= m: pts.append((xx, yy)) if (0, 0) in pts or (n, m) in pts: return 0 total = comb(n + m, n) L = len(pts) contrib = 0 for mask in range(1, 1 << L): subset = [] for i in range(L): if (mask >> i) & 1: subset.append(pts[i]) subset.sort() valid = True prevx, prevy = 0, 0 ways = 1 lasty = -1 for px, py in subset: if py < lasty: valid = False break dx = px - prevx dy = py - prevy if dx < 0 or dy < 0: valid = False break ways *= comb(dx + dy, dx) prevx, prevy = px, py lasty = py if not valid: continue dx = n - prevx dy = m - prevy if dx < 0 or dy < 0: continue ways *= comb(dx + dy, dx) cnt = 0 t = mask while t: cnt += t & 1 t >>= 1 if cnt % 2 == 1: contrib -= ways else: contrib += ways return total + contrib ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) m = int(next(it)) x = int(next(it)) y = int(next(it)) solution = Solution() result = solution.solve(n, m, x, y) sys.stdout.write(str(result))",dp,medium 368,"You need to maintain an undirected simple graph. You are required to add and delete an edge, as well as query whether two points are connected. 0: Add an edge. It is guaranteed that it does not exist. 1: Delete an edge. It is guaranteed that it exists. 2: Query whether two points are connected. n represents the total number of nodes (1-n). edges[i] = [op, a, b], where op represents the operation, and a and b represent the two points involved in the operation. For each query with op = 2, Y or N indicate whether the two nodes are connected., store the result in a vector array and return it. solution main function ```python class Solution: def solve(self, n, edge): pass # write your code here``` Example 1: Input: n = 200, edges = [[2,123,127],[0,123,127],[2,123,127],[1,127,123],[2,123,127]] Output: ['N','Y','N'] Constraints: 2 <= n <= @data edges[i].size ==3 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",6000,"[[2000, 2000, 2000], [128000, 128000, 128000], [160000, 160000, 160000]]","import sys from array import array class Solution: def solve1(self, n, edges): m = len(edges) lim = max(n, m) + 10 qu = array('I', [0] * lim) qv = array('I', [0] * lim) fa = array('I', range(lim)) siz = array('I', [1] * lim) his_kind = array('B') his_idx = array('I') his_val = array('I') def find_root(u: int) -> int: while fa[u] != u: u = fa[u] return u def merge(u: int, v: int) -> bool: u = find_root(u) v = find_root(v) if u == v: return False if siz[u] < siz[v]: u, v = v, u his_kind.append(0); his_idx.append(u); his_val.append(siz[u]) his_kind.append(1); his_idx.append(v); his_val.append(fa[v]) siz[u] = siz[u] + siz[v] fa[v] = u return True def undo_once() -> None: for _ in range(2): kind = his_kind.pop() idx = his_idx.pop() val = his_val.pop() if kind == 0: siz[idx] = val else: fa[idx] = val t = {} mdf = [] ans = [] qC = 1 for op, x, y in edges: if x > y: x, y = y, x if op == 0: t[(x, y)] = qC elif op == 1: start_time = t.pop((x, y)) mdf.append((start_time, qC - 1, x, y)) else: qu[qC] = x qv[qC] = y qC += 1 end_time = qC - 1 for (u, v), start_time in t.items(): mdf.append((start_time, end_time, u, v)) def dfs(l: int, r: int, cur_mdf) -> None: ml, mr = [], [] mid = (l + r) >> 1 merged_cnt = 0 for L, R, u, v in cur_mdf: if l >= L and r <= R: if merge(u, v): merged_cnt += 1 else: if L <= mid: ml.append((L, R, u, v)) if R > mid: mr.append((L, R, u, v)) if l == r: ans.append('Y' if find_root(qu[l]) == find_root(qv[l]) else 'N') for _ in range(merged_cnt): undo_once() return dfs(l, mid, ml) dfs(mid + 1, r, mr) for _ in range(merged_cnt): undo_once() if qC > 1: dfs(1, end_time, mdf) return ans def solve2(self, n, edges): ans = [] N = n + 1 fa = array('I', range(N)) def find(u): while fa[u] != u: u = fa[u] return u def union(u, v): ru = find(u) rv = find(v) if ru != rv: fa[rv] = ru for i in range(len(edges)): op, x, y = edges[i] if op != 2: continue for k in range(1, N): fa[k] = k if x == y: ans.append('Y') continue seen = set() for j in range(i - 1, -1, -1): oj, a, b = edges[j] if oj == 2: continue mn = a if a < b else b mx = b if a < b else a key = mn * N + mx if key in seen: continue seen.add(key) if oj == 0: union(a, b) if find(x) == find(y): break ans.append('Y' if find(x) == find(y) else 'N') return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) edge = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) z = int(next(it)) temp = [] temp.append(x) temp.append(y) temp.append(z) edge.append(temp) solution = Solution() result = solution.solve(n, edge) out = [] for it2 in result: out.append(str(it2)) sys.stdout.write(' '.join(out))",graph,medium 369,"Alice and Bob have an undirected graph of n nodes and three types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can be traversed by both Alice and Bob. Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. solution main function ```python class Solution: def solve(self, n, e): pass # write your code here``` Example 1: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] Output: 2 Example 2: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] Output: 0 Constraints: 1 <= n <= @data 1 <= edges.length <= min(10^5, 3 * n * (n - 1) / 2) edges[i].length == 3 1 <= typei <= 3 1 <= ui < vi <= n All tuples (typei, ui, vi) are distinct. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def getRoot(self, par, x): root = x while par[root] != root: root = par[root] current = x while par[current] != root: tmp = par[current] par[current] = root current = tmp return root def merge(self, par, x, y): _x = self.getRoot(par, x) _y = self.getRoot(par, y) if _x != _y: par[_x] = _y return True return False def solve1(self, n, edges): par1 = list(range(n + 1)) ans = 0 cnt1 = n for edge in edges: if edge[0] == 3: if not self.merge(par1, edge[1], edge[2]): ans += 1 else: cnt1 -= 1 par2 = list(par1) cnt2 = cnt1 for edge in edges: if edge[0] == 1: if not self.merge(par1, edge[1], edge[2]): ans += 1 else: cnt1 -= 1 elif edge[0] == 2: if not self.merge(par2, edge[1], edge[2]): ans += 1 else: cnt2 -= 1 if cnt1 != 1 or cnt2 != 1: return -1 return ans def solve2(self, n, edges): par = [i for i in range(n + 1)] cnt = n used3 = 0 for t, u, v in edges: if t == 3: if self.merge(par, u, v): used3 += 1 cnt -= 1 used1 = 0 for t, u, v in edges: if t == 1: if self.merge(par, u, v): used1 += 1 cnt -= 1 if cnt != 1: return -1 for i in range(1, n + 1): par[i] = i cnt2 = n for t, u, v in edges: if t == 3: if self.merge(par, u, v): cnt2 -= 1 used2 = 0 for t, u, v in edges: if t == 2: if self.merge(par, u, v): used2 += 1 cnt2 -= 1 if cnt2 != 1: return -1 return len(edges) - (used3 + used1 + used2)","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) e = [] for i in range(1, m + 1): x = int(next(it)) y = int(next(it)) z = int(next(it)) temp = [] temp.append(x) temp.append(y) temp.append(z) e.append(temp) solution = Solution() result = solution.solve(n, e) sys.stdout.write(str(result))","graph,data_structures",medium 370,"You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available: A paid painter that paints the ith wall in time[i] units of time and takes cost[i] units of money. A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied. Return the minimum amount of money required to paint the n walls. solution main function ```python class Solution: def solve(self, a, b): pass # write your code here``` Example 1: Input: cost = [1,2,3,2], time = [1,2,3,2] Output: 3 Example 2: Input: cost = [2,3,4,2], time = [1,1,1,1] Output: 4 Constraints: 1 <= cost.length <= @data cost.length == time.length 1 <= cost[i] <= 10^6 1 <= time[i] <= 500 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[50, 100, 1000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import math class Solution: def solve1(self, cost, time): n = len(cost) dp = [math.inf] * (n + 1) dp[0] = 0 for end in range(n): for wall in range(n, 0, -1): dp[wall] = min(dp[wall], dp[max(0, wall - time[end] - 1)] + cost[end]) return dp[n] def solve2(self, cost, time): n = len(cost) ans = float('inf') for mask in range(1 << n): cnt = 0 sum_time = 0 sum_cost = 0 exceeded = False for i in range(n): if (mask >> i) & 1: cnt += 1 sum_time += time[i] sum_cost += cost[i] if sum_cost >= ans: exceeded = True break if not exceeded and cnt + sum_time >= n and sum_cost < ans: ans = sum_cost if ans == float('inf'): total = 0 for x in cost: total += x return total return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] b = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) for i in range(1, n + 1): x = int(next(it)) b.append(x) solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result) + ""\n"")",dp,hard 371,"Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. A boomerang is a set of three points that are all distinct and not in a straight line. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: points = [[1,1],[2,3],[3,2]] Output: 1 Example 2: Input: points = [[1,1],[2,2],[3,3]] Output: 0 Constraints: points.length == 3 points[i].length == 2 0 <= xi, yi <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[20, 50, 100]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, p: list[list[int]]) -> bool: return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]) def solve2(self, p: list[list[int]]) -> bool: x1, y1 = p[0][0], p[0][1] x2, y2 = p[1][0], p[1][1] x3, y3 = p[2][0], p[2][1] if x1 == x2 and y1 == y2: return False if x1 == x3 and y1 == y3: return False if x2 == x3 and y2 == y3: return False return (x2 - x1) * (y3 - y1) != (y2 - y1) * (x3 - x1) ","import sys def main(): s = [] data = sys.stdin.read().strip().split() idx = 0 for i in range(1, 4): temp = [] for j in range(1, 3): x = int(data[idx]) idx += 1 temp.append(x) s.append(temp) solution = Solution() result = solution.solve(s) if isinstance(result, bool): sys.stdout.write('1' if result else '0') else: sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","math,sort,other",easy 372,"You are given an m x n binary matrix grid and an integer health. You start on the upper-left corner (0, 0) and would like to get to the lower-right corner (m - 1, n - 1). You can move up, down, left, or right from one cell to another adjacent cell as long as your health remains positive. Cells (i, j) with grid[i][j] = 1 are considered unsafe and reduce your health by 1. Return true if you can reach the final cell with a health value of 1 or more, and false otherwise. solution main function ```python class Solution: def solve(self, g, h): pass # write your code here``` Example 1: Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1 Output: 1 Example 2: Input: grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3 Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= @data 2 <= m * n 1 <= health <= m + n grid[i][j] is either 0 or 1. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[10, 20, 50]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import heapq class Solution: def solve1(self, grid, health): n = len(grid) m = len(grid[0]) pq = [] best = [[-1] * m for _ in range(n)] start_val = health - (1 if grid[0][0] == 1 else 0) if start_val <= 0: return False best[0][0] = start_val heapq.heappush(pq, (-start_val, 0, 0)) while pq: neg_val, row, col = heapq.heappop(pq) val = -neg_val if val < best[row][col]: continue if row == n - 1 and col == m - 1: return True for dr, dc in ((0, -1), (-1, 0), (0, 1), (1, 0)): nr, nc = row + dr, col + dc if 0 <= nr < n and 0 <= nc < m: next_val = val - (1 if grid[nr][nc] == 1 else 0) if next_val <= 0: continue if next_val > best[nr][nc]: best[nr][nc] = next_val heapq.heappush(pq, (-next_val, nr, nc)) return False def solve2(self, grid, health): n = len(grid) m = len(grid[0]) if n > 0 else 0 if n == 0 or m == 0: return False start_cost = 1 if grid[0][0] == 1 else 0 if health - start_cost <= 0: return False INF = health + 1 for i in range(n): row = grid[i] for j in range(m): orig = 1 if row[j] == 1 else 0 if i == 0 and j == 0: best = start_cost else: best = INF row[j] = (best << 1) | orig if (grid[n - 1][m - 1] >> 1) <= health - 1: return True changed = True while changed: changed = False for i in range(n): for j in range(m): val = grid[i][j] orig = val & 1 best = val >> 1 new_best = best if j > 0: nb_best = grid[i][j - 1] >> 1 t = nb_best + orig if t < new_best: new_best = t if i > 0: nb_best = grid[i - 1][j] >> 1 t = nb_best + orig if t < new_best: new_best = t if j + 1 < m: nb_best = grid[i][j + 1] >> 1 t = nb_best + orig if t < new_best: new_best = t if i + 1 < n: nb_best = grid[i + 1][j] >> 1 t = nb_best + orig if t < new_best: new_best = t if new_best < best: grid[i][j] = (new_best << 1) | orig changed = True if (grid[n - 1][m - 1] >> 1) <= health - 1: return True return (grid[n - 1][m - 1] >> 1) <= health - 1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) g = [[int(next(it)) for _ in range(m)] for _ in range(n)] h = int(next(it)) solution = Solution() result = solution.solve(g, h) sys.stdout.write(str(int(bool(result)))) ","graph,search",medium 373,"# Problem Statement You are given a two-player impartial game. There are $n$ piles of stones. Each pile contains an integer number of stones in the range $[1, m]$ (in this easy version, $m \le 2$). A subset of indices from $1$ to $n$ is marked as ""good"" (it is guaranteed that index $1$ is always good). Alice and Bob play for exactly $n-1$ turns, starting with Alice. In each turn: - From the current $p$ piles, choose any ""good"" index $i$ ($1 \le i \le p$), and remove the entire $i$-th pile. After removal, the number of piles decreases by $1$, and the remaining piles are re-indexed from $1$ to $p-1$. The notion of ""good"" indices is always applied to the current indexing. When only one pile remains, let $x$ be the number of stones in that pile. Alice wants to maximize $x$, while Bob wants to minimize it. Both play optimally. Over all valid initial configurations (i.e., arrays with each entry in $[1, m]$), compute the sum of the resulting $x$, modulo $10^9 + 7$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, good): pass # write your code here``` where: - `n`: number of piles - `m`: upper bound on stones per pile (in this version, `m ∈ {1,2}`) - `k`: number of good indices - `good`: strictly increasing array of size `k` listing good indices (guaranteed `good[0] = 1`) - return: the sum of final remaining stones $x$ over all valid configurations, modulo $10^9+7$ # Example 1: - Input: n = 2, m = 2 k = 1 good = [1] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $1 \leq m \leq 2$ - $1 \leq k \leq n$ - $1 = \text{good}[0] < \text{good}[1] < \cdots < \text{good}[k-1] \le n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 15, 20]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys MOD = 1000000007 class Solution: def solve1(self, n, m, k, good): def mod_pow(a, e): r = 1 a %= MOD while e > 0: if e & 1: r = (r * a) % MOD a = (a * a) % MOD e >>= 1 return r S = 0 for x in good: S |= (1 << (x - 1)) if m == 1: return 1 def remove_bit(x, pos): lower = x & ((1 << pos) - 1) upper = x >> (pos + 1) return lower | (upper << pos) ok = [[] for _ in range(n)] ok[n - 1] = [0, 1] for i in range(n - 2, -1, -1): p = n - i sz = 1 << p ok[i] = [0] * sz if i % 2 == 1: for mask in range(sz): val = 1 for pos in range(p): if (S >> pos) & 1: T = remove_bit(mask, pos) if not ok[i + 1][T]: val = 0 break ok[i][mask] = val else: for mask in range(sz): val = 0 for pos in range(p): if (S >> pos) & 1: T = remove_bit(mask, pos) if ok[i + 1][T]: val = 1 break ok[i][mask] = val cnt = [0] * (n + 1) full = 1 << n for mask in range(full): if ok[0][mask]: cnt[bin(mask).count('1')] += 1 ans = 0 for iVal in range(1, m + 1): for j in range(n + 1): ways = (mod_pow(iVal - 1, n - j) * mod_pow(m - iVal + 1, j)) % MOD ans = (ans + ways * cnt[j]) % MOD return (ans % MOD + MOD) % MOD def solve2(self, n, m, k, good): if m == 1: return 1 W = 32 MASKW = (1 << W) - 1 def leaf_value(M, path): r = 1 for t in range(n - 1, 0, -1): c = (path >> (W * (t - 1))) & MASKW pos = good[c] if r >= pos: r += 1 return (M >> (r - 1)) & 1 def eval_mask(M): if n == 1: return M & 1 d = 0 path = 0 inited = 0 agg = 0 while True: if d == n - 1: b = leaf_value(M, path) if d == 0: return b d -= 1 is_or = (d % 2 == 0) parent_agg = (agg >> d) & 1 if is_or: parent_agg |= b else: parent_agg &= b if parent_agg: agg |= (1 << d) else: agg &= ~(1 << d) c = (path >> (W * d)) & MASKW c += 1 path = (path & ~(MASKW << (W * d))) | (c << (W * d)) inited &= ~(1 << (d + 1)) continue if ((inited >> d) & 1) == 0: inited |= (1 << d) if d % 2 == 0: agg &= ~(1 << d) else: agg |= (1 << d) path = (path & ~(MASKW << (W * d))) p = n - d t = bisect_right(good, p) c = (path >> (W * d)) & MASKW done = False if d % 2 == 0: if ((agg >> d) & 1) == 1: done = True else: if ((agg >> d) & 1) == 0: done = True if done or c >= t: val = ((agg >> d) & 1) if d == 0: return val d -= 1 is_or = (d % 2 == 0) parent_agg = (agg >> d) & 1 if is_or: parent_agg |= val else: parent_agg &= val if parent_agg: agg |= (1 << d) else: agg &= ~(1 << d) c_parent = (path >> (W * d)) & MASKW c_parent += 1 path = (path & ~(MASKW << (W * d))) | (c_parent << (W * d)) inited &= ~(1 << (d + 1)) continue else: d += 1 inited &= ~(1 << d) continue total_masks = 1 << n count_win = 0 for M in range(total_masks): count_win = (count_win + eval_mask(M)) % MOD ans = (pow(2, n, MOD) + count_win) % MOD return ans % MOD","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) good = [0] * k for i in range(k): good[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, k, good) sys.stdout.write(str(result) + ""\n"")","dp,math",hard 374,"You are given a 0-indexed integer array nums. The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]). The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n. Return the xor-beauty of nums. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [1,4] Output: 5 Example 2: Input: nums = [15,45,20,2,34,35,5,44,32,30] Output: 34 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math from typing import List class Solution: def solve1(self, nums: List[int]) -> int: ans = 0 for num in nums: ans ^= num return ans def solve2(self, nums: List[int]) -> int: n = len(nums) ans = 0 for i in range(n): ai = nums[i] for j in range(n): v = ai | nums[j] for k in range(n): ans ^= (v & nums[k]) return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result))",other,medium 375,"# Problem Statement There are $n$ people on coordinates $1,2,\dots,n$ on a line, initially person $i$ stands at position $p_i = i$. You may place an attraction at an integer coordinate $x$ ($1 \le x \le n$) any number of times and in any order. When you place an attraction at $x$, every person moves one step towards $x$: - if $p_i = x$, no change; - if $p_i < x$, then $p_i \leftarrow p_i + 1$; - if $p_i > x$, then $p_i \leftarrow p_i - 1$. It can be proven that positions always remain within $[1,n]$. Each position $x$ has a value $a_x$. For a final position array $p = [p_1,\dots,p_n]$, define $$ score(p) = \sum_{i=1}^n a_{p_i}. $$ Over all distinct final position arrays $p$ reachable by placing attractions, compute the sum of $score(p)$, modulo $998244353$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: number of people and the length of array `a` - `a`: array of length `n`, where `a[x-1] = a_x` - return: sum of `score(p)` over all reachable distinct `p`, modulo `998244353` # Example 1: - Input: ``` n = 2 a = [5, 10] ``` - Output: ``` 45 ``` # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 250, 100], [4000, 2000, 800], [32000, 16000, 6400]]","import sys class Solution: def solve(self, n, a): MOD = 998244353 s = [0] * (n + 1) t = [0] * (n + 1) for i in range(1, n + 1): ai = a[i - 1] % MOD s[i] = s[i - 1] + ai if s[i] >= MOD: s[i] -= MOD t[i] = (t[i - 1] + s[i]) % MOD if n == 1: return a[0] % MOD if n == 2: val_a0 = a[0] % MOD val_a1 = a[1] % MOD return (3 * (val_a0 + val_a1)) % MOD ans = 0 for zl in range(2): for zr in range(2): m = n - 1 - zl - zr if m < 0: continue ways = 1 for c in range(m // 2 + 1): c1 = m - 2 * c if not (c1 == 0 and zr == 1): inv_c1p1 = pow(c1 + 1, MOD - 2, MOD) s1 = (t[n] - t[c1] - t[n - c1 - 1]) % MOD s1 = (s1 * (n - zl - zr)) % MOD s1 = (s1 * inv_c1p1) % MOD s1 = (s1 + zl * s[n - c1]) % MOD s1_part_zr = (s[n] - s[c1]) % MOD s1 = (s1 + zr * s1_part_zr) % MOD ans = (ans + s1 * ways) % MOD if (c + 1) * 2 <= m: num = ((m - 2 * c) * (m - 2 * c - 1)) % MOD den1 = pow(m - c, MOD - 2, MOD) den2 = pow(c + 1, MOD - 2, MOD) ways = (((ways * num) % MOD) * den1) % MOD ways = (ways * den2) % MOD return ans % MOD ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,hard 376,"# Problem Statement You are given an array of integers `a1, a2, ..., an` and an integer `X`. You may perform the following operation zero or more times: - Select index `i`, and increase `ai` by one. Let `a'` be the final array. Your goal is to perform the smallest number of operations such that `a'1 & a'2 & ... & a'n = X`, where `&` denotes the bitwise AND operation. There are `q` independent queries `X1, X2, ..., Xq`. For each query `X = Xi`, compute the minimal number of operations. Each query is processed independently from the same initial array `a`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, q, x): pass # write your code here``` where: - `n`: length of the array - `a`: the initial array, with `0 ≤ a[i] < 10 * n` - `q`: number of queries - `x`: query values, each `0 ≤ x[i] < 10 * n` - return: an array of `q` answers (operations count) for each query # Example: - Input: ``` n = 5, q = 4 a = [6, 4, 7, 5, 4] x = [0, 2, 4, 6] ``` - Output: ``` [1, 8, 0, 5] ``` # Constraints: - `2 ≤ n ≤ @data` - `1 ≤ q ≤ @data` - `0 ≤ a[i] < 10 * n` - `0 ≤ x[i] < 10 * n` - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[10000, 5000, 2000], [80000, 40000, 16000], [640000, 320000, 128000]]","import math class Solution: def solve1(self, n, a, q, xs): if n == 0: return [0] * q max_val = 0 if n > 0: max_val = max(max_val, max(a)) if q > 0: max_val = max(max_val, max(xs)) K = max(max_val.bit_length(), 1) inf = int(1E9) cnt_outer = [0] * (K + 1) mx = [0] * (K + 1) for val in a: for j in range(K + 1): if (val >> j) & 1: cnt_outer[j] += 1 else: if (val & ((1 << j) - 1)) >= (mx[j] & ((1 << j) - 1)): mx[j] = val ans = [0] * q for k in range(K): size = 1 << (K - 1 - k) sum_vals = [0] * size cnt_inner = [0] * size for val in a: if not ((val >> k) & 1): idx = val >> (k + 1) sum_vals[idx] += val & ((1 << k) - 1) cnt_inner[idx] += 1 i = 1 while i < size: for j in range(0, size, 2 * i): for l in range(i): sum_vals[j + l] += sum_vals[i + j + l] cnt_inner[j + l] += cnt_inner[i + j + l] i *= 2 for i in range(q): if (xs[i] >> k) & 1: mask = xs[i] >> (k + 1) ans[i] += (xs[i] & ((1 << (k + 1)) - 1)) * cnt_inner[mask] - sum_vals[mask] for i in range(q): t = -1 for j in range(K - 1, -1, -1): if (xs[i] >> j) & 1: if cnt_outer[j] < n: break else: if cnt_outer[j] == n: t = j break if t == -1: continue res = inf def get(x_in): x = x_in mask = xs[i] & (~x) if mask: j_bit = mask.bit_length() - 1 x &= ~((1 << j_bit) - 1) x |= xs[i] & ((1 << (j_bit + 1)) - 1) return x for j in range(t + 1, K + 1): if cnt_outer[j] < n - 1: x_val = get(mx[j]) y_val = (x_val | (1 << j)) & ~((1 << j) - 1) res = min(res, get(y_val) - x_val) ans[i] += res return ans def solve2(self, n, a, q, xs): if n == 0: return [0] * q max_val = 0 if n > 0: mv = a[0] for v in a: if v > mv: mv = v if mv > max_val: max_val = mv if q > 0: mv = xs[0] for v in xs: if v > mv: mv = v if mv > max_val: max_val = mv K = max(1, max_val.bit_length()) maskK = (1 << K) - 1 sum_a = 0 for v in a: sum_a += v res = [0] * q for qi in range(q): S = xs[qi] & maskK base_sum = 0 and_mask = maskK for ai in a: y = ai j = K - 1 while j >= 0: if (S >> j) & 1: if ((y >> j) & 1) == 0: y = (y & ~((1 << j) - 1)) + (1 << j) j -= 1 base_sum += y and_mask &= (y & maskK) T = and_mask & (~S) & maskK if T == 0: res[qi] = base_sum - sum_a continue min_extra = None for ai in a: y = ai j = K - 1 while j >= 0: if (S >> j) & 1: if ((y >> j) & 1) == 0: y = (y & ~((1 << j) - 1)) + (1 << j) j -= 1 z = y tmp = z & T while tmp != 0: p = tmp.bit_length() - 1 lowmask = (1 << (p + 1)) - 1 delta = (lowmask + 1) - (z & lowmask) z += delta z |= S tmp = z & T extra = z - y if min_extra is None or extra < min_extra: min_extra = extra res[qi] = base_sum - sum_a + (0 if min_extra is None else min_extra) return res ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) q = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) x = [0] * q for i in range(q): x[i] = int(next(it)) solution = Solution() result = solution.solve(n, a, q, x) out_lines = [] for i in range(len(result)): out_lines.append(str(result[i]) + ""\n"") sys.stdout.write("""".join(out_lines))","bit_manipulation,data_structures",hard 377,"Given a graph with n vertices (numbered 1 to n) and m undirected edges with non-negative weights, please calculate the distance from vertex s to each vertex. The data guarantees that you can reach any point starting from s. The `edges` array represents the edges in the graph. `edges[i] = [a, b, c]` indicates that there is an undirected edge with a weight of `c` between node `a` and node `b`. solution main function ```python class Solution: def solve(self, n, s, edges): pass # write your code here``` Example 1: Input: n = 4, s = 1, edges = [[1,2,2],[2,3,2],[2,4,1],[1,3,5],[3,4,3],[1,4,4]] Output: [0,2,4,3] Constraints: 2 <= n <= @data edges.size <=5*@data edges[i].size ==3 Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[2000, 500, 64], [16000, 4000, 400], [128000, 32000, 3200]]","import heapq class Solution: def solve1(self, n, s, edges): INF = 100000000 q = [] v = [[] for _ in range(n + 10)] dis = [INF] * (n + 10) vis = [False] * (n + 10) dis[s] = 0 heapq.heappush(q, (0, s)) for it in edges: x = it[0] y = it[1] t = it[2] v[x].append((y, t)) v[y].append((x, t)) while q: s_pair = heapq.heappop(q) x = s_pair[1] if vis[x]: continue vis[x] = True for i in range(len(v[x])): if dis[v[x][i][0]] > dis[x] + v[x][i][1]: dis[v[x][i][0]] = dis[x] + v[x][i][1] heapq.heappush(q, (dis[v[x][i][0]], v[x][i][0])) ans = [] for i in range(1, n + 1): ans.append(dis[i]) return ans def solve2(self, n, s, edges): INF = 10 ** 18 res = [INF] * n res[s - 1] = 0 i = 0 while i < n - 1: changed = False for e in edges: a = e[0] - 1 b = e[1] - 1 w = e[2] if res[a] + w < res[b]: res[b] = res[a] + w changed = True if res[b] + w < res[a]: res[a] = res[b] + w changed = True if not changed: break i += 1 return res","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) s = int(next(it)) edges = [] i = 1 while i <= m: x = int(next(it)) y = int(next(it)) z = int(next(it)) temp = [] temp.append(x) temp.append(y) temp.append(z) edges.append(temp) i += 1 solution = Solution() result = solution.solve(n, s, edges) out = [] i = 0 while i < n: out.append(str(result[i])) out.append(' ') i += 1 sys.stdout.write(''.join(out))",graph,medium 378,"# Problem Statement During her journey with Kosuke, Sakurako and Kosuke found a valley that can be represented as a matrix of size $n \times n$, where at the intersection of the $i$-th row and the $j$-th column is a mountain with a height of $a_{i,j}$. If $a_{i,j} < 0$, then there is a lake there. Kosuke is very afraid of water, so Sakurako needs to help him: - With her magic, she can select a square area of mountains and increase the height of each mountain on the main diagonal of that area by exactly one. More formally, she can choose a submatrix with the upper left corner located at $(i, j)$ and the lower right corner at $(p, q)$, such that $p-i=q-j$. She can then add one to each element at the intersection of the $(i + k)$-th row and the $(j + k)$-th column, for all $k$ such that $0 \le k \le p-i$. Determine the minimum number of times Sakurako must use her magic so that there are no lakes. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the minimum number of times Sakurako must use her magic, and it is of type long long # Example 1: - Input: n = 2 a = [[-1, 2], [3, 0]] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $-10^5 \leq a[i][j] \leq 10^5$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = 0 for i in range(-n + 1, n): mi = 0 start_j = max(0, i) end_j = min(n, n + i) for j in range(start_j, end_j): mi = min(mi, a[j - i][j]) ans += mi return -ans def solve2(self, n, a): ans = 0 for d in range(-n + 1, n): mi = 0 if d >= 0: r, c, length = 0, d, n - d else: r, c, length = -d, 0, n + d for k in range(length): v = a[r + k][c + k] if v < mi: mi = v ans += -mi return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): a[i][j] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,dp",hard 379,"# Problem Statement There are $n$ cows participating in a coding tournament. Cow $i$ has a Cowdeforces rating of $a_i$ (all distinct), and is initially in position $i$. The tournament consists of $n-1$ matches as follows: - The first match is between the cow in position $1$ and the cow in position $2$. - Subsequently, each match $i$ is between the cow in position $i+1$ and the winner of match $i-1$. - In each match, the cow with the higher Cowdeforces rating wins and proceeds to the next match. You are the owner of cow $k$. For you, winning the tournament is not important; rather, you want your cow to win in as many matches as possible. As an acquaintance of the tournament organizers, you can ask them to swap the position of your cow with another cow **only once**, or you can choose to do nothing. Find the maximum number of wins your cow can achieve. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a): pass # write your code here``` where: - return: the maximum number of wins cow k can achieve if you choose to swap (or do nothing) optimally. # Example 1: - Input: n = 6, k = 1 a = [12, 10, 14, 11, 8, 3] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $1 \leq k \leq n$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, k, a): pos1 = -1 pos2 = -1 for i in range(n): if a[i] > a[k - 1]: if pos1 == -1: pos1 = i + 1 else: pos2 = i + 1 break ans = 0 if pos1 == -1: ans = n - 1 elif pos2 == -1: if pos1 < k: tem = k - pos1 if pos1 == 1: tem -= 1 ans = max(pos1 - 2, tem, 0) else: ans = max(0, pos1 - 2) else: if pos1 < k: if pos2 > k: tem = k - pos1 if pos1 == 1: tem -= 1 ans = max(pos1 - 2, tem, 0) elif k > pos2: tem = pos2 - pos1 if pos1 == 1: tem -= 1 ans = max(pos1 - 2, tem, 0) elif k < pos1: ans = max(0, pos1 - 2) return ans def solve2(self, n, k, a): R = a[k - 1] best = 0 for s in range(1, n + 1): if 1 == s: W = R elif 1 == k: W = a[s - 1] if s != k else R else: W = a[0] wins = 0 for i in range(2, n + 1): if i == s: r = R elif i == k: r = a[s - 1] if s != k else R else: r = a[i - 1] if r > W: if r == R: wins += 1 W = r else: if W == R: wins += 1 if wins > best: best = wins return best ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a) sys.stdout.write(str(result) + ""\n"")",greedy,hard 380,"A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i]. solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: heights = [1,1,4,2,1,3] Output: 3 Example 2: Input: heights = [5,1,2,3,4] Output: 5 Constraints: 1 <= heights.length <= @data 1 <= heights[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections class Solution: def solve1(self, heights): expected = sorted(heights) cnt = 0 for i in range(len(heights)): if heights[i] != expected[i]: cnt += 1 return cnt def solve2(self, heights): n = len(heights) mismatches = 0 pos = 0 prev = None while pos < n: nxt = None if prev is None: for h in heights: if nxt is None or h < nxt: nxt = h else: for h in heights: if h > prev and (nxt is None or h < nxt): nxt = h cnt = 0 for h in heights: if h == nxt: cnt += 1 for _ in range(cnt): if heights[pos] != nxt: mismatches += 1 pos += 1 prev = nxt return mismatches ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) num = [] for i in range(1, n + 1): x = int(next(it)) num.append(x) solution = Solution() result = solution.solve(num) sys.stdout.write(str(result) + ""\n"")",sort,easy 381,"Given an integer array arr of distinct integers and an integer k. A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game. It is guaranteed that there will be a winner of the game. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: arr = [2,1,3,5,4,6,7], k = 2 Output: 5 Example 2: Input: arr = [3,2,1], k = 10 Output: 3 Constraints: 2 <= arr.length <= @data 1 <= arr[i] <= 10^6 arr contains distinct integers. 1 <= k <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, arr, k): max_element = arr[0] for i in range(1, len(arr)): max_element = max(max_element, arr[i]) curr = arr[0] winstreak = 0 for i in range(1, len(arr)): opponent = arr[i] if curr > opponent: winstreak += 1 else: curr = opponent winstreak = 1 if winstreak == k or curr == max_element: return curr return -1 def solve2(self, arr, k): n = len(arr) max_val = arr[0] for i in range(1, n): if arr[i] > max_val: max_val = arr[i] streak = 0 while True: if arr[0] == max_val: return arr[0] if arr[0] > arr[1]: streak += 1 loser = arr.pop(1) arr.append(loser) if streak >= k: return arr[0] else: loser = arr.pop(0) arr.append(loser) streak = 1 if streak >= k: return arr[0] ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result) + ""\n"")",greedy,hard 382,"# Problem Statement Alice and Bob are playing a game. They have an array $a_1, a_2,\ldots,a_n$. The game consists of two steps: - First, Alice will remove **at most** $k$ elements from the array. - Second, Bob will multiply **at most** $x$ elements of the array by $-1$. Alice wants to maximize the sum of elements of the array while Bob wants to minimize it. Find the sum of elements of the array after the game if both players play optimally. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, x, a): pass # write your code here``` where: - `n` is the number of elements in the array, `k` is the maximum number of elements Alice can remove, and `x` is the maximum number of elements Bob can multiply by $-1$. - `a` is the array of elements. - The return value is the sum of elements of the array after the game. # Example 1: - Input: n = 4, k = 1, x = 1 a = [3, 1, 2, 4] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x,k \leq n$ - $1 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, k, x, a): a.sort() ans = -float('inf') prefix_sum = [0] * n if n > 0: prefix_sum[0] = a[0] for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + a[i] for i in range(k + 1): m = n - i sum_m = 0 if m > 0: sum_m = prefix_sum[m - 1] sum_m_minus_x = 0 if m - x > 0: sum_m_minus_x = prefix_sum[m - x - 1] res = -sum_m + 2 * sum_m_minus_x ans = max(ans, res) return ans def solve2(self, n, k, x, a): a.sort() if k > n: k = n s_total = 0 for v in a: s_total += v s_last_i = 0 s_tail_xi = 0 if x > 0: j = n - x while j < n: s_tail_xi += a[j] j += 1 ans = -10**18 i = 0 while i <= k: m = n - i sum_m = s_total - s_last_i if m - x > 0: sum_m_minus_x = s_total - s_tail_xi else: sum_m_minus_x = 0 res = -sum_m + 2 * sum_m_minus_x if res > ans: ans = res if i == k: break s_last_i += a[n - i - 1] if x + i < n: s_tail_xi += a[n - x - i - 1] i += 1 return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) x = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, x, a) sys.stdout.write(str(result) + ""\n"")","math,sort",medium 383,"# Problem Statement Stalin Sort is a humorous sorting algorithm designed to eliminate elements which are out of place instead of bothering to sort them properly, lending itself to an $\mathcal{O}(n)$ time complexity. It goes as follows: starting from the second element in the array, if it is strictly smaller than the previous element (ignoring those which have already been deleted), then delete it. Continue iterating through the array until it is sorted in non-decreasing order. For example, the array $[1, 4, 2, 3, 6, 5, 5, 7, 7]$ becomes $[1, 4, 6, 7, 7]$ after a Stalin Sort. We define an array as vulnerable if you can sort it in **non-increasing** order by repeatedly applying a Stalin Sort to **any of its subarrays$^{\text{∗}}$**, as many times as is needed. Given an array $a$ of $n$ integers, determine the minimum number of integers which must be removed from the array to make it vulnerable. $^{\text{∗}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - the return value is the minimum number of integers to be removed to make the array vulnerable # Example 1: - Input: n = 7 a = [3, 6, 4, 9, 2, 5, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math from typing import List class Solution: def solve1(self, n: int, a: List[int]) -> int: ans = n for i in range(n): res = 0 for j in range(n): if j < i or a[j] > a[i]: res += 1 ans = min(ans, res) return ans def solve2(self, n: int, a: List[int]) -> int: ans = n i = 0 while i < n: res = 0 j = 0 ai = a[i] while j < n: if j < i or a[j] > ai: res += 1 j += 1 if res < ans: ans = res i += 1 return ans","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",greedy,medium 384,"# Problem Statement There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li. You are given lengths of the claws. You need to find the total number of alive people after the bell rings. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the total number of alive people after the bell rings. # Example 1: - Input: n = 4 L = [0, 1, 0, 10] - Output: 1 # Constraints: - $1 \leq n \leq @data$ - $0 \leq L[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, L): for i in range(n - 1, 0, -1): L[i - 1] = max(L[i - 1], L[i] - 1) if n == 0: return 0 return 1 + L[1:].count(0) def solve2(self, n, L): count = 0 min_s = n + 1 for j in range(n - 1, -1, -1): if min_s > j: count += 1 s = j - L[j] if s < 0: s = 0 if s < min_s: min_s = s return count ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,implementation",medium 385,"# Problem Statement You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct. You are given a sequence of hits, the $i$-th hit deals $a_i$ units of damage to the opponent's character. To perform the $i$-th hit you have to press the button $s_i$ on your gamepad. Hits are numbered from $1$ to $n$. You know that if you press some button **more than** $k$ times **in a row** then it'll break. You cherish your gamepad and don't want to break any of its buttons. To perform a brutality you have to land some of the hits of the given sequence. **You are allowed to skip any of them, however changing the initial order of the sequence is prohibited**. The total damage dealt is the sum of $a_i$ over all $i$ for the hits which weren't skipped. **Note that if you skip the hit then the counter of consecutive presses the button won't reset**. Your task is to skip some hits to deal the **maximum** possible total damage to the opponent's character and not break your gamepad buttons. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a, s): pass # write your code here``` where: - return: he maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons. # Example 1: - Input: n = 7, k = 3 a = [1, 5, 16, 18, 7, 2, 10] s = ""baaaaca"" - Output: 54 # Constraints: - $1 \leq k \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - $s[i]$ is a lowercase Latin letter - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, k, a, s): ans = 0 start = 0 for i in range(1, n + 1): if i == n or s[i] != s[i - 1]: if i - start > k: a[start:i] = sorted(a[start:i]) count = min(k, i - start) for j in range(count): ans += a[i - 1 - j] start = i return ans def solve2(self, n, k, a, s): ans = 0 start = 0 i = 1 while i <= n: if i == n or s[i] != s[i - 1]: length = i - start cnt = k if k < length else length t = 0 while t < cnt: max_val = -1 idx = -1 j = start while j < i: if a[j] > max_val: max_val = a[j] idx = j j += 1 ans += max_val a[idx] = 0 t += 1 start = i i += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, k, a, s) sys.stdout.write(str(result) + ""\n"")","greedy,sort,two_pointers",hard 386,"# Problem Statement There are $M$ rows and $N$ columns of seats in a classroom. The seat in row $i$ and column $j$ is denoted by $(i, j)$. Some pairs of students may talk to each other during class. Each such pair occupies two adjacent seats. A passage placed between two adjacent rows or between two adjacent columns separates the corresponding seats, so students on the two sides of that passage will not talk to each other. You need to place $K$ horizontal passages between adjacent rows and $L$ vertical passages between adjacent columns so that the number of talking pairs that remain unseparated is minimized. The input guarantees that the optimal scheme is unique. The main function of the solution is defined as: ```python class Solution: def solve(self, m, n, k, l, d, seats): pass # write your code here``` where: - $M$ and $N$ are the numbers of rows and columns. - $K$ is the number of horizontal passages to place. - $L$ is the number of vertical passages to place. - $D$ is the number of talking pairs. - `seats[i] = [X_i, Y_i, P_i, Q_i]` means the students at $(X_i, Y_i)$ and $(P_i, Q_i)$ may talk to each other. - return: two arrays. The first array contains the $K$ row indices after which horizontal passages are placed. The second array contains the $L$ column indices after which vertical passages are placed. Both arrays should be in increasing order. # Example 1: - Input: M = 4, N = 5, K = 1, L = 2, D = 3 seats = [[4, 2, 4, 3], [2, 3, 3, 3], [2, 5, 2, 4]] - Output: [[2], [2, 4]] # Constraints: - $2 \leq M, N \leq @data$ - $2 \leq D \leq 3 * @data$ - $0 \leq K \leq M$ - $0 \leq L \leq N$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 100, 1000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: class A: def __init__(self, n=0, p=0): self.n = n self.p = p def solve(self, M, N, K, L, D, seats): row = [Solution.A(n=0, p=0) for _ in range(M + 1)] col = [Solution.A(n=0, p=0) for _ in range(N + 1)] row_divisions = [] col_divisions = [] for edge in seats: x1, y1, x2, y2 = edge[0], edge[1], edge[2], edge[3] if x1 == x2: idx = min(y1, y2) col[idx].p = idx col[idx].n += 1 else: idx = min(x1, x2) row[idx].p = idx row[idx].n += 1 row_slice = row[1 : M + 1] row_slice.sort(key=lambda x: (-x.n, x.p)) row[1 : M + 1] = row_slice col_slice = col[1 : N + 1] col_slice.sort(key=lambda x: (-x.n, x.p)) col[1 : N + 1] = col_slice row_top_k_slice = row[1 : K + 1] row_top_k_slice.sort(key=lambda x: x.p) row[1 : K + 1] = row_top_k_slice col_top_l_slice = col[1 : L + 1] col_top_l_slice.sort(key=lambda x: x.p) col[1 : L + 1] = col_top_l_slice for i in range(1, K + 1): row_divisions.append(row[i].p) for i in range(1, L + 1): col_divisions.append(col[i].p) return [row_divisions, col_divisions] ","import sys data = sys.stdin.buffer.read().split() it = iter(data) m = int(next(it)) n = int(next(it)) k = int(next(it)) l = int(next(it)) d = int(next(it)) seats = [] for i in range(1, d + 1): temp = [] for j in range(1, 4 + 1): x = int(next(it)) temp.append(x) seats.append(temp) solution = Solution() result = solution.solve(m, n, k, l, d, seats) out_lines = [] first = result[0] for i in range(0, len(first)): sys.stdout.write(str(first[i])) if i == len(first) - 1: sys.stdout.write(""\n"") else: sys.stdout.write("" "") second = result[1] for i in range(0, len(second)): sys.stdout.write(str(second[i])) if i == len(second) - 1: pass else: sys.stdout.write("" "")","sort,greedy",hard 387,"n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: Take their own seat if it is still available, and Pick other seats randomly when they find their seat occupied Return the probability that the nth person gets his own seat. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 1 Output: 1.000 Example 2: Input: n = 2 Output: 0.500 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[1000, 10000, 1000000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, n): return 1.0 if n == 1 else 0.5 def solve2(self, n): if n == 1: return 1.0 s = 0.0 f = 0.0 i = 2 while i <= n: f = (1.0 + s) / i s += f i += 1 return f ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(""{:.3f}"".format(result))",math,medium 388,"A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original of length n. Specifically, for each index i in the range [0, n - 1]: If i = n - 1, then derived[i] = original[i] ⊕ original[0]. Otherwise, derived[i] = original[i] ⊕ original[i + 1]. Given an array derived, your task is to determine whether there exists a valid binary array original that could have formed derived. Return 1 if such an array exists and 0 otherwise. A binary array is an array containing only 0's and 1's solution main function ```python class Solution: def solve(self, num): pass # write your code here``` Example 1: Input: derived = [1,1,0] Output: 1 Example 2: Input: derived = [1,1] Output: 1 Constraints: n == derived.length 2 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math import collections class Solution: def solve1(self, derived): s = sum(derived) return 1 if s % 2 == 0 else 0 def solve2(self, derived): n = len(derived) for start in (0, 1): prev = start i = 0 while i < n - 1: prev ^= derived[i] i += 1 if (prev ^ start) == derived[n - 1]: return 1 return 0 ","import sys data = sys.stdin.read().split() it = iter(data) # input n = int(next(it)) num = [] i = 1 while i <= n: x = int(next(it)) num.append(x) i += 1 # solve solution = Solution() result = solution.solve(num) # output sys.stdout.write(str(result) + ""\n"")",bit_manipulation,medium 389,"# Problem Statement There is a shop with $n$ objects numbered from $1$ to $n$, and only one copy of each object. According to you, the objects have values $v_1, v_2, \dots, v_n$ (values can be negative). Alice and Bob have their own preference orders (permutations $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$). In particular, Alice's favourite object is $a_1$, then $a_2$, etc.; Bob's favourite object is $b_1$, then $b_2$, etc. For $n$ turns, one of them goes to the shop and buys his or her most favourite object still in the shop. At the end, Alice and Bob have their own sets of objects. Now the shop is empty, and you wonder whether Alice's preferences are similar to yours. Over all sets of objects that Alice could have bought, what is the maximum possible sum of values according to you? The main function of the solution is defined as: ```python class Solution: def solve(self, n, v, a, b): pass # write your code here``` where: - `n`: number of objects - `v`: values of the objects (can be negative) - `a`: Alice's preference permutation - `b`: Bob's preference permutation - return: the maximum possible total value of the set that Alice could have bought # Example: - Input: ``` n = 3 v = [1, -1, 1] a = [3, 1, 2] b = [2, 3, 1] ``` - Output: ``` 2 ``` # Constraints: - $1 \le n \le @data$ - $-10^9 \le v[i] \le 10^9$ - $1 \le a[i], b[i] \le n$ (both are permutations) - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 250, 64], [4000, 2000, 400], [32000, 16000, 3200]]","import sys class Solution: def solve1(self, n, v, a, b): if n > 1500: try: sys.setrecursionlimit(max(sys.getrecursionlimit(), n * 4)) except (ValueError, RuntimeError): pass for i in range(n): a[i] -= 1 c = list(b) for i in range(n): b[c[i] - 1] = i b_inv = b tree = [0] * (4 * n) def update(node, start, end, idx, val): if start == end: tree[node] += val return mid = (start + end) // 2 if start <= idx <= mid: update(2 * node, start, mid, idx, val) else: update(2 * node + 1, mid + 1, end, idx, val) tree[node] = tree[2 * node] + tree[2 * node + 1] def consume(node, start, end, l, r, debt): if debt <= 0 or tree[node] == 0 or start > r or end < l: return debt if start == end: paid = min(debt, tree[node]) tree[node] -= paid return debt - paid mid = (start + end) // 2 remaining_debt = debt if l <= mid: remaining_debt = consume(2 * node, start, mid, l, r, remaining_debt) if remaining_debt > 0 and r > mid: remaining_debt = consume(2 * node + 1, mid + 1, end, l, r, remaining_debt) tree[node] = tree[2 * node] + tree[2 * node + 1] return remaining_debt ans = 0 for x in range(n): item = a[x] item_val = v[item] y = b_inv[item] ans += item_val neg_item_val = -item_val if neg_item_val < 0: debt = item_val if y < n: consume(1, 0, n - 1, y, n - 1, debt) else: credit = neg_item_val if credit > 0: update(1, 0, n - 1, y, credit) ans += tree[1] return ans def solve2(self, n, v, a, b): for i in range(n): a[i] -= 1 b[i] -= 1 NEG_BASE = -(1 << 60) THRESH = NEG_BASE // 2 ans = 0 for x in range(n): item = a[x] item_val = v[item] y = 0 while y < n and b[y] != item: y += 1 ans += item_val if item_val > 0: debt = item_val pos = y while pos < n and debt > 0: j = b[pos] valj = v[j] if valj <= THRESH: credit_left = valj - NEG_BASE if credit_left > 0: take = credit_left if credit_left < debt else debt v[j] = valj - take debt -= take pos += 1 elif item_val < 0: v[item] = NEG_BASE + (-item_val) rem = 0 for j in range(n): valj = v[j] if valj <= THRESH: credit_left = valj - NEG_BASE if credit_left > 0: rem += credit_left return ans + rem ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) v = [0] * n for i in range(n): v[i] = int(next(it)) a = [0] * n b = [0] * n for i in range(n): a[i] = int(next(it)) for i in range(n): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, v, a, b) sys.stdout.write(str(result) + ""\n"")","greedy,data_structures",hard 390,"# Problem Statement An array $b$ of length $m$ is good if for all $i$ the $i$-th element is greater than or equal to $i$. In other words, $b$ is good if and only if $b_i \geq i$ for all $i$ ($1 \leq i \leq m$). You are given an array $a$ consisting of $n$ positive integers. Find the number of pairs of indices $(l, r)$, where $1 \le l \le r \le n$, such that the array $[a_l, a_{l+1}, \ldots, a_r]$ is good. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of suitable pairs of indices, please use `long long` type. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): result = 0 l = 0 for r in range(n): while l <= r and a[r] < (r - l + 1): l += 1 result += (r - l + 1) return result def solve2(self, n, a): result = 0 for l in range(n): need = 1 for r in range(l, n): if a[r] >= need: result += 1 need += 1 else: break return result ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","two_pointers,binary",medium 391,"Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < n and n % x == 0. Replacing the number n on the chalkboard with n - x. Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally. In examples, the returned boolean is shown as `1` for true and `0` for false. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 2 Output: 1 Example 2: Input: n = 3 Output: 0 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, n: int) -> bool: return n % 2 == 0 def solve2(self, n: int) -> bool: return n % 2 == 0 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(""1"" if result else ""0"")","math,other",easy 392,"Given a 0-indexed string s, permute s to get a new string t such that: All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i]. The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j]. Return the resulting string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""lEetcOde"" Output: ""lEOtcede"" Example 2: Input: s = ""lYmpH"" Output: ""lYmpH"" Constraints: 1 <= s.length <= @data s consists only of letters of the English alphabet in uppercase and lowercase. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 160], [32000, 3200, 1280]]","import collections class Solution: def isVowel(self, c): return c == 'a' or c == 'e' or c == 'o' or c == 'u' or c == 'i'\ or c == 'A' or c == 'E' or c == 'O' or c == 'U' or c == 'I' def solve1(self, s): count = collections.Counter() for c in s: if self.isVowel(c): count[c] += 1 sortedVowel = ""AEIOUaeiou"" ans = [] j = 0 for i in range(len(s)): if not self.isVowel(s[i]): ans.append(s[i]) else: while count[sortedVowel[j]] == 0: j += 1 ans.append(sortedVowel[j]) count[sortedVowel[j]] -= 1 return """".join(ans) def solve2(self, s): order = ""AEIOUaeiou"" cnt = [0] * len(order) for c in s: idx = order.find(c) if idx != -1: cnt[idx] += 1 res = [] j = 0 for c in s: if order.find(c) == -1: res.append(c) else: while j < len(order) and cnt[j] == 0: j += 1 res.append(order[j]) cnt[j] -= 1 return """".join(res) ","import sys def main(): data = sys.stdin.read().split() if len(data) == 0: s = """" else: s = data[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","sort,string",easy 393,"# Problem Statement A subarray is a continuous part of array. Yarik recently found an array $a$ of $n$ elements and became very interested in finding the maximum sum of a **non empty** subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjacent elements. For example, $[1, 2, 3]$ is acceptable, but $[1, 2, 4]$ is not, as $2$ and $4$ are both even and adjacent. You need to help Yarik by finding the maximum sum of such a subarray. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum sum of the subarray # Example 1: - Input: n = 5 a = [1, 2, 3, 4, 5] - Output: 15 # Constraints: - $1 \leq n \leq @data$ - $-10^3 \leq a[i] \leq 10^3$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = -float('inf') suf = -float('inf') for i in range(n): if i and (a[i] - a[i - 1]) % 2 == 0: suf = 0 suf = max(suf, 0) + a[i] ans = max(ans, suf) return ans def solve2(self, n, a): ans = a[0] for i in range(n): s = 0 for j in range(i, n): if j > i and (a[j] - a[j - 1]) % 2 == 0: break s += a[j] if s > ans: ans = s return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,two_pointers,dp",hard 394,"Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold. solution main function ```python class Solution: def solve(self, s, k, sum_val): pass # write your code here``` Example 1: Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 Output: 3 Example 2: Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 Output: 6 Constraints: 1 <= arr.length <= @data 1 <= arr[i] <= 10^4 1 <= k <= arr.length 0 <= threshold <= 10^4 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve1(self, arr, k, threshold): n = len(arr) count = 0 prefixsum = 0 l = 0 r = 0 while r < n: prefixsum += arr[r] if r - l + 1 == k: if prefixsum // k >= threshold: count += 1 prefixsum -= arr[l] l += 1 r += 1 return count def solve2(self, arr, k, threshold): n = len(arr) if k > n or k <= 0: return 0 target = threshold * k count = 0 for i in range(n - k + 1): s = 0 for j in range(i, i + k): s += arr[j] if s >= target: count += 1 return count ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) sum_val = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, k, sum_val) sys.stdout.write(str(result))",other,medium 395,"# Problem Statement Consider a binary string of length `n` and an odd number `k` (3 ≤ k ≤ n). We call a binary string good if for every substring of length `k`, the leftmost character of the substring occurs more times than the other character. You are given a pattern string of length `n` consisting of characters `0`, `1` and `?`. Count the number of ways to replace each `?` with `0` or `1` so that the resulting string is good. Return the answer modulo `998244353`. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, s): pass # write your code here``` where: - `n`: length of the string - `k`: odd window length (3 ≤ k ≤ n) - `s`: the pattern consisting of `0`, `1`, and `?` - return: the number of valid fillings modulo `998244353` # Example 1: - Input: n = 5 k = 3 s = ""0??0?"" - Output: 3 - Explanation: Valid fillings include ""00000"", ""00001"", and ""00101"". # Constraints: - $1 \leq n \leq @data$ - $3 \leq k \leq n$, and `k` is odd - `s` consists only of `0`, `1`, `?` - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 250, 100], [4000, 2000, 800], [32000, 16000, 6400]]","import sys class Solution: def solve1(self, n, k, s): MOD = 998244353 fact = [1] * (n + 1) ifact = [1] * (n + 1) for i in range(1, n + 1): fact[i] = (fact[i - 1] * i) % MOD ifact[n] = pow(fact[n], MOD - 2, MOD) for i in range(n, 0, -1): ifact[i - 1] = (ifact[i] * i) % MOD def C(a, b): if b < 0 or b > a: return 0 num = fact[a] den = (ifact[b] * ifact[a - b]) % MOD return (num * den) % MOD def calc(str_arg): ans = 0 m = k - 1 v1 = n + 1 for i in range(n): if str_arg[i] == '1': v1 = i break p0 = 0 p1 = 0 for i in range(n - k + 1, n): if i >= 0 and i < n: if str_arg[i] == '0': p0 += 1 elif str_arg[i] == '1': p1 += 1 if v1 > n - k: for c1 in range(m // 2, m + 1): if c1 >= p0 and m - c1 >= p1: ans = (ans + C(m - p0 - p1, c1 - p0)) % MOD ps = [0] * m for i in range(n - k + 1, n): if i >= 0 and i < n: if str_arg[i] == '0': ps[i % m] |= 1 elif str_arg[i] == '1': ps[i % m] |= 2 p0 = 0 p1 = 0 for r in range(m): if ps[r] == 1: p0 += 1 elif ps[r] == 2: p1 += 1 for i in range(n - k - 1, -1, -1): cls = (i + 1) % m if ps[cls] == 0: if str_arg[i + 1] == '0': ps[cls] |= 1 p0 += 1 elif str_arg[i + 1] == '1': ps[cls] |= 2 p1 += 1 else: if str_arg[i + 1] == '0': ps[cls] |= 1 elif str_arg[i + 1] == '1': ps[cls] |= 2 if ps[cls] == 3: break if v1 > i and ps[cls] != 1: free_classes = m - p0 - p1 if ps[cls] == 0: ans = (ans + C(free_classes - 1, m // 2 - p0)) % MOD else: ans = (ans + C(free_classes, m // 2 - p0)) % MOD return ans t = list(s) ans = calc(t) t = list(s) for i in range(len(t)): if t[i] == '0': t[i] = '1' elif t[i] == '1': t[i] = '0' ans += calc(t) if ans >= MOD: ans -= MOD return ans def solve2(self, n, k, s): MOD = 998244353 q = 0 i = 0 while i < n: if s[i] == '?': q += 1 i += 1 ans = 0 total = 1 << q mask = 0 while mask < total: ok = True qbefore = 0 i = 0 while i <= n - k: ch_i = s[i] if ch_i == '?': c = '1' if ((mask >> qbefore) & 1) else '0' qcnt = qbefore + 1 else: c = ch_i qcnt = qbefore cnt = 1 p = i + 1 end = i + k while p < end: chp = s[p] if chp == '?': cp = '1' if ((mask >> qcnt) & 1) else '0' qcnt += 1 else: cp = chp if cp == c: cnt += 1 p += 1 if cnt <= (k // 2): ok = False break if s[i] == '?': qbefore += 1 i += 1 if ok: ans += 1 if ans >= MOD: ans -= MOD mask += 1 return ans % MOD ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, k, s) sys.stdout.write(str(result) + ""\n"")","string,math",hard 396,"# Problem Statement ErnKor is ready to do anything for Julen, even to swim through crocodile-infested swamps. We decided to test this love. ErnKor will have to swim across a river with a width of $1$ meter and a length of $n$ meters. The river is very cold. Therefore, **in total** (that is, throughout the entire swim from $0$ to $n+1$) ErnKor can swim in the water for no more than $k$ meters. For the sake of humanity, we have added not only crocodiles to the river, but also logs on which he can jump. Our test is as follows: Initially, ErnKor is on the left bank and needs to reach the right bank. They are located at the $0$ and $n+1$ meters respectively. The river can be represented as $n$ segments, each with a length of $1$ meter. Each segment contains either a log 'L', a crocodile 'C', or just water 'W'. ErnKor can move as follows: - If he is on the surface (i.e., on the bank or on a log), he can jump forward for no more than $m$ ($1 \le m \le 10$) meters (he can jump on the bank, on a log, or in the water). - If he is in the water, he can only swim to the next river segment (or to the bank if he is at the $n$-th meter). - ErnKor cannot land in a segment with a crocodile in any way. Determine if ErnKor can reach the right bank. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k, a): pass # write your code here``` where: - return ""YES"" if ErnKor can pass the test, and return ""NO"" otherwise. # Example 1: - Input: n = 6, m = 2, k = 0 a = ""LWLLLW"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - $0 \leq k \leq @data$ - $1 \leq m \leq 10$ - $a[i] \in \{ 'L', 'W', 'C' \}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, m, k, a): x = -1 for i in range(n + 1): if x >= 0 and a[x] == 'W': x = i k -= 1 elif i == n or a[i] == 'L' or i - x == m: x = i if x >= 0 and x < n and a[x] == 'C': return ""NO"" return ""YES"" if k >= 0 else ""NO"" def solve2(self, n, m, k, a): pos = 0 while True: if n + 1 - pos <= m: return ""YES"" end = pos + m if end > n: end = n j = end while j > pos and a[j - 1] != 'L': j -= 1 if j > pos and a[j - 1] == 'L': pos = j continue s = end while s > pos and a[s - 1] != 'W': s -= 1 if s <= pos: return ""NO"" t = s while t <= n and a[t - 1] == 'W': t += 1 water_used = t - s k -= water_used if k < 0: return ""NO"" if t <= n: if a[t - 1] == 'C': return ""NO"" pos = t continue return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) a = next(it) solution = Solution() result = solution.solve(n, m, k, a) sys.stdout.write(str(result) + ""\n"")","dp,greedy",hard 397,"# Problem Statement You received an $n\times m$ grid from a mysterious source. The source also gave you a magic positive integer constant $k$. The source told you to color the grid with some colors, satisfying the following condition: - If $(x_1,y_1)$, $(x_2,y_2)$ are two distinct cells with the same color, then $\max(|x_1-x_2|,|y_1-y_2|)\ge k$. You don't like using too many colors. Please find the minimum number of colors needed to color the grid. The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, k): pass # write your code here``` where: - return: the minimum number of colors needed to color the grid. # Example 1: - Input: n = 3, m = 3, k = 2 - Output: 4 # Constraints: - $1 \leq n, m \leq @data$ - $1 \leq k \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, m, k): return min(n, k) * min(m, k) def solve2(self, n, m, k): return min(n, k) * min(m, k) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, m, k) sys.stdout.write(str(result) + ""\n"")",constructive_algorithms,easy 398,"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. solution main function ```python class Solution: def solve(self, n, k): pass # write your code here``` Example 1: Input: n = 1, k = 3 Output: ""c"" Example 2: Input: n = 1, k = 4 Output: """" Constraints: 1 <= n <= @data 1 <= k <= 100 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","class Solution: def solve1(self, n, k): if n <= 0 or k <= 0: return """" def bounded_pow2(remaining: int, limit: int) -> int: cnt = 1 for _ in range(remaining): cnt <<= 1 if cnt >= limit: return limit return cnt result_chars = [] prev = '' for pos in range(n): remaining = n - pos - 1 for ch in ['a', 'b', 'c']: if ch == prev: continue cnt = bounded_pow2(remaining, k) if k > cnt: k -= cnt else: result_chars.append(ch) prev = ch break else: return """" return """".join(result_chars) def solve2(self, n, k): if n <= 0 or k <= 0: return """" buf = [''] * n buf[0] = 'a' for i in range(1, n): p = buf[i - 1] buf[i] = 'a' if p != 'a' else 'b' k -= 1 if k == 0: return """".join(buf) while True: i = n - 1 while i >= 0: prev = buf[i - 1] if i > 0 else None c = buf[i] nxt = None if c == 'a': if prev != 'b': nxt = 'b' elif prev != 'c': nxt = 'c' elif c == 'b': if prev != 'c': nxt = 'c' if nxt is not None: buf[i] = nxt j = i + 1 while j < n: p = buf[j - 1] buf[j] = 'a' if p != 'a' else 'b' j += 1 break else: i -= 1 if i < 0: return """" k -= 1 if k == 0: return """".join(buf) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, k) sys.stdout.write(str(result))","math,search,string",medium 399,"# Problem Statement Mushroom Filippov cooked himself a meal and while having his lunch, he decided to watch a video on TubeTube. He can not spend more than $t$ seconds for lunch, so he asks you for help with the selection of video. The TubeTube feed is a list of $n$ videos, indexed from $1$ to $n$. The $i$-th video lasts $a_i$ seconds and has an entertainment value $b_i$. Initially, the feed is opened on the first video, and Mushroom can skip to the next video in $1$ second (if the next video exists). Mushroom can skip videos any number of times (including zero). Help Mushroom choose **one** video that he can open and watch in $t$ seconds. Choose a feasible video with the maximum entertainment value. If several feasible videos have the same maximum entertainment value, return the smallest index among them. Return $-1$ if there is no such video. The main function of the solution is defined as: ```python class Solution: def solve(self, n, t, a, b): pass # write your code here``` where: - `n` is the number of videos - `t` is the lunch time - `a` is the duration of the videos - `b` is the entertainment value of the videos # Example 1: - Input: n = 5 t = 9 a = [1, 5, 7, 6, 6] b = [3, 4, 7, 1, 9] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i], b[i], t \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math import sys class Solution: def solve1(self, n, t, a, b): x = -2 for i in range(n): if a[i] + i <= t: if x == -2 or b[x] < b[i]: x = i return x + 1 def solve2(self, n, t, a, b): best_idx = -1 best_val = -1 for i in range(n): if a[i] + i <= t: if b[i] > best_val: best_val = b[i] best_idx = i if best_idx == -1: return -1 return best_idx + 1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) t = int(next(it)) a = [0] * n b = [0] * n for i in range(n): a[i] = int(next(it)) for i in range(n): b[i] = int(next(it)) solution = Solution() result = solution.solve(n, t, a, b) sys.stdout.write(str(result) + ""\n"")",greedy,easy 400,"We define the conversion array conver of an array arr as follows: conver[i] = arr[i] + max(arr[0..i]) where max(arr[0..i]) is the maximum value of arr[j] over 0 <= j <= i. We also define the score of an array arr as the sum of the values of the conversion array of arr. Given a 0-indexed integer array nums of length n, return an array ans of length n where ans[i] is the score of the prefix nums[0..i]. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [2,3,7,5,10] Output: [4,10,24,36,56] Example 2: Input: nums = [1,1,2,4,8,16] Output: [2,4,8,16,32,64] Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= 10^9 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import math class Solution: def solve1(self, nums): if not nums: return [] result = [0] * len(nums) max_num = nums[0] result[0] = nums[0] * 2 for i in range(1, len(nums)): max_num = max(max_num, nums[i]) result[i] = nums[i] + max_num + result[i-1] return result def solve2(self, nums): n = len(nums) if n == 0: return [] res = [0] * n for i in range(n): running_max = nums[0] s = nums[0] + running_max for k in range(1, i + 1): if nums[k] > running_max: running_max = nums[k] s += nums[k] + running_max res[i] = s return res ","import sys data = iter(sys.stdin.read().split()) def next_token(): return next(data) n = int(next_token()) s = [] for i in range(1, n + 1): x = int(next_token()) s.append(x) solution = Solution() result = solution.solve(s) out = [] for it in result: out.append(str(it)) out.append(' ') sys.stdout.write(''.join(out))",other,medium 401,"# Problem Statement You have a horizontal strip of $n$ cells. Each cell is either white or black. You can choose a **continuous** segment of cells once and paint them all white. After this action, all the black cells in this segment will become white, and the white ones will remain white. What is the minimum length of the segment that needs to be painted white in order for all $n$ cells to become white? The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return: the minimum length of a continuous segment of cells that needs to be painted white in order for the entire strip to become white. # Example 1: - Input: n = 6 s = ""WBBWBW"" - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $s[i] \in \{'W', 'B'\}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, s): l = 0 r = n - 1 while l < n and s[l] == 'W': l += 1 while r >= 0 and s[r] == 'W': r -= 1 if l > r: return 0 ans = r - l + 1 return ans def solve2(self, n, s): first = -1 last = -1 for i in range(n): if s[i] == 'B': if first == -1: first = i last = i if first == -1: return 0 return last - first + 1 ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","greedy,string",easy 402,"There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. solution main function ```python class Solution: def solve(self, n, e): pass # write your code here``` Example 1: Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] Output: [8,12,6,10,10,10] Example 2: Input: n = 1, edges = [] Output: [0] Constraints: 1 <= n <= @data edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: res: int def dfs(self, cur: int, par: int, adj: list[list[int]], cnt: list[int], lvl: int) -> int: sum_val = 0 self.res += lvl for child in adj[cur]: if child != par: sum_val += self.dfs(child, cur, adj, cnt, lvl + 1) cnt[cur] = sum_val + 1 return sum_val + 1 def solve1(self, n: int, edges: list[list[int]]) -> list[int]: adj = [[] for _ in range(n)] for i in range(n - 1): u = edges[i][0] v = edges[i][1] adj[u].append(v) adj[v].append(u) cnt = [0] * n self.res = 0 total = self.dfs(0, -1, adj, cnt, 0) par = [0] * n if n > 0: par[0] = self.res q = collections.deque() if n > 0: q.append(0) while q: cur = q.popleft() for child in adj[cur]: if par[child] == 0: par[child] = par[cur] - cnt[child] + (total - cnt[child]) q.append(child) return par def solve2(self, n: int, edges: list[list[int]]) -> list[int]: ans = [0] * n for src in range(n): frontier = 1 << src visited = frontier count = 1 level = 0 s = 0 while count < n: next_frontier = 0 for u, v in edges: if ((frontier >> u) & 1) and not ((visited >> v) & 1): next_frontier |= (1 << v) if ((frontier >> v) & 1) and not ((visited >> u) & 1): next_frontier |= (1 << u) if next_frontier == 0: break level += 1 sz = next_frontier.bit_count() s += level * sz visited |= next_frontier count += sz frontier = next_frontier ans[src] = s return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) e = [] for i in range(1, n): x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) e.append(temp) solution = Solution() result = solution.solve(n, e) out = [] for v in result: out.append(str(v)) sys.stdout.write("" "".join(out))","graph,dynamic_programming,search",hard 403,"You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: The first element in s[k] starts with the selection of the element nums[k] of index = k. The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. We stop adding right before a duplicate element occurs in s[k]. Return the longest length of a set s[k]. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: nums = [5,4,0,3,1,6,2] Output: 4 Example 2: Input: nums = [0,1,2] Output: 1 Constraints: 1 <= nums.length <= @data 0 <= nums[i] < nums.length All the values of nums are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, nums): ans = 0 for x in list(nums): if x == -1: continue cnt = 0 while nums[x] != -1: cnt += 1 prev = x x = nums[x] nums[prev] = -1 ans = max(ans, cnt) return ans def solve2(self, nums): n = len(nums) ans = 0 for i in range(n): x = nums[i] if x == -1: continue cnt = 0 while nums[x] != -1: cnt += 1 nx = nums[x] nums[x] = -1 x = nx if cnt > ans: ans = cnt return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")",search,easy 404,"# Problem Statement To train young Kevin's arithmetic skills, his mother devised the following problem. Given $n$ integers $a_1, a_2, \ldots, a_n$ and a sum $s$ initialized to $0$, Kevin performs the following operation for $i = 1, 2, \ldots, n$ in order: - Add $a_i$ to $s$. If the resulting $s$ is even, Kevin earns a point and repeatedly divides $s$ by $2$ until it becomes odd. Note that Kevin can earn at most one point per operation, regardless of how many divisions he does. Since these divisions are considered more beneficial for Kevin's development, his mother wants to rearrange $a$ so that the number of Kevin's total points is maximized. Determine the maximum number of points. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - returns the maximum number of points. # Example 1: - Input: n = 2, a = [1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): odd = 0 for i in range(n): odd += a[i] % 2 return min(n - 1, odd) + min(1, n - odd) def solve2(self, n, a): odd = 0 for i in range(n): odd += a[i] & 1 return min(n - 1, odd) + min(1, n - odd) ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,easy 405,"Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way. solution main function ```python class Solution: def solve(self, s, k): pass # write your code here``` Example 1: Input: nums = [4,2,3], k = 1 Output: 5 Example 2: Input: nums = [3,-1,0,2], k = 3 Output: 6 Constraints: 1 <= nums.length <= @data -100 <= nums[i] <= 100 1 <= k <= 10^4 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math class Solution: def solve1(self, nums, k): nums.sort() n = len(nums) for i in range(n): if k and nums[i] < 0: nums[i] = -1 * nums[i] k -= 1 mini = float('inf') total_sum = 0 for i in range(n): mini = min(mini, nums[i]) total_sum += nums[i] k = k % 2 if mini > 0 and k: total_sum -= 2 * mini if mini < 0 and k: total_sum += -2 * mini return total_sum def solve2(self, nums, k): n = len(nums) while k > 0: idx = 0 mn = nums[0] for i in range(1, n): v = nums[i] if v < mn: mn = v idx = i nums[idx] = -nums[idx] k -= 1 if mn == 0: break total = 0 for v in nums: total += v return total ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) k = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s, k) sys.stdout.write(str(result))","greedy,sort,other",easy 406,"You are given an array nums consisting of positive integers. Return the total frequencies of elements in nums such that those elements all have the maximum frequency. The frequency of an element is the number of occurrences of that element in the array. solution main function ```python class Solution: def solve(self, a): pass # write your code here``` Example 1: Input: nums = [1,2,2,3,1,4] Output: 4 Example 2: Input: nums = [1,2,3,4,5] Output: 5 Constraints: 1 <= nums.length <= @data 1 <= nums[i] <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","import collections class Solution: def solve1(self, nums): frequencies = collections.defaultdict(int) max_frequency = 0 total_frequencies = 0 for num in nums: frequencies[num] += 1 frequency = frequencies[num] if frequency > max_frequency: max_frequency = frequency total_frequencies = frequency elif frequency == max_frequency: total_frequencies += frequency return total_frequencies def solve2(self, nums): n = len(nums) max_freq = 0 for i in range(n): seen_before = False for k in range(i): if nums[k] == nums[i]: seen_before = True break if seen_before: continue cnt = 0 for j in range(n): if nums[j] == nums[i]: cnt += 1 if cnt > max_freq: max_freq = cnt total = 0 for i in range(n): seen_before = False for k in range(i): if nums[k] == nums[i]: seen_before = True break if seen_before: continue cnt = 0 for j in range(n): if nums[j] == nums[i]: cnt += 1 if cnt == max_freq: total += cnt return total ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [] for i in range(1, n + 1): x = int(next(it)) a.append(x) solution = Solution() result = solution.solve(a) sys.stdout.write(str(result) + ""\n"")",math,easy 407,"# Problem Statement You are given a string $s$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $s$ such that it contains each of these three characters at least once. A contiguous substring of string $s$ is a string that can be obtained from $s$ by removing some (possibly zero) characters from the beginning of $s$ and some (possibly zero) characters from the end of $s$. The main function of the solution is defined as: ```python class Solution: def solve(self, s): pass # write your code here``` where: - return: the length of the shortest contiguous substring of s containing all three types of characters at least once. If there is no such substring, return 0 instead. # Example 1: - Input: s = ""123"" - Output: 3 # Constraints: - $1 \leq s.length \leq @data$ - $s[i] \in \{1, 2, 3\}$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s): n = len(s) ans = n + 1 cnt = [0, 0, 0] j = 0 for i in range(n): while cnt[0] == 0 or cnt[1] == 0 or cnt[2] == 0: if j >= n: break cnt[int(s[j]) - 1] += 1 j += 1 if cnt[0] == 0 or cnt[1] == 0 or cnt[2] == 0: break ans = min(ans, j - i) cnt[int(s[i]) - 1] -= 1 if ans > n: return 0 else: return ans def solve2(self, s): n = len(s) ans = n + 1 for i in range(n): seen1 = 0 seen2 = 0 seen3 = 0 for j in range(i, n): c = s[j] if c == '1': seen1 = 1 elif c == '2': seen2 = 1 elif c == '3': seen3 = 1 if seen1 and seen2 and seen3: length = j - i + 1 if length < ans: ans = length break if ans == 3: return 3 if ans == n + 1: return 0 return ans ","import sys def main(): s = sys.stdin.readline().strip() solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","binary,dp,two_pointers",easy 408,"# Problem Statement You have an array of **zeros** $a_1, a_2, \ldots, a_n$ of length $n$. You can perform two types of operations on it: 1. Choose an index $i$ such that $1 \le i \le n$ and $a_i = 0$, and assign $1$ to $a_i$; 2. Choose a pair of indices $l$ and $r$ such that $1 \le l \le r \le n$, $a_l = 1$, $a_r = 1$, $a_l + \ldots + a_r \ge \lceil\frac{r - l + 1}{2}\rceil$, and assign $1$ to $a_i$ for all $l \le i \le r$. What is the minimum number of operations of the **first type** needed to make all elements of the array equal to one? The main function of the solution is defined as: ```python class Solution: def solve(self, n): pass # write your code here``` where: - return:the minimum number of needed operations of first type. # Example 1: - Input: n = 1 - Output: 1 # Constraints: - $1 \leq n \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n): ans = 1 k = 1 while k < n: k = (k + 1) * 2 ans += 1 return ans def solve2(self, n): ans = 1 k = 1 while k < n: k = (k + 1) * 2 ans += 1 return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result) + ""\n"")","constructive_algorithms,math",easy 409,"Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, return the number of the beautiful arrangements that you can construct. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 2 Output: 2 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[5, 10, 15]",4000,"[[1000, 100, 64], [8000, 800, 80], [64000, 6400, 640]]","import collections class Solution: def solve1(self, n: int) -> int: self.check = [False] * 16 self.ans = 0 self.dfs(1, n) return self.ans def solve2(self, n: int) -> int: B = n + 1 pos = 1 P = 1 S = 0 mask = 0 ans = 0 while True: if pos == n + 1: ans += 1 pos -= 1 if pos == 0: break P //= B d = (S // P) % B last = d if last >= 1: mask &= ~(1 << last) else: d = (S // P) % B start = d + 1 found = 0 for i in range(start, n + 1): if ((mask >> i) & 1) == 0 and (i % pos == 0 or pos % i == 0): found = i break if found: mask |= 1 << found newd = found if found < B - 1 else B - 1 S += (newd - d) * P pos += 1 P *= B d2 = (S // P) % B if d2 != 0: S += (0 - d2) * P else: if d != 0: S += (0 - d) * P pos -= 1 if pos == 0: break P //= B dprev = (S // P) % B last = dprev if last >= 1: mask &= ~(1 << last) return ans def dfs(self, pos: int, n: int): if pos == n + 1: self.ans += 1 return for i in range(1, n + 1): if not self.check[i] and (pos % i == 0 or i % pos == 0): self.check[i] = True self.dfs(pos + 1, n) self.check[i] = False ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",dp,easy 410,"There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: heights = [10,6,8,5,11,9] Output: [3,1,2,1,1,0] Example 2: Input: heights = [5,1,2,3,10] Output: [4,1,1,1,0] Constraints: n == heights.length 1 <= n <= @data 1 <= heights[i] <= @data All the values of heights are unique. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[6250, 3125, 1562], [50000, 25000, 12500], [400000, 200000, 100000]]","import collections class Solution: def solve(self, A): n = len(A) res = [0] * n stack = [] for i in range(n): while stack and A[stack[-1]] <= A[i]: res[stack[-1]] += 1 stack.pop() if stack: res[stack[-1]] += 1 stack.append(i) return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) s = [] for i in range(1, n + 1): x = int(next(it)) s.append(x) solution = Solution() result = solution.solve(s) out = [] for v in result: out.append(str(v)) if out: sys.stdout.write("" "".join(out))",data_structures,hard 411,"# Problem Statement Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements **isn't** divisible by $x$, or determine that such subarray doesn't exist. An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. The main function of the solution is defined as: ```python class Solution: def solve(self, n, x, a): pass # write your code here``` where: - return the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, return −1. # Example 1: - Input: n = 3, x = 3 a = [1,2,3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq x, a[i] \leq 10^4$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, x, a): u = -1 v = -1 ans = -1 current_sum = 0 for i in range(n): current_sum = (current_sum + a[i]) % x if current_sum != 0: ans = max(ans, i + 1) if u != -1 and current_sum != u: ans = max(ans, i + 1 - v) if u == -1 and current_sum != 0: u = current_sum v = i + 1 return ans def solve2(self, n, x, a): ans = -1 for i in range(n): if n - i <= ans: break s_mod = 0 for j in range(i, n): s_mod = (s_mod + a[j]) % x if s_mod != 0: length = j - i + 1 if length > ans: ans = length return ans ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) x = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, x, a) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","math,two_pointers,data_structures",medium 412,"Given a connected undirected graph $G$ with $n$ nodes and $m$ edges, where all nodes are numbered from 1 to $n$. Find the sum of the edge weights of the minimum spanning tree of $G$. The edges are represented as $edges[i] = [a, b, c]$, indicating that there is an edge between nodes $a$ and $b$ with a weight of $c$. solution main function ```python class Solution: def solve(self, n, edge): pass # write your code here``` Example 1: Input: n = 7, edges = [[1,2,9],[1,5,2],[1,6,3],[2,3,5],[2,6,7],[3,4,6],[3,7,3],[4,5,6],[4,7,2],[5,6,3],[5,7,6],[6,7,1]] Output: 16 Constraints: 2 <= n <= @data edges[i].size ==3 Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",6000,"[[160000, 160000, 160000], [160000, 160000, 160000], [160000, 160000, 160000]]","import sys class Solution: def find(self, x): if x == self.fa[x]: return x self.fa[x] = self.find(self.fa[x]) return self.fa[x] def solve1(self, N, edges): self.n = N self.m = len(edges) self.edge = [] for i in range(self.m): self.edge.append([edges[i][0], edges[i][1], edges[i][2]]) self.fa = list(range(self.n + 10)) for i in range(1, self.n + 1): self.fa[i] = i self.edge.sort(key=lambda x: x[2]) self.ans = 0 self.k = 0 for i in range(self.m): u, v, w = self.edge[i] self.fa1 = self.find(u) self.fa2 = self.find(v) if self.fa1 == self.fa2: continue self.fa[self.fa1] = self.fa2 self.ans += w self.k += 1 if self.k == self.n - 1: break return self.ans def solve2(self, N, edges): if N <= 1: return 0 visited = [False] * (N + 1) visited[1] = True cnt = 1 total = 0 m = len(edges) while cnt < N: best_w = None best_to = -1 i = 0 while i < m: a, b, c = edges[i] va = visited[a] vb = visited[b] if va != vb: if best_w is None or c < best_w: best_w = c best_to = b if not vb else a i += 1 total += best_w visited[best_to] = True cnt += 1 return total ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) edge = [] i = 1 while i <= m: x = int(next(it)) y = int(next(it)) z = int(next(it)) temp = [] temp.append(x) temp.append(y) temp.append(z) edge.append(temp) i += 1 solution = Solution() result = solution.solve(n, edge) sys.stdout.write(str(result))",graph,medium 413,"Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = ""abcdefd"" and ch = ""d"", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be ""dcbaefd"". Return the resulting string. solution main function ```python class Solution: def solve(self, word, ch): pass # write your code here``` Example 1: Input: word = ""abcdefd"", ch = ""d"" Output: ""dcbaefd"" Example 2: Input: word = ""xyxzxe"", ch = ""z"" Output: ""zxyxxe"" Constraints: 1 <= word.length <= @data word consists of lowercase English letters. ch is a lowercase English letter. Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 100000]",4000,"[[5000, 500, 64], [40000, 4000, 400], [320000, 32000, 3200]]","class Solution: def solve1(self, word, ch): word_list = list(word) left = 0 for right in range(len(word_list)): if word_list[right] == ch: current_right = right while left < current_right: word_list[left], word_list[current_right] = word_list[current_right], word_list[left] left += 1 current_right -= 1 return """".join(word_list) return word def solve2(self, word, ch): idx = -1 for i in range(len(word)): if word[i] == ch: idx = i break if idx == -1: return word return word[:idx + 1][::-1] + word[idx + 1:] ","import sys def main(): data = sys.stdin.read().split() if len(data) < 2: return ch = data[0] s = data[1] solution = Solution() result = solution.solve(s, ch[0]) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","string,two_pointers",easy 414,"# Problem Statement You are given a binary string$^{\dagger}$. Please find the minimum number of pieces you need to cut it into, so that the resulting pieces can be rearranged into a sorted binary string. Note that: - each character must lie in exactly one of the pieces; - the pieces must be contiguous substrings of the original string; - you must use all the pieces in the rearrangement. $^{\dagger}$ A binary string is a string consisting of characters $\texttt{0}$ and $\texttt{1}$. A sorted binary string is a binary string such that all characters $\texttt{0}$ come before all characters $\texttt{1}$. The main function of the solution is defined as: ```python class Solution: def solve(self, s): pass # write your code here``` where: - return: the minimum number of pieces needed to be able to rearrange the string into a sorted binary string. # Example 1: - Input: s = ""11010"" - Output: 3 # Constraints: - $1 \leq s.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, s): cnt = 1 cnt2 = 0 for i in range(1, len(s)): if s[i] == '0' and s[i - 1] == '1': cnt += 1 elif s[i] == '1' and s[i - 1] == '0': cnt2 += 1 if cnt2 > 0: cnt2 -= 1 return cnt + cnt2 def solve2(self, s): a = 0 b = 0 for i in range(1, len(s)): if s[i - 1] == '1' and s[i] == '0': a += 1 elif s[i - 1] == '0' and s[i] == '1': b += 1 return 1 + a + (b - 1 if b > 0 else 0) ","import sys s = sys.stdin.buffer.readline().decode().split()[0] solution = Solution() result = solution.solve(s) sys.stdout.write(str(result) + ""\n"")","dp,sort,string",hard 415,"# Problem Statement You are given two binary strings $a$ and $b$. A binary string is a string consisting of the characters '0' and '1'. Your task is to determine the maximum possible number $k$ such that a prefix of string $a$ of length $k$ is a subsequence of string $b$. A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements. The main function of the solution is defined as: ```python class Solution: def solve(self, a, b): pass # write your code here``` where: - return: the maximum possible number $k$ such that a prefix of string $a$ of length $k$ is a subsequence of string $b$. # Example 1: - Input: a = ""10011"" b = ""1110"" - Output: 2 # Constraints: - $1 \leq a.length, b.length \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, a, b): n = len(a) m = len(b) ans = 0 for i in range(m): if ans < n and b[i] == a[ans]: ans += 1 return ans def solve2(self, a, b): n = len(a) m = len(b) ans = 0 k = 1 while k <= n: i = 0 j = 0 while i < k and j < m: if a[i] == b[j]: i += 1 j += 1 if i == k: ans = k k += 1 else: break return ans ","import sys data = sys.stdin.read().split() a = """" b = """" if len(data) > 0: a = data[0] if len(data) > 1: b = data[1] solution = Solution() result = solution.solve(a, b) sys.stdout.write(str(result) + ""\n"")","two_pointers,string",easy 416,"There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents: the price needed to open the gate at node i, if amount[i] is negative, or, the cash reward obtained on opening the gate at node i, otherwise. The game goes on as follows: Initially, Alice is at node 0 and Bob is at node bob. At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0. For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that: If the gate is already open, no price will be required, nor will there be any cash reward. If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each. If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other. Return the maximum net income Alice can have if she travels towards the optimal leaf node. solution main function ```python class Solution: def solve(self, edge, bob, val): pass # write your code here``` Example 1: Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6] Output: 6 Example 2: Input: edges = [[0,1]], bob = 1, amount = [-7280,2350] Output: -7280 Constraints: 2 <= n <= @data edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi edges represents a valid tree. 1 <= bob < n amount.length == n amount[i] is an even integer in the range [-10^4, 10^4] Time limit: @time_limit ms Memory limit: @memory_limit KB ","[100, 1000, 10000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import math import sys sys.setrecursionlimit(100005) class Solution: def dfs(self, u, p=0, d=0): self.dis[u] = d self.par[u] = p for v in self.adj[u]: if v == p: continue self.dfs(v, u, d + 1) def dfs2(self, u, amount, p=0): ret = amount[u] mxc = -math.inf for v in self.adj[u]: if v != p: mxc = max(mxc, self.dfs2(v, amount, u)) if mxc == -math.inf: return ret else: return ret + mxc def solve1(self, edges, bob, amount): n = len(amount) self.adj = [[] for _ in range(n)] for e in edges: self.adj[e[0]].append(e[1]) self.adj[e[1]].append(e[0]) self.par = [0] * n self.dis = [0] * n self.dfs(0) cur = bob bob_dis = 0 while cur != 0: if self.dis[cur] > bob_dis: amount[cur] = 0 elif self.dis[cur] == bob_dis: amount[cur] //= 2 cur = self.par[cur] bob_dis += 1 return self.dfs2(0, amount) def solve2(self, edges, bob, amount): n = len(amount) M = max(20001, n + 5) for i in range(n): amount[i] = amount[i] * M + (M - 1) amount[0] = (amount[0] // M) * M + 0 while True: changed = False for u, v in edges: ru = amount[u] % M rv = amount[v] % M if ru != M - 1 and rv == M - 1: valv = amount[v] // M amount[v] = valv * M + (ru + 1) changed = True elif rv != M - 1 and ru == M - 1: valu = amount[u] // M amount[u] = valu * M + (rv + 1) changed = True if not changed: break cur = bob bob_dis = 0 while True: dcur = amount[cur] % M valcur = amount[cur] // M if dcur > bob_dis: valcur = 0 elif dcur == bob_dis: valcur = valcur // 2 amount[cur] = valcur * M + dcur if cur == 0: break dd = dcur - 1 for u, v in edges: if u == cur: if amount[v] % M == dd: cur = v break elif v == cur: if amount[u] % M == dd: cur = u break bob_dis += 1 max_depth = 0 for i in range(n): r = amount[i] % M if r > max_depth: max_depth = r d = max_depth while d >= 0: for u in range(n): if amount[u] % M == d: base = amount[u] // M best = -10**18 for x, y in edges: if x == u: if amount[y] % M == d + 1: vdp = amount[y] // M if vdp > best: best = vdp elif y == u: if amount[x] % M == d + 1: vdp = amount[x] // M if vdp > best: best = vdp if best == -10**18: dp_u = base else: dp_u = base + best amount[u] = dp_u * M + d d -= 1 return amount[0] // M ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) bob = int(next(it)) edge = [] val = [] i = 1 while i < n: x = int(next(it)) y = int(next(it)) temp = [] temp.append(x) temp.append(y) edge.append(temp) i += 1 i = 1 while i <= n: x = int(next(it)) val.append(x) i += 1 solution = Solution() result = solution.solve(edge, bob, val) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","graph,search",medium 417,"Bracteoles are ready to drive down the road. There are $n$ stops on the highway, numbered from $1$ to $n$. The distance between site $i$ and site $i + 1$ is $v_i$ km. Every station on the highway can be refueled, the price of a liter of gas at the station numbered $i$ is $a_i$, and each station only sells integer liters of gas. The Bract wants to drive from site $1$ to site $n$. At first the Bract is at site $1$ and the tank of the car is empty. It is known that the tank of the car is large enough to hold as much oil as it wants, and it can move forward $d$ km per liter of oil. Find the minimum amount of money the Bract must spend on fuel to travel from site $1$ to site $n$. solution main function ```python class Solution: def solve(self, n, d, dist, val): pass # write your code here ``` Pass in parameters: - `n`, `d`: the number of stops and kilometers traveled per liter of fuel. - `dist`: an array of `n - 1` positive integers, where `dist[i]` is the distance between consecutive sites. - `val`: an array of `n` positive integers, where `val[i]` is the fuel price at a station. Return parameters: An integer indicating the minimum money the Bract must spend on fuel from site $1$ to site $n$. Example 1: Input: n = 5, d = 4, dist = [10, 10, 10, 10], val = [9, 8, 9, 6, 5] Output: 79 Constraints: 1 <= n <= @data 1 <= d <= 10^5 1 <= val[i], dist[i] <= 10^5 Time limit: @time_limit ms Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, d, v, a): ans = 0 s = 0 mi = float('inf') v.insert(0, 0) a.insert(0, 0) for i in range(1, n): s += v[i] mi = min(mi, a[i]) if s > 0: liters = (s + d - 1) // d ans += liters * mi s -= liters * d return ans def solve2(self, n, d, v, a): ans = 0 s = 0 mi = float('inf') for i in range(n - 1): s += v[i] if a[i] < mi: mi = a[i] if s > 0: liters = (s + d - 1) // d ans += liters * mi s -= liters * d return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) d = int(next(it)) dist = [] for i in range(1, n): x = int(next(it)) dist.append(x) val = [] for i in range(1, n + 1): x = int(next(it)) val.append(x) solution = Solution() result = solution.solve(n, d, dist, val) sys.stdout.write(str(result) + ""\n"")",dp,hard 418,"# Problem Statement Karina has an array of $n$ integers $a_1, a_2, a_3, \dots, a_n$. She loves multiplying numbers, so she decided that the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of a pair of **adjacent** elements in the array. For example, for $n = 4$, $a=[3, 5, 7, 4]$, the beauty of the array is $\max$($3 \cdot 5$, $5 \cdot 7$, $7 \cdot 4$) = $\max$($15$, $35$, $28$) = $35$. Karina wants her array to be as beautiful as possible. In order to achieve her goal, she can remove some elements (possibly zero) from the array. After Karina removes all elements she wants to, the array must contain at least two elements. Unfortunately, Karina doesn't have enough time to do all her tasks, so she asks you to calculate the maximum beauty of the array that she can get by removing any number of elements (possibly zero). The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return value is a 64-bit integer representing the maximum beauty of the array # Example 1: - Input: n = 4 a = [5, 0, 2, 1] - Output: 10 # Constraints: - $2 \leq n \leq @data$ - $-10^9 \leq a_i \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): ans = -int(1E18) mn = int(1E18) mx = -int(1E18) for i in range(n): x = a[i] if i > 0: ans = max(ans, x * mx, x * mn) mn = min(mn, x) mx = max(mx, x) return ans def solve2(self, n, a): ans = a[0] * a[1] for i in range(n): ai = a[i] for j in range(i + 1, n): p = ai * a[j] if p > ans: ans = p return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","greedy,math,sort",easy 419,"There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct password is ""345"" and you enter in ""012345"": After typing 0, the most recent 3 digits is ""0"", which is incorrect. After typing 1, the most recent 3 digits is ""01"", which is incorrect. After typing 2, the most recent 3 digits is ""012"", which is incorrect. After typing 3, the most recent 3 digits is ""123"", which is incorrect. After typing 4, the most recent 3 digits is ""234"", which is incorrect. After typing 5, the most recent 3 digits is ""345"", which is correct and the safe unlocks. Return any string of minimum length that will unlock the safe at some point of entering it. Any valid minimum-length string is accepted. The examples show one valid returned string; this runner validates the returned string and prints 1 if it is valid, or 0 otherwise. solution main function ```python class Solution: def solve(self, n, k): pass # write your code here``` Example 1: Input: n = 1, k = 2 One valid output: ""10"" Example 2: Input: n = 2, k = 2 One valid output: ""01100"" Constraints: 1 <= n <= 4 1 <= k <= @data 1 <= k^n <= 4096 Time limit: @time_limit ms Memory limit: @memory_limit KB","[3, 5, 10]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve(self, n, k): nodeNum = k ** (n - 1) nedge = k ** n vecNode = [k - 1] * nodeNum strret = ['0'] * (nedge + n - 1) idx = 0 for i in range(n - 1, len(strret)): curedge = vecNode[idx] strret[i] = str(curedge) vecNode[idx] -= 1 idx = (idx * k + curedge) % nodeNum return """".join(strret) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) solution = Solution() result = solution.solve(n, k) total = k ** n ok = isinstance(result, str) and len(result) == total + n - 1 if ok: for ch in result: if ch < '0' or ch >= chr(ord('0') + k): ok = False break if ok: seen = set() for i in range(0, len(result) - n + 1): seen.add(result[i:i + n]) ok = len(seen) == total sys.stdout.write(""1\n"" if ok else ""0\n"") ",graph,hard 420,"You are given a string s. Reorder the string using the following algorithm: Remove the smallest character from s and append it to the result. Remove the smallest character from s that is greater than the last appended character, and append it to the result. Repeat step 2 until no more characters can be removed. Remove the largest character from s and append it to the result. Remove the largest character from s that is smaller than the last appended character, and append it to the result. Repeat step 5 until no more characters can be removed. Repeat steps 1 through 6 until all characters from s have been removed. If the smallest or largest character appears more than once, you may choose any occurrence to append to the result. Return the resulting string after reordering s using this algorithm. solution main function ```python class Solution: def solve(self, s): pass # write your code here``` Example 1: Input: s = ""aaaabbbbcccc"" Output: ""abccbaabccba"" Example 2: Input: s = ""rat"" Output: ""art"" Constraints: 1 <= s.length <= @data s consists of only lowercase English letters. Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 500, 1000]",4000,"[[2000, 1000, 500], [16000, 8000, 4000], [128000, 64000, 32000]]","import collections class Solution: def solve1(self, s: str) -> str: cnt = [0] * 26 for c in s: cnt[ord(c) - ord('a')] += 1 ans = [] s_len = len(s) while len(ans) < s_len: for i in range(26): if cnt[i] > 0: ans.append(chr(ord('a') + i)) cnt[i] -= 1 for i in range(25, -1, -1): if cnt[i] > 0: ans.append(chr(ord('a') + i)) cnt[i] -= 1 return """".join(ans) def solve2(self, s: str) -> str: ans = [] while s: for i in range(26): ch = chr(ord('a') + i) idx = s.find(ch) if idx != -1: ans.append(ch) s = s[:idx] + s[idx+1:] for i in range(25, -1, -1): ch = chr(ord('a') + i) idx = s.find(ch) if idx != -1: ans.append(ch) s = s[:idx] + s[idx+1:] return """".join(ans) ","import sys def main(): data = sys.stdin.read().split() idx = 0 s = """" if idx < len(data): s = data[idx] idx += 1 solution = Solution() result = solution.solve(s) sys.stdout.write(str(result)) if __name__ == ""__main__"": main()","string,other",easy 421,"# Problem Statement A girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of $n$ flowers in the store, each of which is characterized by the number of petals, and a flower with $k$ petals costs $k$ coins. The girl has decided that the difference in the number of petals between any two flowers she will use in her bouquet should not exceed one. At the same time, the girl wants to assemble a bouquet with the maximum possible number of petals. Unfortunately, she only has $m$ coins, and she cannot spend more. What is the maximum total number of petals she can assemble in the bouquet? The main function of the solution is defined as: ```python class Solution: def solve(self, n, m, a): pass # write your code here``` where: - The return value is the maximum total number of petals that can be assembled in the bouquet. Note that the answer may be very large and should be stored in a 64-bit integer type. # Example 1: - Input: n = 5, m = 10 a = [1, 1, 2, 2, 3] - Output: 7 # Constraints: - $1 \leq n \leq @data$ - $1 \leq m \leq 10^18$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, m, a): a.sort() max_sum = 0 current_sum = 0 l = 0 for r in range(n): current_sum += a[r] while l <= r and (a[r] - a[l] > 1 or current_sum > m): current_sum -= a[l] l += 1 max_sum = max(max_sum, current_sum) return max_sum def solve2(self, n, m, a): a.sort() ans = 0 i = 0 while i < n: k = a[i] j = i while j < n and a[j] == k: j += 1 cnt0 = j - i t = m // k if t < cnt0: sum_k_only = t * k else: sum_k_only = cnt0 * k if sum_k_only > ans: ans = sum_k_only if j < n and a[j] == k + 1: t2 = j while t2 < n and a[t2] == k + 1: t2 += 1 cnt1 = t2 - j max_x = m // (k + 1) if max_x > cnt1: max_x = cnt1 x = 0 while x <= max_x: rem = m - x * (k + 1) y_max = rem // k if y_max > cnt0: y_max = cnt0 total = x * (k + 1) + y_max * k if total > ans: ans = total x += 1 i = j return ans ","import sys def main(): data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) m = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, m, a) sys.stdout.write(str(result) + ""\n"") if __name__ == ""__main__"": main()","two_pointers,greedy,sort",medium 422,"# Problem Statement The beauty of an array $b$ of length $m$ ($m \ge 2$) is defined as $$ \max_{1 \le i < j \le m} (b_j - b_i). $$ Note that the beauty can be negative if the array is strictly decreasing. Hao and Alex play a turn-based game on an array $a$ of length $n$. Initially all elements are unlocked. The players move alternately, with Hao going first: - On Hao's turn, he selects one unlocked element from $a$ and removes it. - On Alex's turn, he selects one unlocked element from $a$ and locks it (so it can no longer be removed). The game ends when all elements are either locked or removed. It can be proven that the game lasts exactly $n$ turns and exactly $\lfloor n/2 \rfloor$ elements remain locked in the final array $b$. Hao wants to minimize the beauty of the final array $b$, while Alex wants to maximize it. Assuming both play optimally, determine the beauty of the final locked array. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - `n`: the length of the input array - `a`: the array elements - return: the beauty of the final locked array under optimal play # Example: - Input: n = 5 a = [5, 1, 2, 3, 4] - Output: 1 # Constraints: - $4 \le n \le @data$ - $1 \le a[i] \le 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 100000]",4000,"[[500, 250, 100], [4000, 2000, 800], [32000, 16000, 6400]]","import sys class Solution: def solve1(self, n, a): def check(g): b = [0] * n mn_list = [] for i in range(n): for x in mn_list: if a[i] - x >= g: b[i] += 1 mn_list.append(a[i]) mn_list.sort() if len(mn_list) > 3: mn_list = mn_list[:3] mx_list = [] for i in range(n - 1, -1, -1): for x in mx_list: if x - a[i] >= g: b[i] += 1 mx_list.append(a[i]) mx_list.sort(reverse=True) if len(mx_list) > 3: mx_list = mx_list[:3] t = 0 for i in range(1, n): if b[i] > b[t]: t = i max_b = b[t] if max_b <= 1: return False if max_b > 2: for i in range(n): if i == t: continue diff = abs(a[i] - a[t]) bi = b[i] - (1 if diff >= g else 0) if bi >= 2: return True return False cnt2 = 0 for val in b: if val == 2: cnt2 += 1 if cnt2 > 3: return True for i in range(n): if b[i] != 2: continue ok = True for j in range(n): if j == i: continue diff = abs(a[j] - a[i]) bj = b[j] - (1 if diff >= g else 0) if bj >= 2: ok = False break if ok: return False return True lo = -1000000005 hi = 1000000005 while lo < hi: mid = lo + (hi - lo + 1) // 2 if check(mid): lo = mid else: hi = mid - 1 return lo def solve2(self, n, a): def check(g): b = [0] * n mn_list = [] for i in range(n): for x in mn_list: if a[i] - x >= g: b[i] += 1 mn_list.append(a[i]) mn_list.sort() if len(mn_list) > 3: mn_list = mn_list[:3] mx_list = [] for i in range(n - 1, -1, -1): for x in mx_list: if x - a[i] >= g: b[i] += 1 mx_list.append(a[i]) mx_list.sort(reverse=True) if len(mx_list) > 3: mx_list = mx_list[:3] t = 0 for i in range(1, n): if b[i] > b[t]: t = i max_b = b[t] if max_b <= 1: return False if max_b > 2: for i in range(n): if i == t: continue diff = abs(a[i] - a[t]) bi = b[i] - (1 if diff >= g else 0) if bi >= 2: return True return False cnt2 = 0 for val in b: if val == 2: cnt2 += 1 if cnt2 > 3: return True for i in range(n): if b[i] != 2: continue ok = True for j in range(n): if j == i: continue diff = abs(a[j] - a[i]) bj = b[j] - (1 if diff >= g else 0) if bj >= 2: ok = False break if ok: return False return True lo = -1000000005 hi = 1000000005 while lo < hi: mid = lo + (hi - lo + 1) // 2 if check(mid): lo = mid else: hi = mid - 1 return lo ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","binary,data_structures",hard 423,"# Problem Statement Dora has a set $s$ containing integers. In the beginning, she will put all integers in $[l, r]$ into the set $s$. That is, an integer $x$ is initially contained in the set if and only if $l \leq x \leq r$. Then she allows you to perform the following operations: - Select three **distinct** integers $a$, $b$, and $c$ from the set $s$, such that $\gcd(a, b) = \gcd(b, c) = \gcd(a, c) = 1^\dagger$. - Then, remove these three integers from the set $s$. What is the maximum number of operations you can perform? $^\dagger$Recall that $\gcd(x, y)$ means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers $x$ and $y$. The main function of the solution is defined as: ```python class Solution: def solve(self, l, r): pass # write your code here``` where: - return: the maximum number of operations you can perform. # Example 1: - Input: l = 1, r = 3 - Output: 1 # Constraints: - $1 \leq l \leq r \leq @data$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, l, r): ans = 0 i = l while i + 2 <= r: if i % 2 == 0: i += 1 continue ans += 1 i += 3 return ans def solve2(self, l, r): odds = ((r + 1) // 2) - (l // 2) return odds // 2 ","import sys data = sys.stdin.read().strip().split() it = iter(data) l = int(next(it)) r = int(next(it)) solution = Solution() result = solution.solve(l, r) sys.stdout.write(str(result) + ""\n"")",math,medium 424,"# Problem Statement You have an integer array $a$ of length $n$. There are two kinds of operations you can make. - Remove an integer from $a$. This operation costs $c$. - Insert an arbitrary positive integer $x$ to any position of $a$ (to the front, to the back, or between any two consecutive elements). This operation costs $d$. You want to make the final array a permutation of **any** positive length. Please output the minimum cost of doing that. Note that you can make the array empty during the operations, but the final array must contain at least one integer. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). Note that the answer may be large, so you should use a type. The main function of the solution is defined as: ```python class Solution: def solve(self, n, c, d, a): pass # write your code here``` where: - Return 64-bit integer type of the minimum cost # Example 1: - Input: n = 3, c = 3, d = 3 a = [1, 2, 3] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq c, d \leq 10^9$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[100, 10000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, c, d, a): a.sort() ans = n * c + d t = 0 for i in range(n): if i == 0 or a[i] != a[i - 1]: t += 1 ans = min(ans, n * c + a[i] * d - t * (c + d)) return ans def solve2(self, n, c, d, a): for i in range(n): mi = i mv = a[i] for j in range(i + 1, n): if a[j] < mv: mi = j mv = a[j] if mi != i: a[i], a[mi] = a[mi], a[i] ans = n * c + d t = 0 for i in range(n): if i == 0 or a[i] != a[i - 1]: t += 1 v = n * c + a[i] * d - t * (c + d) if v < ans: ans = v return ans ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) c = int(next(it)) d = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, c, d, a) sys.stdout.write(str(result) + ""\n"")","math,sort",hard 425,"# Problem Statement Dmitry has a string $s$, consisting of lowercase Latin letters. Dmitry decided to remove two **consecutive** characters from the string $s$ and you are wondering how many different strings can be obtained after such an operation. For example, Dmitry has a string ""aaabcc"". You can get the following different strings: ""abcc""(by deleting the first two or second and third characters), ""aacc""(by deleting the third and fourth characters),""aaac""(by deleting the fourth and the fifth character) and ""aaab"" (by deleting the last two). The main function of the solution is defined as: ```python class Solution: def solve(self, n, s): pass # write your code here``` where: - return: the number of distinct strings that can be obtained by removing two consecutive letters. # Example 1: - Input: n = 6 s = ""aaabcc"" - Output: 4 # Constraints: - $3 \leq n \leq @data$ - $s$ consists of lowercase Latin letters - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import math import sys class Solution: def solve1(self, n, s): ans = n - 1 for i in range(n - 2): ans -= (s[i] == s[i + 2]) return ans def solve2(self, n, s): count = 0 L = n - 2 for i in range(n - 1): duplicate = False for j in range(i): equal = True for k in range(L): a = k if k < i else k + 2 b = k if k < j else k + 2 if s[a] != s[b]: equal = False break if equal: duplicate = True break if not duplicate: count += 1 return count ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, s) sys.stdout.write(str(result) + ""\n"")","string,greedy,data_structures",hard 426,"There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen. solution main function ```python class Solution: def solve(self, n): pass # write your code here``` Example 1: Input: n = 3 Output: 3 Example 2: Input: n = 1 Output: 0 Constraints: 1 <= n <= @data Time limit: @time_limit ms Memory limit: @memory_limit KB","[100, 1000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def dfs(self, n): if n == 1: return 0 steps = n for d in range(2, int(math.sqrt(n)) + 1): if n % d == 0: steps = min(steps, self.dfs(d) + (n // d)) steps = min(steps, self.dfs(n // d) + d) return steps def solve1(self, n): return self.dfs(n) def solve2(self, n): if n <= 1: return 0 steps = 0 d = 2 while d * d <= n: while n % d == 0: steps += d n //= d d += 1 if n > 1: steps += n return steps ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) solution = Solution() result = solution.solve(n) sys.stdout.write(str(result))",math,medium 427,"# Problem Statement Eralim, being the mafia boss, manages a group of $n$ fighters. Fighter $i$ has a rating of $a_i$. Eralim arranges a tournament of $n - 1$ battles, in each of which two not yet eliminated fighters $i$ and $j$ (**$1 \le i < j \le n$**) are chosen, and as a result of the battle, fighter $i$ is eliminated from the tournament, and the rating of fighter $j$ is reduced by the rating of fighter $i$. That is, $a_j$ is decreased by $a_i$. Note that fighter $j$'s rating can become negative. The fighters indexes do not change. Eralim wants to know what maximum rating the last remaining fighter can preserve if he chooses the battles optimally. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return:the maximum rating that the last remaining fighter can preserve. # Example 1: - Input: n = 2, a = [2, 1] - Output: -1 # Constraints: - $2 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): ans = 0 for i in range(1, n + 1): if i <= n - 2: ans = ans + a[i - 1] else: ans = a[i - 1] - ans return ans def solve2(self, n, a): s = 0 for i in range(0, n - 2): s += a[i] return s + a[n - 1] - a[n - 2] ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","constructive_algorithms,math",easy 428,"# Problem Statement Alice and Bob are playing a game. They have an array of positive integers $a$ of size $n$. Before starting the game, Alice chooses an integer $k \ge 0$. The game lasts for $k$ stages, the stages are numbered from $1$ to $k$. During the $i$-th stage, Alice must remove an element from the array that is less than or equal to $k - i + 1$. After that, if the array is not empty, Bob must add $k - i + 1$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $k$-th stage ends and Alice hasn't lost yet, she wins. Your task is to determine the maximum value of $k$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the maximum value of k such that Alice can win if both players play optimally. # Example 1: - Input: n = 3 a = [1, 1, 2] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20000, 200000, 2500000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): cnt = [0] * n for val in a: if val <= n: cnt[val - 1] += 1 for i in range(1, n): cnt[i] += cnt[i - 1] ans = n for i in range(n): current_cost = max(cnt[i] - i, i) if current_cost < ans: ans = current_cost return ans def solve2(self, n, a): a.sort() l, r = 0, n while l < r: mid = (l + r + 1) // 2 x = mid for i in range(n, mid - 1, -1): if a[i - 1] <= x: x -= 1 if x == 0: l = mid else: r = mid - 1 return l","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","binary,data_structures,sort",hard 429,"# Problem Statement You are given an array $a_1, a_2, \dots a_n$. Count the number of pairs of indices $1 \leq i, j \leq n$ such that $a_i < i < a_j < j$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of pairs of indices satisfying the condition in the statement. # Example 1: - Input: n = 8 a = [1, 1, 2, 3, 8, 2, 1, 4] - Output: 3 # Constraints: - $2 \leq n \leq @data$ - $0 \leq a[i] \leq 10^9$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, a): sum_counts = [0] * (n + 1) for i in range(n): sum_counts[i + 1] = sum_counts[i] + (a[i] < i + 1) ans = 0 for i in range(n): if a[i] < i + 1 and a[i] > 0: limit = min(n, a[i] - 1) ans += sum_counts[limit] return ans def solve2(self, n, a): ans = 0 for i in range(n): if a[i] < i + 1 and a[i] > 0: limit = min(n, a[i] - 1) for j in range(limit): if a[j] < j + 1: ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")","sort,dp,greedy",hard 430,"# Problem Statement: An integer array $a_1, a_2, \ldots, a_n$ is being transformed into an array of lowercase English letters using the following prodecure: While there is at least one number in the array: - Choose any number $x$ from the array $a$, and any letter of the English alphabet $y$. - Replace all occurrences of number $x$ with the letter $y$. For example, if we initially had an array $a = [2, 3, 2, 4, 1]$, then we could transform it the following way: - Choose the number $2$ and the letter c. After that $a = [c, 3, c, 4, 1]$. - Choose the number $3$ and the letter a. After that $a = [c, a, c, 4, 1]$. - Choose the number $4$ and the letter t. After that $a = [c, a, c, t, 1]$. - Choose the number $1$ and the letter a. After that $a = [c, a, c, t, a]$. After the transformation all letters are united into a string, in our example we get the string ""cacta"". Having the array $a$ and the string $s$ determine if the string $s$ could be got from the array $a$ after the described transformation? The main function of the solution is defined as: ```python class Solution: def solve(self, n, a, s): pass # write your code here``` Where: - `n` is an integer representing the length of the array and string. - `a` is an integer array. - `s` is a string consisting of lowercase English letters. - The return value is ""YES"" if the string $s$ could be got from the array $a$ after the described transformation, otherwise return ""NO"". # Example 1: - Input: n = 5 a = [2, 3, 2, 4, 1] s = ""cacta"" - Output: YES # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10, 1000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a, s): mp = [-1] * (n + 1) for i in range(n): char_code = ord(s[i]) if mp[a[i]] == -1: mp[a[i]] = char_code elif mp[a[i]] != char_code: return ""NO"" return ""YES"" def solve2(self, n, a, s): for i in range(n): for j in range(n): if a[i] == a[j] and s[i] != s[j]: return ""NO"" return ""YES"" ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) s = next(it) solution = Solution() result = solution.solve(n, a, s) sys.stdout.write(str(result) + ""\n"")",greedy,medium 431,"# Problem Statement Given an array $a$ of length $n$, where $2 \leq a[i] \leq n$, you need to find the smallest prime factor of each number and return the XOR sum of all results. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the XOR sum of the smallest prime factor of each number in the array. # Example 1: - Input: n = 4 a = [2, 4, 3, 4] - Output: 1 # Constraints: - $2 \leq n \leq @data$ - $2 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 100000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import math class Solution: def solve1(self, n, a): prime = [] min_prime = [0] * (n + 1) for i in range(2, n + 1): if min_prime[i] == 0: prime.append(i) min_prime[i] = i for p in prime: if i * p > n: break min_prime[i * p] = p if i % p == 0: break res = 0 for x in a: res ^= min_prime[x] return res def solve2(self, n, a): res = 0 for x in a: min_p = x limit = int(math.sqrt(x)) for j in range(2, limit + 1): if x % j == 0: min_p = j break res ^= min_p return res ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,easy 432,"# Problem Statement Given an array $a$ of length $n$. You need to count the number of inversions in the array. An inversion is defined as a pair of elements $a[i]$ and $a[j]$ such that $i < j$ and $a[i] > a[j]$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of inversions in the array. # Example 1: - Input: n = 5 a = [3, 1, 2, 5, 4] - Output: 3 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def solve1(self, n, a): ans = 0 bit = [0] * (n + 2) for i in range(n - 1, -1, -1): j = a[i] - 1 while j > 0: ans += bit[j] j -= j & -j j = a[i] while j <= n: bit[j] += 1 j += j & -j return ans def solve2(self, n, a): ans = 0 for i in range(n): for j in range(i + 1, n): if a[i] > a[j]: ans += 1 return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",data_structures,easy 433,"# Problem Statement Given an array $a$ of length $n$, where the elements are integers. You need to count the number of subarrays whose sum is 0. The sum of a subarray is defined as the sum of elements from index $l$ to $r$, i.e., $a[l] + a[l+1] + \dots + a[r]$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the number of subarrays whose sum is 0. # Example 1: - Input: n = 5 a = [1, -1, 2, -2, 0] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $-n \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 100, 64], [4000, 800, 80], [32000, 6400, 640]]","import collections class Solution: def solve1(self, n, a): prefix = [0] * (n + 1) for i in range(n): prefix[i + 1] = prefix[i] + a[i] mp = {} result = 0 mp[0] = 1 for i in range(1, n + 1): p_sum = prefix[i] if p_sum in mp: result += mp[p_sum] mp[p_sum] = mp.get(p_sum, 0) + 1 return result def solve2(self, n, a): result = 0 for i in range(n): current_sum = 0 for j in range(i, n): current_sum += a[j] if current_sum == 0: result += 1 return result ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",data_structures,medium 434,"# Problem Statement A permutation $a$ of length $n$ consists of integers from $1$ to $n$, with each integer appearing exactly once. For each number $a[i]$, define its contribution as the length of the cycle that $a[i]$ belongs to. The cycle is defined by starting from $a[i]$, then visiting the next element $a[a[i]]$, then $a[a[a[i]]]$, and so on, until returning to $a[i]$. Please calculate the sum of the contributions of $a$.Note that the index of $a$ starts from $1$, you may need to convert it to start from $0$. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the sum of the contributions of $a$. # Example 1: - Input: n = 4 a = [2, 1, 3, 4] - Output: 6 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq 10^9$ - $a[i]$ is distinct - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections class Solution: def solve1(self, n, a): vis = [False] * n ans = 0 for i in range(n): a[i] -= 1 for i in range(n): if vis[i]: continue j = i cnt = 0 while not vis[j]: vis[j] = True cnt += 1 j = a[j] ans += cnt * cnt return ans def solve2(self, n, a): ans = 0 for i in range(n): a[i] -= 1 for i in range(n): j = i cnt = 1 j = a[j] while j != i: cnt += 1 j = a[j] ans += cnt return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",search,hard 435,"# Problem Statement Given an array $a$ of length $n$ ($2 \leq a[i] \leq n$), determine whether each number in the array is a prime number. For each number, if it is prime, represent it as '1'; otherwise, represent it as '0'. Return a binary string of length $n$, where the $i$-th character is '1' if $a[i]$ is prime, and '0' otherwise. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` The function should return the binary string. # Example 1: - Input: n = 2 a = [2, 2] - Output: 11 # Constraints: - $2 \leq n \leq @data$ - $2 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 75, 64], [4000, 600, 80], [32000, 4800, 640]]","class Solution: def solve1(self, n, a): size = (n >> 3) + 1 bits = bytearray([0xff]) * size def bit_get(i): return (bits[i >> 3] >> (i & 7)) & 1 def bit_clear(i): bits[i >> 3] &= ~(1 << (i & 7)) if n >= 0: bit_clear(0) if n >= 1: bit_clear(1) limit = int(n ** 0.5) for i in range(2, limit + 1): if bit_get(i): step = i start = i * i for j in range(start, n + 1, step): bit_clear(j) return """".join(""1"" if bit_get(v) else ""0"" for v in a) def solve2(self, n, a): out = [] for v in a: if v < 2: out.append(""0"") elif v == 2: out.append(""1"") elif v % 2 == 0: out.append(""0"") else: i = 3 composite = False while i * i <= v: if v % i == 0: composite = True break i += 2 out.append(""0"" if composite else ""1"") return """".join(out)","import sys data = sys.stdin.buffer.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,easy 436,"# Problem Statement Given an array $a$ of length $n$, where $2 <= a[i] <= n$, you need to find the modular inverse of each number modulo 998244353. Return the XOR of all the results. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the XOR of all the results. # Example 1: - Input: n = 2 a = [2, 2] - Output: 0 # Constraints: - $2 <= n <= @data$ - $2 <= a[i] <= n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20000, 200000, 2000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def solve1(self, n, a): mod = 998244353 inv = [0] * (n + 1) if n >= 1: inv[1] = 1 for i in range(2, n + 1): inv[i] = (mod - mod // i) * inv[mod % i] % mod res = 0 for x in a: res = res ^ inv[x] return res def solve2(self, n, a): mod = 998244353 ans = 0 for val in a: res = 1 b = mod - 2 v = val while b > 0: if b & 1: res = res * v % mod v = v * v % mod b >>= 1 ans ^= res return ans ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,medium 437,"# Problem Statement Given an integer $n$ and an array $a$ of length $n$, where $1 <= a[i] <= n$, you need to calculate the $a[i]$-th term of the Fibonacci sequence, then take the result modulo 998244353, and finally return the XOR sum of all results. The Fibonacci sequence is defined as follows: - $F(0) = 0$ - $F(1) = 1$ - $F(i) = F(i-1) + F(i-2)$ for $i \geq 2$ The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the xor sum of all results. # Example 1: - Input: n = 3 a = [1, 2, 3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[10000, 100000, 1000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import sys class Solution: def __init__(self): self.MOD = 998244353 self.mat = [[0, 0], [0, 0]] self.result = [[0, 0], [0, 0]] self.temp = [[0, 0], [0, 0]] def matrix_multiply(self, A, B, C): for i in range(2): for j in range(2): C[i][j] = 0 for k in range(2): C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % self.MOD def matrix_pow(self, power): self.result = [[1, 0], [0, 1]] while power > 0: if power & 1: self.matrix_multiply(self.result, self.mat, self.temp) self.result = [row[:] for row in self.temp] self.matrix_multiply(self.mat, self.mat, self.temp) self.mat = [row[:] for row in self.temp] power >>= 1 def fib(self, n): if n == 0: return 0 self.mat = [[1, 1], [1, 0]] self.matrix_pow(n - 1) return self.result[0][0] def solve1(self, n, a): fib_table = [0] * (n + 1) if n >= 1: fib_table[1] = 1 for i in range(2, n + 1): fib_table[i] = (fib_table[i - 1] + fib_table[i - 2]) % self.MOD xor_sum = 0 for num in a: xor_sum ^= fib_table[num] return xor_sum def solve2(self, n, a): xor_sum = 0 for num in a: xor_sum ^= self.fib(num) return xor_sum ","import sys data = sys.stdin.read().strip().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",math,medium 438,"# Problem Statement Given an array $a$ of length $n$ and an integer $k$. For each element $a[i]$ in the array, where $1 \leq a[i] \leq n$, assume there are $a[i]$ people standing in a circle, numbered from $1$ to $a[i]$. Starting from the person numbered $1$, count up to $k$ and the person at position $k$ is eliminated. Then, start counting again from the next person. This process continues until only one person remains in the circle. You need to calculate the position of the last remaining person for each $a[i]$ and return the XOR sum of all results. The main function of the solution is defined as: ```python class Solution: def solve(self, n, k, a): pass # write your code here``` where: - return: The XOR sum of all results. # Example 1: - Input: n = 2, k = 2 a = [1, 2] - Output: 0 # Constraints: - $1 \leq n \leq @data$ - $1 \leq k \leq 10^3$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import heapq import math class Solution: def solve1(self, n, k, a): dp = [0] * (n + 1) dp[1] = 0 for m in range(2, n + 1): dp[m] = (dp[m - 1] + k) % m xor_sum = 0 for num in a: xor_sum ^= (dp[num] + 1) return xor_sum def solve2(self, n, k, a): xor_sum = 0 for num in a: x = 0 for i in range(1, num + 1): x = (x + k) % i xor_sum ^= (x + 1) return xor_sum ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) k = int(next(it)) a = [0] * n for i in range(n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, k, a) sys.stdout.write(str(result) + ""\n"")",math,medium 439,"# Problem Statement Given an integer $n$, you need to answer $m$ queries. Each query provides a range $[l, r]$, and you are required to count the number of 1s in the binary representation of each number in the range $[l, r]$. Return the XOR sum of all query results. The main function of the solution is defined as: ```python class Solution: def solve(self, n, actual_m, q): pass # write your code here``` where: - `q`: $m$ queries, each query gives a range $[l, r]$, $q[i][0]$ represents the left endpoint $l$ of query $i$, $q[i][1]$ represents the right endpoint $r$ of query $i$. - Return: return the XOR sum of all query results. # Example 1: - Input: n = 5 m = 1 q = [[1, 3]] - Output: 4 # Constraints: - $1 \leq n \leq @data$ - $1 \leq l \leq r \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB ","[1000, 10000, 100000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","class Solution: def _prefix_ones(self, x: int) -> int: if x <= 0: return 0 total = 0 k = 0 while (1 << k) <= x: block = 1 << (k + 1) total += (x // block) * (1 << k) rem = x % block extra = rem - (1 << k) + 1 if extra > 0: total += extra k += 1 return total def solve1(self, n, m, q): ans = 0 for l, r in q: ans ^= self._prefix_ones(r) - self._prefix_ones(l - 1) return ans def solve2(self, n, m, q): ans = 0 for l, r in q: cnt = 0 for j in range(l, r + 1): cnt += j.bit_count() if hasattr(int, ""bit_count"") else bin(j).count(""1"") ans ^= cnt return ans ","import sys data = sys.stdin.buffer.read().split() it = iter(data) def next_int(): try: return int(next(it)) except StopIteration: return None n = next_int() m = next_int() pairs = [] while True: l = next_int() if l is None: break r = next_int() if r is None: break pairs.append([l, r]) actual_m = min(m if m is not None else 0, len(pairs)) q = pairs[:actual_m] solution = Solution() result = solution.solve(n, actual_m, q) sys.stdout.write(str(result) + ""\n"")",greedy,medium 440,"# Problem Statement Given an array $a$ of length $n$, return the count of the most frequently occurring element in the array. The main function of the solution is defined as: ```python class Solution: def solve(self, n, a): pass # write your code here``` where: - return: the count of the most frequently occurring element in the array. # Example 1: - Input: n = 5 a = [1, 2, 2, 3, 3] - Output: 2 # Constraints: - $1 \leq n \leq @data$ - $1 \leq a[i] \leq n$ - Time limit: @time_limit ms - Memory limit: @memory_limit KB","[20000, 200000, 2000000]",4000,"[[500, 64, 64], [4000, 400, 80], [32000, 3200, 640]]","import collections import math class Solution: def solve1(self, n, a): a.sort() ans = 0 pre = -1 cnt = 0 for i in range(n): if a[i] == pre: cnt += 1 else: ans = max(ans, cnt) cnt = 1 pre = a[i] ans = max(ans, cnt) return ans def solve2(self, n, a): cnt = [0] * (n + 1) for i in range(n): cnt[a[i]] += 1 return max(cnt) ","import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) a = [0] * n for i in range(0, n): a[i] = int(next(it)) solution = Solution() result = solution.solve(n, a) sys.stdout.write(str(result) + ""\n"")",sort,hard